【发布时间】:2026-02-09 17:25:02
【问题描述】:
我在使用 powershell 时遇到了一个奇怪的问题。我还有其他脚本类似于在整个脚本中多次使用的行上引发错误的脚本。
我正在使用get-content 来获取 CSV 文件。然后我开始解析这些数据,只选择某些列并将它们输出到 excel 中。这是我的一个问题发生的地方......
这是非常不一致的,但是在解析 csv 的某个时间点我得到了这个错误
Exception setting "Item": "Call was rejected by callee. (Exception from HRESULT: 0x80010001 (RPC_E_CALL_REJECTED))"
在这一行上,用于将数据输出到excel中的特定列和行。
$excel.Cells.Item <<<< ($rowMonth, $columnMonth) = "$item"
我注意到,如果我在解析数据时按住滚动条,我会忽略此错误。我还注意到它几乎每次都停在不同的位置(提供或获取一些数据单元格),或者有时我根本没有收到错误。
在每次插入失败后我立即收到此错误
Assignment failed because [System.__ComObject] doesn't contain a settable property 'Item()'.
...直到我在脚本的解析部分完成错误。
我已尝试用 Google 搜索这些错误,但关于 PowerShell 和 Excel 的信息已经很少,我很难找出问题所在(第 3 天..)
我还有 4 个运行这行代码的其他脚本..
$excel.Cells.Item($rowNumber, $column) = "$item"
他们从来没有告诉我这个错误。
一旦我的解析完成(如果它在那里,我在尝试调试并按住滚动条时作弊)我在这里有这一行,我用它来切换到 Excel 中的另一个工作表,它会出错每次都在这里。
$sheet2 = $workBook.WorkSheets.Item($sheetName2).Select()
还给了我我发布的第一个错误..而且当我在解析一半时确实收到错误时,一旦出错,excel要求我将书设置为读/写(......再次......只是有时.....)。
这可能是什么问题,为什么如此不一致?会不会是内存限制? (我在 CSV 中解析的数据比我在脚本中解析的数据多,并且从未遇到过这个问题)
请帮忙!
这是我创建 excel 对象的方式。
#Create an instance of Excel
$excel = New-Object -comobject Excel.Application
#declaring sheet names
$sheetName = "some sheet name"
#open Excel file
[string]$file = "C:\Users\Desktop\excel-file.xlsx"
$workBook = $excel.Workbooks.open($file)
$workBook.WorkSheets.Item($sheetName).activate()
$excel.Visible = $true
$excel.displayAlerts = $false
这是我输出到 excel 的地方:
#Declaring variables
$i = 0
$rowNumber = 2
$rowMonth = 2786
$data1 = Get-Content $file1
foreach($row in $data1){
if($row){
$line = $row.Split(",")
$i++
#reset back to the first column once there is no more data for that row
$column = 1
$columnMonth = 7
$dataColumn = 0
if($i -ge 1){
foreach($item in $line){
$dataColumn++
if($dataColumn -eq 1 -or $dataColumn -eq 2 -or $dataColumn -eq 5 -or $dataColumn -eq 7){
$excel.Cells.Item($rowNumber, $column) = "$item"
$excel.Cells.Item($rowMonth, $columnMonth) = "$item"
$column++
$columnMonth++
}#endif
}#end foreach
$rowNumber++
$rowMonth++
}#end if $i
}#end if $row
}#end foreach
【问题讨论】:
-
当您尝试向其中插入项目时,您的 Excel 文件是否打开?
-
您的
$excel对象是什么,您是如何创建它的?另外,为什么需要切换到另一个工作表?你应该只做$sheet2 = $workBook.WorkSheets.Item(2)和$sheet2.Name = $sheet2name...调用$sheet2.cells.item($row,$col) = $item将为你“切换”工作表 -
我正在切换到另一个工作表来更新图表标题。
标签: excel powershell