我有一个每周导出到 CSV 的查询,其中包含与我的 Excel 数据表相同的标题和列顺序。 powershell 脚本将位于事件计时器上,我希望它能够抓取 CSV 并使用相应的标题将数据导入下一个可用单元格中。我不希望它覆盖现有数据,本质上它是一个不断增长的表。
环境:Powershell V3 w/ISE Steroids & Excel 2013
这是我当前不起作用的代码:
Add-Type -AssemblyName Microsoft.Office.Interop.Excel
$Excel = New-Object -ComObject Excel.Application
$xlLastCell = [Microsoft.Office.Interop.Excel.Constants]::xlLastCell
$xlFile = 'C:\Users\me\Desktop\Test\Agents Stats 2016.xlsx'
$csvFile = 'C:\Users\me\Desktop\Test\Data\AgentStats.csv'
$Excel.Visible = $true
$ExcelWordBook = $Excel.Workbooks.Open($xlFile)
$ExcelWorkSheet = $Excel.WorkSheets.item('rawdata')
$ExcelWorkSheet.activate()
$objRange = $ExcelWorkSheet.UsedRange
$lastRow = $objRange.SpecialCells($xlLastCell).Row
$ExcelWorkSheet.cells($lastRow,1).Select()
$AgentStats = Import-Csv -Path C:\Users\me\Desktop\Test\Data\AgentStats.csv
$AgentStats.foreach{
$lastRow += 1
$ExcelWorkSheet.cells($lastRow,1).value = $psitem.COUNT
$ExcelWorkSheet.cells($lastRow,2).value = $psitem.STATUS
$ExcelWorkSheet.cells($lastRow,3).value = $psitem.OPERATOR
$ExcelWorkSheet.cells($lastRow,4).value = $psitem.PRODUCT
$ExcelWorkSheet.cells($lastRow,5).value = $psitem.WEEK
}
$ExcelWordBook.Save()
$ExcelWordBook.Close()
$Excel.Quit()
我收到以下错误,但我不知道原因:
At line:19 char:20 + $AgentStats.foreach{ + ~ Unexpected token '{' in expression or statement. + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : UnexpectedToken
[16,1] Method invocation failed because [System.__ComObject] doesn't contain a method named 'cells'.
[21,3] Method invocation failed because [System.__ComObject] doesn't contain a method named 'cells'.
[22,3] Method invocation failed because [System.__ComObject] doesn't contain a method named 'cells'.
[23,3] Method invocation failed because [System.__ComObject] doesn't contain a method named 'cells'.
[24,3] Method invocation failed because [System.__ComObject] doesn't contain a method named 'cells'.
[25,3] Method invocation failed because [System.__ComObject] doesn't contain a method named 'cells'.
我在过去的一天中用谷歌搜索了这些错误,并且我用“Foreach”进行了愚弄,但没有成功。然而,“cells com 对象”是合法的并且确实存在,我一生都无法弄清楚为什么会发生该错误。
提前感谢您的帮助,我是 Powershell 新手。
最佳答案
1)您使用了错误的括号:
$AgentStats.foreach( #Not the squiggelies
$lastRow += 1
$ExcelWorkSheet.cells($lastRow,1).value = $psitem.COUNT
$ExcelWorkSheet.cells($lastRow,2).value = $psitem.STATUS
$ExcelWorkSheet.cells($lastRow,3).value = $psitem.OPERATOR
$ExcelWorkSheet.cells($lastRow,4).value = $psitem.PRODUCT
$ExcelWorkSheet.cells($lastRow,5).value = $psitem.WEEK
)
2)我认为你的对象声明不正确:
$ExcelWordBook = $Excel.Workbooks.Open($xlFile)
$ExcelWorkSheet = $ExcelWordbooks.item('rawdata') #here, use your excelwordbooks-object
$ExcelWorkSheet.activate() #Not necessary
关于excel - 使用 Powershell 将 CSV 数据插入 Excel 中下一个可用的相应单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36014867/