【问题标题】:Copy AND Overwrite to destination Excel Worksheet from one Workbook to another with Powershell使用 Powershell 将目标 Excel 工作表从一个工作簿复制并覆盖到另一个工作簿
【发布时间】:2014-03-05 12:07:12
【问题描述】:

我的请求与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)

【问题讨论】:

    标签: powershell etl


    【解决方案1】:

    看来你需要重命名目标表,粘贴替换,然后删除目标。

    $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
    

    【讨论】:

    • 由于某种原因,$sh1_wb1.Delete() 没有成功删除重命名的工作表。
    • 嗯,该代码在我的机器上运行良好,复制并粘贴到 PowerShellISE 并使用放置在 C:\Path\ 中的几个虚拟测试电子表格运行。你得到一个错误或什么?您正在运行哪个版本的 Excel?什么版本的 PowerShell?
    • 是的,这很奇怪... Excel 2010 .xlsm 文件(启用宏)和 PowerShell 2.0
    • 您可能只想逐步完成代码,并在您转到$xl.visible=$true 时将 Excel 设置为可见以观察会发生什么。也许尝试从 PS 或其他东西中手动发出删除命令。
    猜你喜欢
    • 2011-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-18
    • 2014-12-09
    • 1970-01-01
    • 2021-06-16
    相关资源
    最近更新 更多