作为参数传递时,值为null

时间:2015-05-28 16:05:45

标签: excel powershell com

我正在从excel电子表格中读取大量格式化文本。当我做以下事情时,一切正常。

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<div id="grid" class="clearfix row">
  <a class="col-xs-4 align-center" href="#">
    <div>1</div>
  </a>
  <a class="col-xs-4 align-center" href="#">
    <div>2</div>
  </a>
  <a class="col-xs-4 align-center" href="#">
    <div>3</div>
  </a>
  <a class="col-xs-4 align-center" href="#">
    <div>4</div>
  </a>
  <a class="col-xs-4 align-center" href="#">
    <div>5</div>
  </a>
  <a class="col-xs-4 align-center" href="#">
    <div>6</div>
  </a>
  <a class="col-xs-4 align-center" href="#">
    <div>7</div>
  </a>
  <a class="col-xs-4 align-center" href="#">
    <div>8</div>
  </a>
  <a class="col-xs-4 align-center" href="#">
    <div>9</div>
  </a>
</div>

然而,当我在函数中包装内部部分时,我收到错误:

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
}

我有必要在PowerShell中传递此参数吗?

1 个答案:

答案 0 :(得分:2)

您不需要Object[]数组作为Function _Get-Next-Block-Excel-File中的第一个参数,[Object]$sheet会很好,因为您没有将一系列工作表传递给功能。