使用PowerShell将大型csv文件导入Excel

时间:2014-08-29 06:34:52

标签: excel powershell csv import

我正在编写一个在Excel文档中导入大型csv文件的脚本。 我尝试使用更快的方式输入数据并将数组直接传递给Excel而不进行循环。

$p = Import-Csv -Path "C:\Report.csv" -Delimiter "`t"
$Excel01 = New-Object -ComObject Excel.Application 
$Excel01.Visible = $True 
$Workbook01 = $Excel01.Workbooks.Add() 
$Worksheet01 = $Workbook01.Sheets.Item(1) 
$Worksheet01.Activate() 

$Worksheet01.Range("A1:D1").EntireColumn.Value() = $p | select field1,field2...

但是当我跑这个时它挂了......我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

Excel中已存在

OpenText()。但请注意,您必须将文本文件的扩展名更改为.csv以外的其他内容,因为Excel对于应如何处理具有该特定扩展名的文件有自己的想法。

New-Variable -Option Constant -Name xlDelimited -Value 1
New-Variable -Option Constant -Name xlTextQualifierNone -Value -4142
New-Variable -Option Constant -Name xlWorkbookDefault -Value 51

$csv = 'C:\path\to\your.csv'
$txt = $csv -replace '\.csv$','.txt'
$xls = $csv -replace '\.csv$','.xlsx'

Rename-Item $csv $txt

$xl = New-Object -COM 'Excel.Application'
$xl.Workbooks.OpenText($txt, [Type]::Missing, [Type]::Missing, $xlDelimited, $xlTextQualifierNone, $false, $true)
$wb = $xl.Workbooks | ? { $_.FullName -eq $txt }

$wb.SaveAs($xls, $xlWorkbookDefault)
$wb.Close()

$xl.Quit()

应保留默认值的参数需要[Type]::Missing值。

答案 1 :(得分:0)

快速而肮脏。也许你可以优化它: - )

$p = Import-Csv -Path "C:\Report.csv" -Delimiter "`t"
$Excel01 = New-Object -ComObject Excel.Application 
$Excel01.Visible = $True 
$Workbook01 = $Excel01.Workbooks.Add() 
$Worksheet01 = $Workbook01.Sheets.Item(1) 
$Worksheet01.Activate() 

#Add csv header to excel
For ($i = 0; $i -lt ($p | Get-Member | Where-Object -FilterScript {$_.MemberType -eq "NoteProperty"}).Count; $i ++) {
    $Worksheet01.Cells.Item(1,(1+$i)) = "$(($p | Get-Member | Where-Object -FilterScript {$_.MemberType -eq "NoteProperty"})[$i].Name)"
}

#Add csv data to ecxel
$startRow = 2
For ($i = 0; $i -lt ($p | Measure-Object).Count; $i ++) {
    For ($i2 = 0; $i2 -lt ($p[$i] | Get-Member | Where-Object -FilterScript {$_.MemberType -eq "NoteProperty"}).Count; $i2 ++) {
        $PropertyName = ($p[$i2] | Get-Member | Where-Object -FilterScript {$_.MemberType -eq "NoteProperty"})[$i2].Name
        $Worksheet01.Cells.Item($startRow,(1+$i2)) = "$($p[$i].$PropertyName)"
    }
    $startRow ++
}