Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

powershell - Get the Number of Rows in Column of a worksheet

I have an Excel sheet as follows:

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

I want to get the count of non-empty cells in each column, i.e.:

Column ID → 3 rows
Name → 1 row
Address → 2 rows

How do I do this in power shell? I tried various things but they don't seem to work.

I am new to PowerShell. Is there a way to get the number of rows for a column directly?

$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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try something like this:

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

$wb = $xl.Workbooks.Open("C:pathoyour.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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...