Read Excel sheet in Powershell

后端 未结 4 1297
有刺的猬
有刺的猬 2020-11-29 09:22

The below script reads the sheet names of an Excel document....

How could I improve it so it could extract all the contents of column B (starting from row 5 - so row

4条回答
  •  生来不讨喜
    2020-11-29 10:03

    This assumes that the content is in column B on each sheet (since it's not clear how you determine the column on each sheet.) and the last row of that column is also the last row of the sheet.

    $xlCellTypeLastCell = 11 
    $startRow = 5 
    $col = 2 
    
    $excel = New-Object -Com Excel.Application
    $wb = $excel.Workbooks.Open("C:\Users\Administrator\my_test.xls")
    
    for ($i = 1; $i -le $wb.Sheets.Count; $i++)
    {
        $sh = $wb.Sheets.Item($i)
        $endRow = $sh.UsedRange.SpecialCells($xlCellTypeLastCell).Row
        $city = $sh.Cells.Item($startRow, $col).Value2
        $rangeAddress = $sh.Cells.Item($startRow + 1, $col).Address() + ":" + $sh.Cells.Item($endRow, $col).Address()
        $sh.Range($rangeAddress).Value2 | foreach 
        {
            New-Object PSObject -Property @{ City = $city; Area = $_ }
        }
    }
    
    $excel.Workbooks.Close()
    

提交回复
热议问题