从Excel中提取列

例

ExampleData

我试图从Excel工作表总共6列。 我从堆栈上的另一篇文章使用修改后的脚本,看起来像这样。

$strPath = "C:\Users\User\Documents\EXEL\fj.xls" $AssetInv = "C:\Users\User\Documents\EXEL\fj.txt" $objExcel = New-Object -ComObject Excel.Application $objExcel.Visible = $false $WorkBook = $objExcel.Workbooks.Open($strPath) $worksheet = $workbook.sheets.item("Daily Price Quote - Better Of -") $intRowMax = ($worksheet.UsedRange.Rows).count #$StartRow = 2 #$site = 1 #$state = 3 #$retailprice = 18 #$yourprice = 20 #$SavingsTotal = 21 Write "`Site City State retailprice yourprice savingstotal" | Out-File $AssetInv Write "--------------- ------------------- -------------------- -----------------------------" | Out-FIle $AssetInv -Append Write-Host "Processing: " $intRowMax "rows" for ($intRow = 7 ; $intRow -le $intRowMax ; $intRow++) { $site = $worksheet.cells.item($intRow, 10).value2 $city = $worksheet.cells.item($intRow, 2).value2 $state = $worksheet.cells.item($intRow, 3).value2 $retailprice = $worksheet.cells.item($intRow, 18).value2 $yourprice = $worksheet.cells.item($intRow, 20).value2 $SavingsTotal = $worksheet.cells.item($intRow, 21).value2 if (($site -ge 1 )) { "{0, -15} {1, -30} {2, -25} {3, -25}" -f $site, $city, $state, $retailprice, $yourprice, $Savingstotal | Out-File $AssetInv -Append } } $objexcel.quit() 

目前我没有提供任何数据,早些时候我最多只能logging3条logging。 任何洞察力,我做错了什么?

好的,我们将从您的代码开始获取我们想要的工作表。 然后,我们将selectUsedRange来获取有数据的单元格的范围。 然后我们通过ForEach循环运行它,跳过前5行,因为它们有垃圾/标题信息。 对于每一行,我们将创build一个新的对象,并将属性设置为关联的单元格(类似于对所有variables所做的操作)。 所有这些对象将被收集到一个数组中,我们将其输出到一个CSV文件中。 如果你不喜欢CSV,你可以将它传送到Format-Table,然后将其传送到Out-File(可能需要pipe到out-string,然后out-file …这不是我经常做的事情)。

 $strPath = "C:\Users\User\Documents\EXEL\fj.xls" $AssetInv = "C:\Users\User\Documents\EXEL\fj.txt" $objExcel = New-Object -ComObject Excel.Application $objExcel.Visible = $false $WorkBook = $objExcel.Workbooks.Open($strPath) $worksheet = $workbook.sheets.item("Daily Price Quote - Better Of -") $UsedRange = $worksheet.usedrange $Data = ForEach($Row in ($UsedRange.Rows|Select -skip 5)){ New-Object PSObject -Property @{ 'Site' = $Row.Cells.Item(1).Value2 'City' = $Row.Cells.Item(2).Value2 'State' = $Row.Cells.Item(3).Value2 'Retail Price' = $Row.Cells.Item(18).Value2 'Your Price' = $Row.Cells.Item(20).Value2 'Total Savings' = $Row.Cells.Item(21).Value2 } } $Data | Where{[int]::Parse($_.Site) -ge 1} | Select Site,City,State,'Retail Price','Your Price','Total Savings' | Export-Csv -NoTypeInformation -Path $AssetInv $objExcel.quit() 

另外一个好处就是你还剩下$ Data,这就是你希望能够使用的所有数据,以防你需要做任何事情(寻找你节省的X%以上的物品,或者花费更less的物品比$ 5还要好。