Converting an Excel file to CSV using the command line (CMD) can be done using several methods, depending on the tools you have available on your system. Below are a few approaches you could use, including leveraging PowerShell and third-party tools.
Method 1: Using PowerShell
PowerShell is a powerful scripting language that can be run from a CMD prompt. You can use it to convert an Excel file to CSV as follows:
-
Open CMD and use the following command to convert the Excel file to a CSV file:
powershell -Command "Get-Content 'C:\path\to\your\file.xlsx' | Export-Csv 'C:\path\to\your\output.csv' -NoTypeInformation"
-
However, if you want to work with Excel files specifically (XLS/XLSX), you'll need to leverage the Excel COM object in a PowerShell script:
Create a PowerShell script (ConvertToCsv.ps1) as follows:
param (
[string]$excelFilePath,
[string]$csvFilePath
)
# Create Excel COM object
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
# Open the Excel Workbook
$workbook = $excel.Workbooks.Open($excelFilePath)
# Save as CSV
$workbook.SaveAs($csvFilePath, 6) # 6 is the enumerator for CSV format
# Close Workbook
$workbook.Close($false)
# Quit Excel
$excel.Quit()
# Clean up
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null
[GC]::Collect() # Collect garbage
Now, run this PowerShell script from CMD:
powershell -ExecutionPolicy Bypass -File "C:\path\to\ConvertToCsv.ps1" -excelFilePath "C:\path\to\your\file.xlsx" -csvFilePath "C:\path\to\your\output.csv"
Method 2: Using Third-Party Tools
If you frequently need to convert between formats and prefer a command-line solution, consider using a third-party utility like LibreOffice or Gnumeric.
Using LibreOffice Command Line:
- Install LibreOffice if you haven’t done so already.
- Use the
soffice (LibreOffice) command as follows:
"C:\Path\To\LibreOffice\program\soffice.exe" --headless --convert-to csv "C:\path\to\your\file.xlsx" --outdir "C:\path\to\output\directory"
Method 3: Using Python Script
You can also write a Python script using the pandas library. You'll need Python installed on your machine.
-
Install Pandas if you don't have it already:
pip install pandas openpyxl
-
Create a Python script (convert_to_csv.py):
import pandas as pd
import sys
excel_file = sys.argv[1]
output_csv = sys.argv[2]
df = pd.read_excel(excel_file)
df.to_csv(output_csv, index=False)
- Run the Python script from CMD:
python C:\path\to\convert_to_csv.py C:\path\to\your\file.xlsx C:\path\to\your\output.csv
Conclusion
The easiest and most straightforward way to convert Excel files to CSV using the command line is to use PowerShell or a third-party tool like LibreOffice. Choose the method that fits your environment and tooling best. If you deal with Excel files frequently, setting up a script can save you lots of time in the long run.