我正在尝试从 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()
目前我没有提取任何数据,早些时候我让它最多处理 3 条记录。关于我做错了什么的任何见解?
最佳答案
好的,我们将从您的代码开始,以获得我们想要的工作表。然后我们将选择 UsedRange 以获取包含数据的单元格范围。然后我们将通过 ForEach 循环运行它,跳过前 5 行,因为它们有垃圾/标题信息。对于每一行,我们将创建一个新对象,并将属性设置为关联的单元格(有点像您对所有变量所做的)。所有这些对象都将收集在一个数组中,我们将其输出到一个 CSV 文件中。如果您不喜欢 CSV,您可以将其通过管道传输到 Format-Table,然后通过管道传输到 Out-File(可能必须先通过管道传输到 out-string,然后再输出文件……这不是我经常做的事情)。
$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% 的项目,或者项目成本不到 5 美元或其他任何东西。
关于excel - 从 Excel 中提取列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28727113/