2014-12-27 98 views
1

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

我相信我能按照自己想要的方式保存文件,但我可以一次做到这一点。

我学习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); 
+0

请勿将该问题用作放置此类信息的地方。如果其他用户遇到像您这样的问题,请更改您的问题以删除历史记录如果需要,请在答案中提供感谢信息和其他信息作为评论。 – Matt 2014-12-29 20:13:16

回答

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); 
+0

弗罗德F.,我跑你的代码,但没有任何反应。我甚至没有出现错误。感谢您的快速回复! – HGtez 2014-12-27 16:46:48

+0

'Get-ChildItem -Path $ scriptPath -Filter“.xlsb”'返回任何内容吗? (尝试在脚本的某个位置添加一个'Write-Host'消息,以便您可以看到响应应该发生的位置。 – 2014-12-27 23:16:10

相关问题