Monday, May 25, 2026Today's Paper

Omni Apps

PowerShell Convert XLS to CSV: The Ultimate Guide
May 25, 2026 · 13 min read

PowerShell Convert XLS to CSV: The Ultimate Guide

Learn how to use PowerShell to convert XLS to CSV effortlessly. Master modern non-Office scripts, legacy COM automation, pipe delimiters, and batch jobs.

May 25, 2026 · 13 min read
PowerShellExcel AutomationScripting

Introduction: Why Convert XLS to CSV with PowerShell?

In modern enterprise environments, data portability and automation are critical. Despite the rise of APIs and cloud databases, business systems still heavily rely on spreadsheets. Often, databases, legacy software, or data ingestion pipelines require plain text flat files like CSV (Comma-Separated Values). However, human operators and reporting tools continue to output spreadsheet files in Microsoft Excel formats, specifically older XLS (Excel 97-2003) and newer XLSX (XML-based) formats.

Manually opening Excel, clicking "Save As," and selecting CSV is tedious and highly inefficient for recurring tasks. Automating this workflow is where PowerShell excels. Using PowerShell to convert XLS to CSV allows you to schedule tasks, process hundreds of files in batches, and run conversions in headless cloud environments.

This comprehensive guide covers everything you need to know about converting spreadsheet files. You will learn the modern cross-platform method using the ImportExcel module (no Office installation required), the traditional COM object automation method, how to specify a pipe delimiter, how to convert in batch, and how to transition back from CSV to formatted Excel files.

Why Your Choice of Method Matters: COM vs. ImportExcel

Historically, system administrators used Component Object Model (COM) automation to interact with Excel from PowerShell. By invoking New-Object -ComObject Excel.Application, PowerShell initiates an actual, hidden instance of Microsoft Excel running in the background. While this method is highly compatible with complex Excel worksheets, it has several critical drawbacks:

  • Office Dependency: It requires Microsoft Excel to be installed on the local system. If you are running scripts on a server, in a container, or in a headless automation environment, installing Office is often impossible or violates licensing agreements.
  • Platform Restrictions: COM object automation is strictly limited to Windows operating systems. It will not work on macOS or Linux systems running PowerShell Core.
  • Resource Leaks: Excel COM objects are notoriously stubborn. If your script crashes or exits improperly before cleaning up, instances of EXCEL.EXE remain running in the background, consuming CPU and memory.
  • Interactive Desktop Requirement: Excel was never architected to run in non-interactive sessions (such as Windows Services or Scheduled Tasks running as SYSTEM). Running Excel via COM in these environments frequently leads to random freezes and permission errors.

The modern alternative is to use the open-source ImportExcel PowerShell module. Created by Microsoft MVP Doug Finke, this library is built on top of EPPlus, a .NET library that reads and writes Excel files directly in XML format.

  • It requires no Microsoft Excel installation.
  • It is incredibly fast and memory-efficient.
  • It is fully cross-platform, working seamlessly on Windows, macOS, and Linux.
  • It is completely safe to run in headless environments, Scheduled Tasks, and Azure Functions.

For almost all production scenarios, the modern ImportExcel module is the superior choice. However, if you are working on a highly locked-down Windows legacy server where installing external modules is banned, the COM method serves as a reliable fallback. We will cover both methods in detail.

Method 1: The Modern Way — Converting XLS/XLSX to CSV with ImportExcel

To get started with the modern approach, you must first install the ImportExcel module from the PowerShell Gallery. Open an administrative PowerShell prompt and execute:

Install-Module -Name ImportExcel -Force -Scope CurrentUser

Once installed, converting a spreadsheet to CSV is incredibly straightforward. Since ImportExcel reads the spreadsheet data and converts it into standard PowerShell custom objects ([PSCustomObject]), you can easily pipe that data directly into PowerShell's native Export-Csv cmdlet.

Simple XLS/XLSX to CSV Conversion

Here is a basic script to convert a single-sheet Excel workbook to a standard CSV file:

# Import the module
Import-Module ImportExcel

# Define input and output paths
$excelPath = "C:\\Data\\SalesData.xlsx"
$csvPath = "C:\\Data\\SalesData.csv"

# Read the Excel file and export to CSV
Import-Excel -Path $excelPath | Export-Csv -Path $csvPath -NoTypeInformation -Encoding utf8

Write-Host "Conversion completed successfully!" -ForegroundColor Green

Handling Multiple Worksheets

Excel workbooks often contain multiple worksheets, whereas a CSV file only supports a single flat table. By default, Import-Excel will import the first worksheet in the workbook. If you need to convert a specific worksheet, you can target it by name using the -WorksheetName parameter:

$excelPath = "C:\\Data\\MultiSheet.xlsx"
$csvPath = "C:\\Data\\Q4_Report.csv"

# Import a specific worksheet named 'Q4_Sales'
Import-Excel -Path $excelPath -WorksheetName "Q4_Sales" | Export-Csv -Path $csvPath -NoTypeInformation -Encoding utf8

If you do not know the sheet names beforehand, you can programmatically extract the names of all worksheets in a workbook and export each one to its own CSV file:

$excelPath = "C:\\Data\\MultiSheet.xlsx"
$outputDir = "C:\\Data\\ExtractedSheets"

# Ensure the output directory exists
if (-not (Test-Path $outputDir)) {
    New-Item -ItemType Directory -Path $outputDir | Out-Null
}

# Open the Excel package and query worksheet names
$excelPackage = Open-ExcelPackage -Path $excelPath
$sheetNames = $excelPackage.Workbook.Worksheets.Name
Close-ExcelPackage $excelPackage

# Loop through sheets and export each to a separate CSV
foreach ($sheet in $sheetNames) {
    $cleanSheetName = $sheet -replace '[\\\\\\/\\:\\?\\*\\[\\]]', '_'
    $csvPath = Join-Path -Path $outputDir -ChildPath "$cleanSheetName.csv"
    
    Write-Host "Exporting worksheet '$sheet' to '$csvPath'..."
    Import-Excel -Path $excelPath -WorksheetName $sheet | Export-Csv -Path $csvPath -NoTypeInformation -Encoding utf8
}

Converting Excel to CSV with Pipe Delimitation

A common issue with standard comma-separated files is that data fields (like product descriptions or addresses) often contain commas. When parsing these CSVs, complex escaping rules are required to prevent data misalignment. Using a pipe symbol (|) as a delimiter is a highly effective way to bypass this problem.

By linking Import-Excel with Export-Csv and utilizing the -Delimiter parameter, you can easily output a pipe-delimited file:

$excelPath = "C:\\Data\\CustomerRecords.xlsx"
$csvPath = "C:\\Data\\CustomerRecords_Pipe.csv"

# Export data using a pipe symbol (|) as the field separator
Import-Excel -Path $excelPath | Export-Csv -Path $csvPath -Delimiter '|' -NoTypeInformation -Encoding utf8

Write-Host "Pipe-delimited CSV exported successfully!" -ForegroundColor Green

Method 2: The Legacy Way — Using the Excel COM Object

If you are working on a secure offline server where you cannot download the ImportExcel module, or if you must deal with highly specific, old legacy .xls files that contain heavy formatting structures, you can automate Microsoft Excel via COM.

Remember, this method requires Microsoft Excel to be installed on the machine running the script, and it will only work on Windows.

Here is a highly robust, professional script that safely opens Excel, performs the conversion, and explicitly releases memory to prevent background process hanging:

# Define absolute paths (COM objects require absolute paths)
$excelPath = "C:\\Data\\OldReport.xls"
$csvPath = "C:\\Data\\OldReport.csv"

# Initialize Excel COM Object
$excelApp = New-Object -ComObject Excel.Application

# Ensure Excel runs silently in the background
$excelApp.Visible = $false
$excelApp.DisplayAlerts = $false

try {
    # Open the XLS workbook
    $workbook = $excelApp.Workbooks.Open($excelPath)
    
    # Save as CSV. 
    # xlCSV is represented by the integer value 6 in the XlFileFormat enumeration.
    # Note: If your data has special characters, you can use format 62 (xlCSVUTF8) if Excel 2016+ is installed.
    $xlCSVFormat = 6 
    $workbook.SaveAs($csvPath, $xlCSVFormat)
    
    # Close the workbook and save changes
    $workbook.Close($true)
    Write-Host "XLS successfully converted to CSV using Excel COM." -ForegroundColor Green
}
catch {
    Write-Error "An error occurred during COM conversion: $_"
}
finally {
    # Critical clean-up steps to kill the hidden EXCEL.EXE process
    $excelApp.Quit()
    
    # Release variables from the garbage collector
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excelApp) | Out-Null
    Remove-Variable excelApp
    
    # Force a garbage collection cycle to release locked files immediately
    [System.GC]::Collect()
    [System.GC]::WaitForPendingFinalizers()
}

Understanding COM Clean-up

The finally block in the script above is the most important part of the COM method. If you fail to call ReleaseComObject and explicitly trigger garbage collection, the EXCEL.EXE process will remain locked in your system's task manager indefinitely. If your script runs on a daily schedule, you could quickly end up with dozens of phantom Excel processes chewing up your server's RAM.

Method 3: Converting Multiple Files in Batch (Folder Processing)

In real-world administrative tasks, you rarely convert just one spreadsheet. Usually, you are handed a folder full of weekly reports or raw export files that all need to be reformatted.

Here is a comprehensive script that dynamically searches a directory, finds all .xls and .xlsx files, and batch-converts them into .csv files using the ImportExcel module. This script also creates a designated output directory if it does not already exist.

# Configuration
$sourceFolder = "C:\\ExcelImports"
$outputFolder = "C:\\CSVExports"

# Create output folder if it doesn't exist
if (-not (Test-Path $outputFolder)) {
    New-Item -ItemType Directory -Path $outputFolder | Out-Null
}

# Verify ImportExcel is available
if (-not (Get-Module -ListAvailable -Name ImportExcel)) {
    Write-Error "The ImportExcel module is required. Install it using: Install-Module ImportExcel"
    return
}

# Fetch all Excel files (both .xls and .xlsx formats)
$excelFiles = Get-ChildItem -Path $sourceFolder -Include *.xlsx, *.xls -Recurse -File

if ($excelFiles.Count -eq 0) {
    Write-Host "No Excel files found in '$sourceFolder'." -ForegroundColor Yellow
    return
}

Write-Host "Found $($excelFiles.Count) Excel files to convert." -ForegroundColor Cyan

foreach ($file in $excelFiles) {
    # Build target path with the same name but .csv extension
    $csvName = $file.BaseName + ".csv"
    $targetPath = Join-Path -Path $outputFolder -ChildPath $csvName
    
    Write-Host "Converting '$($file.Name)'..." -NoNewline
    
    try {
        # Perform the modern conversion
        Import-Excel -Path $file.FullName | Export-Csv -Path $targetPath -NoTypeInformation -Encoding utf8
        Write-Host " [DONE]" -ForegroundColor Green
    }
    catch {
        Write-Host " [FAILED]" -ForegroundColor Red
        Write-Warning "Failed to convert '$($file.FullName)': $_"
    }
}

Write-Host "Batch processing complete!" -ForegroundColor Green

This script can easily be configured as a Windows Scheduled Task or integrated into an automated ETL (Extract, Transform, Load) system.

Going the Other Way: Converting CSV back to Excel (XLS/XLSX)

Frequently, developers and system engineers generate text logs or database extract files in CSV format, but then need to share those files with managers or external clients who require formal Excel spreadsheets. PowerShell can easily perform the reverse operation: converting CSV files back to Excel, while automatically applying professional styling, custom headers, and table structures.

Simple CSV to XLSX Conversion with Headers

With the ImportExcel module, converting a CSV back to an Excel worksheet with headers is incredibly simple because Export-Excel natively handles objects passed from Import-Csv.

$csvPath = "C:\\Data\\ServerLogs.csv"
$excelPath = "C:\\Data\\ServerLogs.xlsx"

# Import CSV data and export it straight to an Excel worksheet
Import-Csv -Path $csvPath | Export-Excel -Path $excelPath -WorksheetName "System Logs"

Write-Host "CSV successfully converted to Excel." -ForegroundColor Green

Elevating Your Spreadsheet: Exporting Excel with Professional Formatting

The true power of ImportExcel lies in its formatting parameters. Instead of sharing a plain, unformatted white spreadsheet that looks like a basic text file, you can build a highly polished report with frozen headers, bold text, styled data tables, and auto-fitted columns.

$csvPath = "C:\\Data\\MonthlySales.csv"
$excelPath = "C:\\Data\\FormattedSales.xlsx"

# Import CSV and apply advanced styling options during the Excel export
Import-Csv -Path $csvPath | Export-Excel -Path $excelPath `
    -WorksheetName "Sales Report" `
    -BoldTopRow `
    -FreezeTopRow `
    -AutoSize `
    -AutoFilter `
    -TableName "SalesData" `
    -TableStyle "Medium9"

Write-Host "Formatted Excel report generated successfully!" -ForegroundColor Green

By leveraging these properties, you achieve several automated styling upgrades:

  • BoldTopRow: Immediately styles your column headers in bold so they stand out from the raw data.
  • FreezeTopRow: Keeps the header row locked at the top of the viewport when users scroll down through hundreds of data records.
  • AutoSize: Adjusts every column's width to precisely fit the longest string in that column, preventing ugly cropped text or standard numeric truncation ### errors.
  • AutoFilter: Adds dropdown filtering arrows to the top header row, letting the end-user sort, search, and filter data with a single click.
  • TableName and TableStyle: Conforms the exported range to an official Excel table structure, adding automatic alternating row colors ("zebra striping") using pre-built Excel design templates (like Medium9).

Advanced Tips & Troubleshooting

When converting spreadsheets via automation, you are bound to run into formatting quirks, encoding issues, and data-loss scenarios. Here is how to handle the most common issues:

1. The Disappearing Leading Zeros (ZIP Codes and Serial Numbers)

A common issue in Excel automation occurs when you have values like postal codes (01234) or custom account IDs. Because PowerShell's standard ingestion tries to parse numeric-looking items as integers, the leading zero is dropped, leaving you with 1234.

If you use ImportExcel, you can suppress number conversion entirely, forcing all values to remain as raw text strings when reading the data:

# Prevent Excel columns from being automatically cast into numeric types
Import-Excel -Path "C:\\Data\\Users.xlsx" -NoNumberConversion | Export-Csv -Path "C:\\Data\\Users.csv" -NoTypeInformation

2. Special Characters and UTF Encoding

By default, old Excel sheets might contain regional special characters (like accented letters, system symbols, or non-English alphabets). Standard PowerShell exports can occasionally translate these into messy corrupted garbage strings (such as é).

To ensure character integrity, always specify -Encoding utf8 (or -Encoding utf8NoBOM on modern PowerShell versions) in your Export-Csv step. UTF-8 formatting ensures universal compatibility with modern web systems and database engines.

3. Suppressing System Headers in Windows PowerShell 5.1

If you are still running Windows PowerShell 5.1, the Export-Csv cmdlet will write a system type metadata string on the very first line of your output file (for example: #TYPE System.Management.Automation.PSCustomObject). If you attempt to load this CSV into an automated database, this header will break the parser.

Always include the -NoTypeInformation parameter when exporting. In PowerShell Core (versions 6, 7, and beyond), this metadata header is suppressed by default, but keeping the parameter ensures absolute backward compatibility.

Frequently Asked Questions (FAQ)

Do I need Microsoft Excel installed on my server to run these conversion scripts?

No! If you use the modern ImportExcel PowerShell module, you do not need Microsoft Office or Excel installed at all. The module interacts directly with the file system XML data using .NET libraries. Excel is only required if you choose to use the legacy COM object automation method.

How do I convert an Excel file to a pipe-delimited CSV?

To use a pipe delimiter, pipe your Excel data into Export-Csv and set the -Delimiter parameter to a single vertical bar character: Import-Excel -Path "Data.xlsx" | Export-Csv -Path "Data.csv" -Delimiter '|' -NoTypeInformation

Can I merge multiple worksheets from a single Excel file into one CSV?

No, a CSV file is structurally limited to a single flat dataset. If you have multiple worksheets, you must export each worksheet to its own separate CSV file, or use a script to append their records together if they share the exact same column structures.

Why does Excel keep running in the background after my COM script finishes?

This happens because Windows still maintains a memory reference to the Excel COM object instance. To completely terminate it, you must execute the cleanup block: quit the application, release the COM marshal reference using [System.Runtime.InteropServices.Marshal]::ReleaseComObject($excelApp), and force a Garbage Collector sweep.

How can I set alternating row colors when converting CSV to Excel?

When piping a CSV into Export-Excel, use the -TableName parameter paired with the -TableStyle parameter. This turns your imported rows into an official Excel data table, which automatically renders professional alternating row background colors.

Conclusion

PowerShell is an incredibly versatile scripting tool for bridging the gap between structured business spreadsheets and raw text flat files. While the legacy Excel COM object model remains a viable fallback for locked-down systems, leveraging the modern, lightweight, and cross-platform ImportExcel module will save you from process leaks, platform restrictions, and complex server installation requirements.

By automating your conversions with the detailed batch, formatting, and custom delimitation scripts provided in this guide, you can eliminate manual office tasks and ensure your enterprise data pipelines run smoothly.

Related articles
Combining CSV Files in Excel: The Complete Step-by-Step Guide
Combining CSV Files in Excel: The Complete Step-by-Step Guide
Learn how to combine CSV files in Excel like a pro. Master Power Query, VBA macros, and Command Prompt to merge multiple CSVs into one spreadsheet fast!
May 25, 2026 · 14 min read
Read →
PowerShell Convert XLSX to CSV: Complete Automation Guide
PowerShell Convert XLSX to CSV: Complete Automation Guide
Learn how to PowerShell convert XLSX to CSV and back again. Master Excel automation scripts with or without Microsoft Excel installed on your server.
May 25, 2026 · 13 min read
Read →
PowerShell Export Excel: The Ultimate Guide to Automation
PowerShell Export Excel: The Ultimate Guide to Automation
Master PowerShell export to Excel workflows. Learn how to convert CSV to multi-sheet workbooks, read spreadsheets, and import data into SQL Server.
May 24, 2026 · 12 min read
Read →
OFX Excel Guide: How to Import and Convert Financial Files
OFX Excel Guide: How to Import and Convert Financial Files
Master the OFX Excel workflow. Learn how to import OFX files into Excel using Power Query, and safely convert Excel or CSV sheets back to OFX format.
May 24, 2026 · 17 min read
Read →
How to Replace Text in a File (And Across Multiple Files)
How to Replace Text in a File (And Across Multiple Files)
Need to replace text in a file or execute a mass find-and-replace across thousands of files? Here is the ultimate guide to batch editing text.
May 24, 2026 · 15 min read
Read →
You May Also Like