如何让这个脚本循环遍历目录中的所有文件?

时间:2014-12-27 15:04:06

标签: excel powershell

如何让这个脚本循环遍历目录中的所有文件?

我相信我是按照我想要的方式保存文件的,但我可以一次保存。

我正在学习Powershell ......

如何将工作簿(excel 2010)中的每个工作表保存为以下格式:文件名+" - " +工作表名称为CSV?

  • 在某些工作簿上,每个工作簿最多有3个工作表(可能更多......)
  • 是否有最佳方式执行此操作?

谢谢,

$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 + "\1B1195.xlsb");

   foreach($ws in $wb.Worksheets) {
    if($ws.name -eq "OP10" -or $ws.name -eq "OP20" -or $ws.name -eq "OP30") {
        Write-Host $ws.name;

   $ws.SaveAs($scriptPath + "\" + $wb.name + "-" + $ws.name + ".csv", [Object] [Microsoft.Office.Interop.Excel.XlFileFormat]::xlCSVMSDOS);

}
}

$wb.close($False)
$excel.Quit();
[void][System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel);

1 个答案:

答案 0 :(得分:1)

我没有测试过,但我认为它应该可行。我已经解释了代码中的变化:

$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;

#Find every xlsb file in $scriptpath. 
#If you want to search through subdirectories also, add " -Recurse" before "| Foreach-Object"
Get-ChildItem -Path $scriptPath -Filter ".xlsb" | ForEach-Object {

    #Inside this loop, $_ is the processed xlsb-file.
    #$_.Fullname includes the full path, like c:\test\myexcelfile.xlsb"

    #File-specific code
    $wb = $excel.Workbooks.Open($_.FullName);

    foreach($ws in $wb.Worksheets) {
        if($ws.name -eq "OP10" -or $ws.name -eq "OP20" -or $ws.name -eq "OP30") {
            Write-Host $ws.name;

            $ws.SaveAs($scriptPath + "\" + $wb.name + "-" + $ws.name + ".csv", [Object] [Microsoft.Office.Interop.Excel.XlFileFormat]::xlCSVMSDOS);
            }
    }

    $wb.close($False)
    #End file-specific code

}    

$excel.Quit();
[void][System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel);