从.xlsm文件中删除工作表

时间:2014-02-10 17:39:50

标签: excel powershell etl

我正在尝试从.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

1 个答案:

答案 0 :(得分:0)

试试这个,对我有帮助:

$Excel = New-Object -ComObject Excel.Application
$workbook = $Excel.workbooks.add()
#working with sheets
$workbook.worksheets.item("Sheet1").Delete()