Last active
September 26, 2017 17:16
-
-
Save joerodgers/aaa7a81c7edcf3f71473b4c9053b9a5d to your computer and use it in GitHub Desktop.
Export Excel Worksheet to CSV
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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