【问题标题】:Powershell - Excel Rename Worksheets base upon filenamePowershell - Excel 根据文件名重命名工作表
【发布时间】:2014-09-17 00:53:18
【问题描述】:

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

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

【问题讨论】:

  • " 我想根据当前正在处理的文件名称重命名这些工作表。" ....如...我需要帮助

标签: excel powershell


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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-25
    • 1970-01-01
    • 1970-01-01
    • 2015-08-06
    • 1970-01-01
    相关资源
    最近更新 更多