Powershell - Excel根据文件名重命名工作表

时间:2014-09-17 00:53:19

标签: excel powershell

我有多个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

实施例:    脚本运行后,最终的笔记本将包含由其原始文件名

命名的多个工作表

1 个答案:

答案 0 :(得分:1)

通过在复制之前重命名工作表来解决它:

$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