2
我正在从Excel电子表格读取大量格式的某些文本。当我做下面的事情时,一切正常。作为参数传递时值为空
Function Read-From-Excel {
Param(
[string]$fileName,
[string]$sheetName="Sheet1"
)
$excelObject = New-Object -ComObject Excel.Application
$excelObject.Visible = $FALSE
$excelBook = $excelObject.Workbooks.Open($fileName)
$excelSheet = $excelBook.Sheets.Item($sheetName)
$intRowMax = ($excelSheet.UsedRange.Rows).count
$col = 1
$row = 1
$headers= @()
While ($TRUE) {
$column = $excelSheet.cells.Item($row, $col).Text
If ($column -eq "") {
Break
}
$headers += $column
$col ++
}
$text = ""
For ($row = 2; $row -le $intRowMax; $row++) {
# Wrapped in another function starting here
$cell = $excelSheet.cells.Item($row, 1).Text
If ($cell.StartsWith("#")) {
$text += "-- {0}`n" -f $cell.substring(1)
} Else {
$c1 = $cell
$c2 = $excelSheet.cells.Item($row, 2).Text -creplace '\s+', ''
$c3= $excelSheet.cells.Item($row, 3).Text -creplace '\s+', ''
$c4 = $excelSheet.cells.Item($row, 4).Text
$c5 = $excelSheet.cells.Item($row, 5).Text
$text += Format-Row $c1 $c2 $c3 $c4 $c5
}
# Until here
}
Write-Host $headers
Write-Host $text
$excelObject.quit()
}
当我包裹内部分的功能,但是,我得到的错误:
You cannot call a method on a null-valued expression.
At C:\Users\dannnno\desktop\FormatFromExcel.ps1:311 char:27
+ $cell = $excelSheet.cells.Item <<<< ($row, 1).Text
+ CategoryInfo : InvalidOperation: (Item:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
这个功能看起来像这样
Function _Get-Next-Block-Excel-File {
Param(
[Object[]]$sheet,
[int]$row
)
# This is all the same, except with the name changed to $sheet
}
和原代码有内部部分改为看起来像
$text += _Get-Next-Block-Excel-File $excelSheet $row
是否有一种特殊的方式需要在PowerShell中传递此参数?
围绕'For($ row = 2; $ row -le $ intRowMax; $ row ++){'循环在循环前是否会获取该异常? – Kev
我不能重复这个。我建议在PowerShell ISE或PowerGUI中运行此操作并在该行上设置断点以查看发生了什么。另外你不需要一个Object []'数组作为'Function _Get-Next-Block-Excel-File'中的第一个参数,'[Object] $ sheet'将会正常工作,因为你没有传递一个数组表功能。 – Kev
另外,你的源数据导致这个呛的样本将是有用的,我怀疑它是在那里。最后需要注意的是,你还应该在'_Get-Next-Block-Excel-File'函数中使'$ text'专用,否则它会在调用函数中破坏'$ text'。请参阅:http://powershell.com/cs/blogs/tips/archive/2010/10/18/working-with-private-variables.aspx – Kev