【发布时间】:2014-05-02 21:46:47
【问题描述】:
编辑:忽略 - 由于某些代码超出了此脚本的范围,这实际上是这种行为。我的错。我刚刚提交了关闭此帖子的请求。
我有一个简单的 PowerShell 脚本,它应该从 Excel .xls 文件中删除第一行。
我的脚本如下:
$file = $args[0]
# Start Excel, hide window
$excel = new-object -com Excel.Application -Property @{Visible = $false}
$workbook = $excel.Workbooks.Open($file) # Open the file
$workbook.CheckCompatibility = $False
$sheet = $workbook.Sheets.Item("Acutal Worksheet") # Select appropriate worksheet
[void]$sheet.Cells.Item(1, 1).EntireRow.Delete() # Delete the first row
$workbook.Close($true) # Close workbook and save changes
$excel.quit() # Quit Excel
[Runtime.Interopservices.Marshal]::ReleaseComObject($excel) # Release COM
当我运行这个时,PoSh 脚本完成干净,但是当我打开工作簿时,我注意到前 两 行已被删除。我只想删除第一行。
现在,当我使用工作簿中不存在的工作表名称运行脚本时,脚本会引发以下错误当我打开工作簿时,只有第一行有已从目标工作表中删除。 注意:工作簿中只有一个工作表。它正在产生我想要的结果,但这很丑陋,我需要实现一些对我有意义的东西。当我指定正确的工作表名称时,需要进行哪些更改才能使其正常工作?
工作簿中不存在名称的脚本示例:
$file = $args[0]
# Start Excel, hide window
$excel = new-object -com Excel.Application -Property @{Visible = $false}
$workbook = $excel.Workbooks.Open($file) # Open the file
$workbook.CheckCompatibility = $False
$sheet = $workbook.Sheets.Item("WRONG_NAME") # Select appropriate worksheet
[void]$sheet.Cells.Item(1, 1).EntireRow.Delete() # Delete the first row
$workbook.Close($true) # Close workbook and save changes
$excel.quit() # Quit Excel
[Runtime.Interopservices.Marshal]::ReleaseComObject($excel) # Release COM
我从运行这个得到的错误:
Exception getting "Item": "Invalid index. (Exception from HRESULT: 0x8002000B (
DISP_E_BADINDEX))"
At I:\path\ps_myScript.ps1:10 char:35
+ $sheet = $workbook.Sheets.Item <<<< ("WRONG_NAME") # Select appropriate works
heet
+ CategoryInfo : NotSpecified: (:) [], GetValueInvocationExceptio
n
+ FullyQualifiedErrorId : CatchFromBaseAdapterParameterizedPropertyGetValu
eTI
You cannot call a method on a null-valued expression.
At I:\path\ps_myScript.ps1:11 char:28
+ [void]$sheet.Cells.Item <<<< (1, 1).EntireRow.Delete() # Delete the first
row
+ CategoryInfo : InvalidOperation: (Item:String) [], RuntimeExcep
tion
+ FullyQualifiedErrorId : InvokeMethodOnNull
【问题讨论】:
-
很遗憾,我无法重现该问题。当我尝试时,您的代码对我来说运行良好。以下是带有前后屏幕的图像链接:Imgur 但是,
Delete方法接受一个参数来决定如何移动和替换已删除的单元格。 documentation 说,if this argument is omitted, Microsoft Excel decides based on the shape of the range.,所以我想知道这是否是您所面临问题的原因。 -
这个问题似乎离题了,因为它实际上是由 powershell 脚本范围之外的错误代码引起的问题。
标签: excel powershell etl