0

I have an excel file with dynamic rows volume, what I want to achieve that to keep only the first 50'000 rows of the file and delete the rest, so if the file has 325,000 then keep the first 50,000 and delete the other 275,000 rows.

Any idea how to do this? I know that this is a novice question, but I don't know how to start with that.

1
  • Import-Excel file1.xlsx -StartRow 1 -EndRow 50000 | Export-Excel file2.xlsx Commented Apr 22, 2021 at 13:31

1 Answer 1

1

Just tested this. It will delete the rows on each sheet, but will fail if the Excel file is already open.

$FilePath = 'C:\Users\Andrew\Documents\DeleteRows.xlsx' #Change path to suit

$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $false
$Excel.DisplayAlerts = $false
$File = $Excel.Workbooks.Open($FilePath)

ForEach($ws in $File.Worksheets)
{

    $ws.Range($ws.Rows(50001),$ws.Rows($ws.Rows.Count)).Delete()

}

$File.Save()
$File.Close()
$Excel.Quit()


[System.Runtime.Interopservices.Marshal]::ReleaseComObject($ws)
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($File)
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.