【问题标题】:How to make this script loop through all files in directory?如何使此脚本循环遍历目录中的所有文件?
【发布时间】:2014-12-30 04:12:09
【问题描述】:

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

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

我正在学习 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);

【问题讨论】:

  • 不要将问题用作输入此类信息的地方。如果其他用户遇到像您这样的问题,则更改您的问题会删除历史记录。如果需要,请在答案中添加感谢和其他信息作为评论。

标签: excel powershell


【解决方案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);

【讨论】:

  • Frode F.,我运行了您的代码,但没有任何反应。我什至没有收到错误。感谢您的快速回复!
  • Get-ChildItem -Path $scriptPath -Filter ".xlsb" 是否返回任何内容? (尝试在脚本中的某处添加它,并在之前和之后使用 Write-Host 消息,这样您就可以看到响应应该来自哪里。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-05
  • 1970-01-01
相关资源
最近更新 更多