How to export a CSV to Excel using Powershell

前端 未结 8 1665
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 05:17

I\'m trying to export a complete CSV to Excel by using Powershell. I stuck at a point where static column names are used. But this doesn\'t work if my CSV has generic unknow

8条回答
  •  悲哀的现实
    2020-11-27 05:54

    Why would you bother? Load your CSV into Excel like this:

    $csv = Join-Path $env:TEMP "process.csv"
    $xls = Join-Path $env:TEMP "process.xlsx"
    
    $xl = New-Object -COM "Excel.Application"
    $xl.Visible = $true
    
    $wb = $xl.Workbooks.OpenText($csv)
    
    $wb.SaveAs($xls, 51)
    

    You just need to make sure that the CSV export uses the delimiter defined in your regional settings. Override with -Delimiter if need be.


    Edit: A more general solution that should preserve the values from the CSV as plain text. Code for iterating over the CSV columns taken from here.

    $csv = Join-Path $env:TEMP "input.csv"
    $xls = Join-Path $env:TEMP "output.xlsx"
    
    $xl = New-Object -COM "Excel.Application"
    $xl.Visible = $true
    
    $wb = $xl.Workbooks.Add()
    $ws = $wb.Sheets.Item(1)
    
    $ws.Cells.NumberFormat = "@"
    
    $i = 1
    Import-Csv $csv | ForEach-Object {
      $j = 1
      foreach ($prop in $_.PSObject.Properties) {
        if ($i -eq 1) {
          $ws.Cells.Item($i, $j++).Value = $prop.Name
        } else {
          $ws.Cells.Item($i, $j++).Value = $prop.Value
        }
      }
      $i++
    }
    
    $wb.SaveAs($xls, 51)
    $wb.Close()
    
    $xl.Quit()
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl)
    

    Obviously this second approach won't perform too well, because it's processing each cell individually.

提交回复
热议问题