Created
February 15, 2023 05:43
-
-
Save aruku7230/383f841cfbb7d79bdea7c7824fbb5b59 to your computer and use it in GitHub Desktop.
Use Powershell to Export Excel 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
# Export Excel sheet to CSV file | |
# $File: file path | |
# $SheetNames: An array, sheet names to export. | |
Function Export-ExcelToCsv ($File, $SheetNames) { | |
$Excel = New-Object -ComObject Excel.Application | |
# SaveAs will overwrite existing file | |
$Excel.Application.DisplayAlerts = $False | |
$wb = $Excel.Workbooks.Open($File) | |
$x = $File | Select-Object Directory, BaseName | |
foreach ($ws in $wb.Worksheets) { | |
# -1 is for xlSheetVisible | |
if (($SheetNames -contains $ws.Name) -and ($ws.Visible -eq -1)) { | |
$baseName = ($x.BaseName, $ws.Name) -join "_" | |
$n = [System.IO.Path]::Combine($x.Directory, (($baseName, 'csv') -join ".")) | |
# 62: xlCSVUTF8 (UTF8 CSV) | |
$ws.SaveAs($n, 62) | |
} | |
} | |
$Excel.Quit() | |
} | |
$FilePatterns = @("*.xlsx", "*.xlsm", "*.xml") | |
$SheetNames = @("a", "b") | |
Get-ChildItem -Path .\* -Include $FilePatterns | | |
ForEach-Object { | |
Export-ExcelToCsv -File $_ -SheetNames $SheetNames | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment