Skip to content

Instantly share code, notes, and snippets.

@yzorg
Created August 20, 2019 19:16
Show Gist options
  • Save yzorg/5fec32dcc475a4681d77a00750cac49a to your computer and use it in GitHub Desktop.
Save yzorg/5fec32dcc475a4681d77a00750cac49a to your computer and use it in GitHub Desktop.
my take on convert .xlsx to .CSV in Powershell using Excel COM (Windows only)
$step = ''
function CustomConvert-XlsxToCsv
{
param(
[Parameter(Mandatory)]$XlsxFile,
[string]$Sheet = 'Sheet1',
[string]$CsvFile,
[switch]$Test
)
$script:step = "init variables";
$filebase = [System.IO.Path]::GetFileNameWithoutExtension($XlsxFile);
$dataDir = $PWD.Path;
if ([System.IO.Path]::IsPathRooted($XlsxFile))
{
$dataDir = Split-Path -Parent $XlsxFile;
}
else {
$XlsxFile = Join-Path $dataDir $XlsxFile;
}
if ($CsvFile -eq '') {
$CsvFile = "$dataDir\$filebase.csv";
}
elseif (-not [System.IO.Path]::IsPathRooted($CsvFile))
{
$CsvFile = Join-Path $dataDir $CsvFile;
}
$script:step = "create COM automation object: New-Object -ComObject Excel.Application";
if ($Test) {
[void]($objExcel = $global:objExcelConvertXlsx);
if (!($objExcel)) { throw 'create $global:objExcelConvertXlsx before running in test mode' }
}
else {
[void]($objExcel = New-Object -ComObject Excel.Application);
$objExcel.Visible = $false;
}
$script:step = "opening: objExcel.Workbooks.Open($XlsxFile)"
[void]($workbook = $objExcel.Workbooks.Open($XlsxFile));
if ($Test) { $workbook.sheets | Select-Object -ExpandProperty Name; }
[void]($worksheet = $workbook.sheets.item($Sheet));
if (Test-Path $CsvFile) { del $CsvFile -Verbose:$Test; }
$script:step = "Saving --$CsvFile--";
$worksheet.SaveAs($CsvFile, [Microsoft.Office.Interop.Excel.XlFileFormat]::xlCSVWindows);
Write-Warning "Saved --$CsvFile--";
# .NET enums are auto-converted, but looks like COM enums are not. This doesn't work:
# $worksheet.SaveAs("$dataDir\$filebase.csv", 'xlCSVWindows')
if ($Test) { return; }
$script:step = "cleanup";
$objExcel.Quit();
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($objExcel);
Remove-Variable objExcel;
}
try {
#cd C:\code\archive\2019-project1\hours
#CustomConvert-XlsxToCsv -XlsxFile AppSchedule.xlsx # exports Sheet1
#CustomConvert-XlsxToCsv -XlsxFile AppSchedule.xlsx -Sheet exceptions -CsvFile AppSchedule-Exceptions.csv
CustomConvert-XlsxToCsv -Sheet schedules -XlsxFile C:\code\archive\2019-project1\hours\AppSchedule.xlsx
}
catch {
Write-Warning "last step before error: $step";
}
#finally {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment