Tag: PowerShell Excel COM Object

  • How to Export PowerShell Output to Excel (CSV and XLSX Methods)

    📤 How to Export Output to Excel in PowerShell – Step-by-Step Guide

    PowerShell offers several ways to export data to Excel, depending on whether you want a simple CSV export or a richly formatted Excel file (with styling, multiple sheets, etc.).


    ✅ Method 1: Export to Excel via CSV (Simple and Quick)

    🔹 Use Export-Csv Cmdlet

    Get-Process | Select-Object Name, CPU, ID | Export-Csv -Path "C:\output\processes.csv" -NoTypeInformation
    

    🔍 This creates a CSV file that you can open in Excel.

    • -NoTypeInformation removes extra metadata.
    • Works well for basic tabular data.

    ✅ Method 2: Export to Real Excel (.xlsx) Using ImportExcel Module

    For more powerful Excel features (multiple sheets, formatting), use the ImportExcel module by Doug Finke.

    🔹 Step 1: Install the module

    Install-Module -Name ImportExcel
    

    📝 Run PowerShell as Administrator if it fails.

    🔹 Step 2: Use Export-Excel Cmdlet

    Get-Process | Select-Object Name, CPU, ID | Export-Excel -Path "C:\output\processes.xlsx" -AutoSize -Title "Running Processes"
    

    📌 Features:

    • Saves as .xlsx
    • Supports formatting, charts, filters, pivot tables, etc.
    • -AutoSize adjusts column width
    • -Title adds a worksheet title

    ✅ Method 3: Write to Excel Using COM Object (Built-in, No Module)

    If you want to use Excel features without installing anything:

    # Create Excel COM Object
    $Excel = New-Object -ComObject Excel.Application
    $Workbook = $Excel.Workbooks.Add()
    $Sheet = $Workbook.Sheets.Item(1)
    
    # Sample data
    $data = Get-Process | Select-Object -First 10 Name, ID, CPU
    
    # Write headers
    $headers = $data[0].psobject.Properties.Name
    for ($i = 0; $i -lt $headers.Count; $i++) {
        $Sheet.Cells.Item(1, $i + 1) = $headers[$i]
    }
    
    # Write data
    $row = 2
    foreach ($item in $data) {
        for ($col = 0; $col -lt $headers.Count; $col++) {
            $Sheet.Cells.Item($row, $col + 1) = $item.($headers[$col])
        }
        $row++
    }
    
    # Save file
    $Excel.Visible = $false
    $Workbook.SaveAs("C:\output\processes_COM.xlsx")
    $Excel.Quit()
    

    ✅ No external module needed
    ⚠️ Slower, and Excel must be installed on your system


    📌 Summary Table:

    MethodFormatRequires ModuleBest For
    Export-Csv.csv❌ NoSimple data exports
    Export-Excel.xlsx✅ Yes (ImportExcel)Professional Excel reports
    COM Automation.xlsx❌ NoFull Excel control, legacy use

    📣 Want to Learn Excel Automation with PowerShell?

    🎓 Learn to automate Excel reports, manipulate files, and create templates with:
    👉 Mastering MS Excel Course