Powershell – Excel基于文件名重命名工作表

我有多个excel文件,我将它们合并到一个带有多个工作表的excel文档中。 我想重新命名这些表基于当前正在处理的文件名称。 码:

$files = Get-ChildItem "C:\Stuff\" -exclude "Pauls*" $DestFile = 'C:\Stuff\Pauls Weekly KPI.xlsx' # source's fullpath foreach($file in $files) { $baseName = [System.IO.Path]::GetFileNameWithoutExtension($file.fullname) Write-Host $baseName $xl = new-object -c excel.application $xl.displayAlerts = $false # don't prompt the user $wb1 = $xl.workbooks.open($file, $null, $true) # open source, readonly $wb2 = $xl.workbooks.open($DestFile) # open target $sh1_wb2 = $wb2.sheets.item(1) # first sheet in destination workbook $sheetToCopy = $wb1.sheets.item('Report') # source sheet to copy $sheetToCopy.copy($sh1_wb2) # copy source sheet to destination workbook $wb1.close($false) # close source workbook w/o saving $wb2.close($true) # close and save destination workbook } $xl.quit() spps -n excel 

示例:脚本运行后,最终的笔记本将包含多个以其原始文件名命名的工作表

通过在复制之前重命名表单来解决:

 $files = Get-ChildItem "C:\Stuff\" -exclude "Pauls*" $DestFile = 'C:\Stuff\Pauls Weekly KPI.xlsx' # source's fullpath $xl = new-object -c excel.application $xl.displayAlerts = $false # don't prompt the user foreach($file in $files){ $baseName = [System.IO.Path]::GetFileNameWithoutExtension($file.fullname) Write-Host $baseName $wb1 = $xl.workbooks.open($file, $null, $true) # open source, readonly $wb2 = $xl.workbooks.open($DestFile) # open target $sh1_wb2 = $wb2.sheets.item(1) # first sheet in destination workbook $sheetToCopy = $wb1.sheets.item('Report') # source sheet to copy $sheetToCopy.name = $baseName $sheetToCopy.copy($sh1_wb2) # copy source sheet to destination workbook $wb1.close($false) # close source workbook w/o saving $wb2.close($true) # close and save destination workbook } $xl.quit() spps -n excel