PowerShell:将Excel工作表导出为CSV

时间:2014-01-09 03:24:53

标签: excel powershell csv

我想出了如何使用PowerShell for excel 2007导出工作簿的所有工作表作为csv。我遇到的问题是脚本随机导出相同的工作表2x。有时它会像它应该创建3个单独的csv文件,有时其中一个csv文件是另一个的副本。 但它始终打印:

A
B
C

以下是代码:

$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
Add-Type -AssemblyName Microsoft.Office.Interop.Excel

$excel = new-object -ComObject "Excel.Application";
$excel.DisplayAlerts=$True;
$excel.Visible =$false;
$wb = $excel.Workbooks.Open($scriptPath + "\file.xlsx");
foreach($ws in $wb.Worksheets) {
    if($ws.name -eq "A" -or $ws.name -eq "B" -or $ws.name -eq "C") {
        Write-Host $ws.name;
        $ws.SaveAs($scriptPath + "\" + $ws.name + ".csv", [Object] Microsoft.Office.Interop.Excel.XlFileFormat]::xlCSVMSDOS);
}
}
$wb.close($False)
$excel.Quit();
[void][System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel);

在Windows 7 x64,Excel 2007 SP2上运行

0 个答案:

没有答案