Delete first four rows in Excel with Powershell

与世无争的帅哥 提交于 2019-12-22 04:33:30

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/16285428/delete-first-four-rows-in-excel-with-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!