Avatar of dann47
dann47
 asked on

Powershell Excel Question

i All. I have a script that brings in an excel workbook and exports to CSV. Problem is, i want this to hit multiple workbooks in excel, starting from

$oWorksheet = $oExcelDoc.Worksheets.item(7)

And going to the end

How can i achive this? Code below

$sExcelFile="C:\WindowsPatching_Reference_2016.xlsx"
$sCSVFile="C:\temp\$wksname.csv"
#$SheetName = "WinA-Test_Thu"

# Get COM Object
$oExcel = New-Object -ComObject "Excel.Application"
# Should Excel be visible?
$oExcel.Visible = $true
# and open excel file
$oExcelDoc = $oExcel.Workbooks.Open($sExcelFile)

# Open Worksheet
#$oWorkSheet = $oExcelDoc.sheets.item($SheetName)
$oWorksheet = $oExcelDoc.Worksheets.item(7)
#Get Sheet Name
$Name = $oworksheet.name
# Activate, show it
$oWorksheet.Activate()

$oExcelDoc.SaveAs($sCSVFile,[Microsoft.Office.Interop.Excel.XlFileFormat]::xlCSVWindows)

$oExcelDoc.Close($false)
Start-Sleep 1
# Cleanup COM
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($oWorksheet)|out-null
$oWorksheet=$null
Start-Sleep 1
# Cleanup COM
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($oExcelDoc)|out-null
$oExcelDoc=$null
# Close Excel
$oExcel.Quit()
Start-Sleep 1
# Cleanup COM
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($oExcel)|out-null
$oExcel=$null
[GC]::Collect()
[GC]::WaitForPendingFinalizers()

Open in new window

Powershell

Avatar of undefined
Last Comment
dann47

8/22/2022 - Mon
Rainer Jeschor

Hi,
if your code is currently working, then the following loop should then export all sheets until the end starting with sheet number 7:

for ($counter = 7; $counter -le $oExcelDoc.Worksheets.count; $counter++) {
$oWorksheet = $oExcelDoc.Worksheets.item(7)
#Get Sheet Name
$Name = $oworksheet.name
# Activate, show it
$oWorksheet.Activate()
$sCSVFile="C:\temp\$wksname$counter.csv"
$oExcelDoc.SaveAs($sCSVFile,[Microsoft.Office.Interop.Excel.XlFileFormat]::xlCSVWindows)
}

Open in new window


I just added the counter to the filename, otherwise the file would always be overwritten.

HTH
Rainer
dann47

ASKER
Hi many thanks, where would this sit in line with the code please?
Also, the code used to get the name of the sheet and call it that name.
Also, how can i force it to overwrite the file?

Many thanks
ASKER CERTIFIED SOLUTION
Rainer Jeschor

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
dann47

ASKER
Fantastic, many thanks
Your help has saved me hundreds of hours of internet surfing.
fblack61