Read Excel sheet in Powershell

后端 未结 4 1295
有刺的猬
有刺的猬 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:08

    Sorry I know this is an old one but still felt like helping out ^_^

    Maybe it's the way I read this but assuming the excel sheet 1 is called "London" and has this information; B5="Marleybone" B6="Paddington" B7="Victoria" B8="Hammersmith". And the excel sheet 2 is called "Nottingham" and has this information; C5="Alverton" C6="Annesley" C7="Arnold" C8="Askham". Then I think this code below would work. ^_^

    $xlCellTypeLastCell = 11 
    $startRow = 5
    
    $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
            $col = $col + $i - 1
            $city = $wb.Sheets.Item($i).name
            $rangeAddress = $sh.Cells.Item($startRow, $col).Address() + ":" + $sh.Cells.Item($endRow, $col).Address()
            $sh.Range($rangeAddress).Value2 | foreach{
                New-Object PSObject -Property @{City = $city; Area=$_}
            }
        }
    
    $excel.Workbooks.Close()
    

    This should be the output (without the commas):

    City, Area
    ---- ----
    London, Marleybone
    London, Paddington
    London, Victoria
    London, Hammersmith
    Nottingham, Alverton
    Nottingham, Annesley
    Nottingham, Arnold
    Nottingham, Askham

提交回复
热议问题