Skip to content

Instantly share code, notes, and snippets.

@joerodgers
Last active September 26, 2017 17:16
Show Gist options
  • Save joerodgers/aaa7a81c7edcf3f71473b4c9053b9a5d to your computer and use it in GitHub Desktop.
Save joerodgers/aaa7a81c7edcf3f71473b4c9053b9a5d to your computer and use it in GitHub Desktop.
Export Excel Worksheet to CSV
function ConvertTo-CsvFromExcelWorksheet
{
[cmdletbinding()]
param
(
[Parameter(Mandatory=$true)][string]$ExcelFilePath,
[Parameter(Mandatory=$true)][string]$CsvFilePath,
[Parameter(Mandatory=$false)][string]$Worksheet = "Sheet1"
)
begin
{
$xlCSV = 6
$ExcelApplication = New-Object -ComObject Excel.Application
}
process
{
if( $ExcelApplication )
{
$ExcelApplication.Visible = $false
$ExcelApplication.DisplayAlerts = $false
$workbook = $ExcelApplication.Workbooks.Open($ExcelFilePath)
try
{
$workbook.Worksheets($Worksheet).SaveAs( $CsvFilePath, $xlCSV )
}
catch
{
Write-Error "Failed to save worksheet '$Worksheet'. Error: $($_.Exception)"
}
}
else
{
Write-Error -Message "Microsoft Excel could not be opened, please make sure that Microsoft Excel is installed on the local machine."
}
}
end
{
if( $ExcelApplication )
{
$ExcelApplication.Quit()
}
}
}
ConvertTo-CsvFromExcelWorksheet -ExcelFilePath "C:\_temp\Excel.xlsx" -CsvFilePath "C:\_temp\data.csv"
ConvertTo-CsvFromExcelWorksheet -ExcelFilePath "C:\_temp\Excel.xlsx" -CsvFilePath "C:\_temp\data.csv" -Sheet "Sheet1"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment