Delete first four rows in Excel with Powershell

I have a powershell script that opens an excel file, reassigns an empty password and then saves the file. I want to add a task to a script to delete the first 4 lines of an excel file before saving.

+5
source share
1 answer

You cannot use OleDB to delete data from an Excel document. According to MSDN docmentation:

Although the Jet OLE DB provider allows you to insert and update records in an Excel workbook, it does not allow you to work with DELETE

What you can do is use the Exel COM interface to delete lines. Remember to release COM . In this way,

$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
+5
source

All Articles