使用Powershell在Excel中删除前四行 [英] Delete first four rows in Excel with Powershell
本文介绍了使用Powershell在Excel中删除前四行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
解决方案
不要使用OleDB从Excel文档中删除数据。根据 MSDN docmentation:
尽管Jet OLE DB提供程序允许您在Excel工作簿中插入和更新
记录,但它不允许DELETE操作
您可以使用Exel的COM界面删除行。记住要发布COM 对象。像这样,
$ file = c:\temp\MyExcelFile.xls
#Star Excel,隐藏窗口
$ excel = new-object -com Excel.Application -Property @ {Visible = $ false}
$ workbook = $ excel.Workbooks.Open($ file)#打开文件
$ sheet = $ workbook.Sheets.Item(1)#激活第一个工作表
[void] $ sheet.Cells.Item(1,1).EntireRow.Delete()#删除第一行
$ workbook.Close($ true)#关闭工作簿并保存更改
$ excel.quit()#退出Excel
[Runtime.Interopservices.Marshal] :: ReleaseComObject($ excel)#Release COM
I have a powershell script that opens an excel file, re-assigns a blank password, and then saves the file. I want to add a task to the script to remove the first 4 rows of the excel file before saving it.
解决方案
You can't use OleDB for deleting data from Excel document. As per MSDN docmentation:
Although the Jet OLE DB Provider allows you to insert and update records in an Excel workbook, it does not allow DELETE operation
What you can do is use Exel's COM interface to delete rows. Remember to release COM object too. Like so,
$file = c:\temp\MyExcelFile.xls
# Star Excel, hide window
$excel = new-object -com Excel.Application -Property @{Visible = $false}
$workbook = $excel.Workbooks.Open($file) # Open the file
$sheet = $workbook.Sheets.Item(1) # Activate the first worksheet
[void]$sheet.Cells.Item(1, 1).EntireRow.Delete() # Delete the first row
$workbook.Close($true) # Close workbook and save changes
$excel.quit() # Quit Excel
[Runtime.Interopservices.Marshal]::ReleaseComObject($excel) # Release COM
这篇关于使用Powershell在Excel中删除前四行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文