How to export a CSV to Excel using Powershell

前端 未结 8 1662
隐瞒了意图╮
隐瞒了意图╮ 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 06:04

    If you want to convert CSV to Excel without Excel being installed, you can use the great .NET library EPPlus (under LGPL license) to create and modify Excel Sheets and also convert CSV to Excel really fast!

    Preparation

    1. Download the latest stable EPPlus version
    2. Extract EPPlus to your preferred location (e.g. to $HOME\Documents\WindowsPowerShell\Modules\EPPlus)
    3. Right Click EPPlus.dll, select Properties and at the bottom of the General Tab click "Unblock" to allow loading of this dll. If you don't have the rights to do this, try [Reflection.Assembly]::UnsafeLoadFrom($DLLPath) | Out-Null

    Detailed Powershell Commands to import CSV to Excel

    # Create temporary CSV and Excel file names
    $FileNameCSV = "$HOME\Downloads\test.csv"
    $FileNameExcel = "$HOME\Downloads\test.xlsx"
    
    # Create CSV File (with first line containing type information and empty last line)
    Get-Process | Export-Csv -Delimiter ';' -Encoding UTF8 -Path $FileNameCSV
    
    # Load EPPlus
    $DLLPath = "$HOME\Documents\WindowsPowerShell\Modules\EPPlus\EPPlus.dll"
    [Reflection.Assembly]::LoadFile($DLLPath) | Out-Null
    
    # Set CSV Format
    $Format = New-object -TypeName OfficeOpenXml.ExcelTextFormat
    $Format.Delimiter = ";"
    # use Text Qualifier if your CSV entries are quoted, e.g. "Cell1","Cell2"
    $Format.TextQualifier = '"'
    $Format.Encoding = [System.Text.Encoding]::UTF8
    $Format.SkipLinesBeginning = '1'
    $Format.SkipLinesEnd = '1'
    
    # Set Preferred Table Style
    $TableStyle = [OfficeOpenXml.Table.TableStyles]::Medium1
    
    # Create Excel File
    $ExcelPackage = New-Object OfficeOpenXml.ExcelPackage 
    $Worksheet = $ExcelPackage.Workbook.Worksheets.Add("FromCSV")
    
    # Load CSV File with first row as heads using a table style
    $null=$Worksheet.Cells.LoadFromText((Get-Item $FileNameCSV),$Format,$TableStyle,$true) 
    
    # Load CSV File without table style
    #$null=$Worksheet.Cells.LoadFromText($file,$format) 
    
    # Fit Column Size to Size of Content
    $Worksheet.Cells[$Worksheet.Dimension.Address].AutoFitColumns()
    
    # Save Excel File
    $ExcelPackage.SaveAs($FileNameExcel) 
    
    Write-Host "CSV File $FileNameCSV converted to Excel file $FileNameExcel"
    

提交回复
热议问题