|
|
茫茫網海中的冷日
發生過的事,不可能遺忘,只是想不起來而已! |
|
恭喜您是本站第 1676073
位訪客!
登入 | 註冊
|
|
|
|
發表者 |
討論內容 |
冷日 (冷日) |
發表時間:2015/12/18 2:51 |
- Webmaster
- 註冊日: 2008/2/19
- 來自:
- 發表數: 15771
|
- [轉貼]Read Excel sheet in Powershell
- Read Excel sheet in Powershell
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 1-4 are ignored) in each worksheet and create an object? E.g. if column B in worksheet 1 (called London) has the following values:
Marleybone
Paddington
Victoria
Hammersmith
and column C in worksheet 2 (called) Nottingham has the following values:
Alverton
Annesley
Arnold
Askham
I'd want to create a object that from that looks like this:
City,Area
London,Marleybone
London,Paddington
London,Victoria
London,Hammersmith
Nottingham,Alverton
Nottingham,Annesley
Nottingham,Arnold
Nottingham,Askham
This is my code so far:
clear all
sheetname = @()
$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++)
{
$sheetname+=$wb.Sheets.Item($i).Name;
}
$sheetname
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,$col=5,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=$_}
}
}
冷日說明: 這個看起來值得學習,回覆者雖然用預定義[coee] $xlCellTypeLastCell = 11 $startRow,$col=5,2[/code] 來解決提問者的問題。 但事實上,只要能知道 Row、Col,或是取得 RowMax 以及 ColMax 的話,就可以用 for 迴圈下去做!
$WorkSheet = $WorkBook.sheets.item($SheetName)
$objRange = $WorkSheet.UsedRange
$RowMax = $objRange.Rows.Count
$ColMax = $objRange.Columns.Count
剩下的控制冷日就不多說啦,看你要撈哪個欄位囉...
原文出處:Read Excel sheet in Powershell - Stack Overflow/
|
|
|
討論串
|