从Excel中拉出列

时间:2015-02-25 18:43:16

标签: excel powershell

Example

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()

目前我没有提取任何数据,早些时候我让它最多可以处理3条记录。关于我做错了什么的任何见解?

1 个答案:

答案 0 :(得分:2)

好的,我们将从您的代码开始,以获取我们想要的工作表。然后我们选择UsedRange来获取具有数据的单元格范围。然后我们将通过ForEach循环运行它,跳过前5行,因为它们有垃圾/标题信息。对于每一行,我们将创建一个新对象,其属性设置为关联的单元格(类似于您对所有变量执行的操作)。所有这些对象都将收集在一个数组中,我们将其输出到CSV文件。如果您不喜欢CSV,可以将其传输到Format-Table,并将其传输到Out-File(可能必须管道输出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%的项目,或项目花费不到5美元或其他任何东西。