使用Powershell将目标Excel工作表从一个工作簿复制并覆盖到另一个工作簿

时间:2014-02-07 22:01:53

标签: powershell etl

我的请求与this post中的请求非常相似,但区别在于:我想覆盖目标Excel文件中现有工作表的内容。

代码(来自链接帖子的精确副本;但为方便起见粘贴在此处)如下:

$file1 = 'C:\path\file1.xls' # source's fullpath
$file2 = 'C:\path\file2.xls' # destination's fullpath

$xl = new-object -c excel.application
$xl.displayAlerts = $false # don't prompt the user
$wb2 = $xl.workbooks.open($file1, $null, $true) # open source, readonly
$wb1 = $xl.workbooks.open($file2) # open target
$sh1_wb1 = $wb1.sheets.item('MyWorksheet') # second sheet in destination workbook
$sheetToCopy = $wb2.sheets.item('MyWorksheet') # source sheet to copy

$sheetToCopy.copy($sh1_wb1)  # copy source sheet to destination workbook

$wb2.close($false) # close source workbook w/o saving
$wb1.close($true) # close and save destination workbook
$xl.quit()
spps -n excel

需要更改的行是:

$sheetToCopy.copy($sh1_wb1) # copy source sheet to destination workbook

您能否告诉我如何重写上述内容,以便它不会在目标Excel文档中创建新的工作表?现在,它不是覆盖MyWorksheet而是创建副本:MyWorksheet (2)

1 个答案:

答案 0 :(得分:0)

似乎你需要的是重命名目标表,粘贴替换,然后删除目标。

$file1 = 'C:\path\file1.xls' # source's fullpath
$file2 = 'C:\path\file2.xls' # destination's fullpath

$xl = new-object -c excel.application
$xl.displayAlerts = $false # don't prompt the user
$wb2 = $xl.workbooks.open($file1, $null, $true) # open source, readonly
$wb1 = $xl.workbooks.open($file2) # open target
$sh1_wb1 = $wb1.sheets.item('MyWorksheet') # second sheet in destination workbook
$sheetToCopy = $wb2.sheets.item('MyWorksheet') # source sheet to copy

$sh1_wb1.Name = "DeleteMe$(get-date -Format hhmmss)" #Extremely unlikely to be a duplicate name
$sheetToCopy.copy($sh1_wb1)  # copy source sheet to destination workbook
$sh1_wb1.Delete()

$wb2.close($false) # close source workbook w/o saving
$wb1.close($true) # close and save destination workbook
$xl.quit()
spps -n excel