Submitted By: Kent Finkle

Saves a worksheet as a comma-separated values file named C:\Scripts\Test.csv.

PowerShell
Edit|Remove
$comments = @'
Script name: Save-ExcelToCSV.ps1
Created on: Sunday, July 01, 2007
Author: Kent Finkle
Purpose: How can I use Windows Powershell to
Save a Single Excel Worksheet to a CSV File?
'@
#-----------------------------------------------------
function Release-Ref ($ref) {
([System.Runtime.InteropServices.Marshal]::ReleaseComObject(
[System.__ComObject]$ref) -gt 0)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers() 
}
#-----------------------------------------------------
$xlCSV = 6
 
$xl = new-object -comobject excel.application
$wb = $xl.Workbooks.Open("C:\Scripts\Testsheet.xls")
$xl.DisplayAlerts = $False
$xl.Visible = $True
 
$ws = $wb.Worksheets.Item("Sheet1")
$a = $ws.SaveAs("c:\scripts\test.csv", $xlCSV)
$a = $xl.Quit()
 
$a = Release-Ref($ws)
$a = Release-Ref($wb)
$a = Release-Ref($xl)