获取工作表的列数

时间:2013-06-05 10:40:47

标签: powershell

我有一张Excel表格如下:

Id   Name   Address
-------------------
1    t1     Add1
2           Add2
3

我想得到每列中非空单元格的数量,即:

  

列ID→3行
  名称→1行
  地址→2行

我如何在电源外壳中执行此操作?我尝试了各种各样的东西,但似乎没有用。

我是PowerShell的新手。有没有办法直接获取列的行数?

$SheetName = "Sheet1"
$Excel = New-Object -ComObject "Excel.Application"

$Workbook = $Excel.workbooks.open($XLSDoc)
$Sheet = $Workbook.Worksheets.Item($SheetName)
$objRange = $Sheet.UsedRange
$RowCount = $objRange.Rows.Count
$ColumnCount = $objRange.Columns.Count
Write-Host "RowCount:" $RowCount
Write-Host "ColumnCount" $ColumnCount
$Range1 = $Sheet.Range("A1:A5")
$TestCount = $Range1.Rows.Count
Write-Host $TestCount

1 个答案:

答案 0 :(得分:7)

尝试这样的事情:

$xl = New-Object -COM "Excel.Application"
$xl.Visible = $true

$wb = $xl.Workbooks.Open("C:\path\to\your.xlsx")
$ws = $wb.Sheets.Item(1)

$rows = $ws.UsedRange.Rows.Count

foreach ( $col in "A", "B", "C" ) {
  $xl.WorksheetFunction.CountIf($ws.Range($col + "1:" + $col + $rows), "<>") - 1
}

$wb.Close()
$xl.Quit()