从.xlsm文件中删除工作表

问题描述 投票:1回答:1

我试图从.xlsm文件中删除一个命名的工作表。

我按照here发布的示例,但它不适合我。当我打开.xlsm文件以检查工作表是否已被删除时,它仍然存在。

这是我的代码:

$file2 = 'c:\file.xlsm' # destination's fullpath

$xl = new-object -c excel.application
$xl.displayAlerts = $false # don't prompt the user

$wb2 = $xl.workbooks.open($file2) # open target

$sh2_wb2 = $wb2.sheets | where {$_.name -eq "myWorksheet"}
$sh2_wb2.delete() #Delete original sheet in template

$wb2.close($true) # close and save destination workbook
$xl.quit()
spps -n excel

我究竟做错了什么?

编辑:

我更改了我的代码,使Excel对象在打开时可见。然后我注意到delete调用正在发送,但它要求用户确认删除是否应该发生:Data may exist in the sheet(s) selected for deletion. To permanently delete the data, press Delete.

然后我尝试在我的代码中添加一些displayAlerts = $false,但它仍然给了我那个提示。

这是我更新的代码,虽然它仍然不起作用。

$file2 = 'c:\file.xlsm' # destination's fullpath

$xl = new-object -com excel.application -Property @{Visible = $true}
$xl.displayAlerts = $false # don't prompt the user

$wb2 = $xl.workbooks.open($file2) # open target
$wb2.displayAlerts = $false # don't prompt the user

$sh2_wb2 = $wb2.sheets | where {$_.name -eq "myWorksheet"}
$sh2_wb2.displayAlerts = $false # don't prompt the user
$sh2_wb2.delete() #Delete original sheet in template

$wb2.close($true) # close and save destination workbook
$xl.quit()
spps -n excel
excel powershell etl
1个回答
0
投票

试试这个,它对我的​​帮助:

$Excel = New-Object -ComObject Excel.Application
$workbook = $Excel.workbooks.add()
#working with sheets
$workbook.worksheets.item("Sheet1").Delete()
© www.soinside.com 2019 - 2024. All rights reserved.