How to Convert XLSX to CSV Using Python

How to Convert XLSX to CSV Using Python

Excel files (XLSX) are widely used for storing structured data, but sometimes you need a simpler format like CSV (Comma-Separated Values) for compatibility with other tools. Python makes this conversion quick and easy with the right libraries. In this guide, we'll use pandas, the most popular Python module for data manipulation, to convert XLSX files to CSV effortlessly.


Prerequisites

Before we begin, ensure you have Python installed on your system. You'll also need the following libraries:

  • pandas – For reading and writing Excel/CSV files.
  • openpyxl – Required for handling XLSX files in pandas.

Install them using pip if you haven't already:

pip install pandas openpyxl

Step-by-Step Conversion

1. Import the Required Libraries

First, import the pandas library in your Python script:

import pandas as pd

2. Read the XLSX File

Use pd.read_excel() to load the Excel file into a pandas DataFrame:

df = pd.read_excel('input_file.xlsx', engine='openpyxl')

Replace input_file.xlsx with the path to your Excel file.

3. Save as CSV

Now, convert the DataFrame to a CSV file using df.to_csv():

df.to_csv('output_file.csv', index=False)

Setting index=False ensures that row numbers are not included in the output.


Handling Multiple Sheets

If your Excel file has multiple sheets, you can specify which sheet to convert:

df = pd.read_excel('input_file.xlsx', sheet_name='Sheet1', engine='openpyxl')

Alternatively, loop through all sheets and save them as separate CSV files:

excel_file = pd.ExcelFile('input_file.xlsx', engine='openpyxl')

for sheet_name in excel_file.sheet_names:
    df = pd.read_excel(excel_file, sheet_name=sheet_name)
    df.to_csv(f'{sheet_name}.csv', index=False)

Conclusion

Converting XLSX to CSV in Python is straightforward with pandas. Whether you're working with single or multiple sheets, this method ensures a clean and efficient conversion process. This technique is particularly useful for data analysis, automation, and integrating Excel data with other applications.

Keywords: Python XLSX to CSV conversion, pandas Excel to CSV, Python data processing, convert Excel to CSV, pandas read_excel, Python automation, XLSX file handling, CSV export in Python, pandas DataFrame to CSV, Excel sheet to CSV.

Incoming search terms
- How to convert Excel to CSV using Python
- Best way to convert XLSX to CSV in Python
- Python script to export Excel as CSV
- Convert multiple Excel sheets to CSV Python
- Pandas read Excel and save as CSV
- Automate Excel to CSV conversion Python
- How to handle XLSX files in Python
- Python code for converting Excel to CSV
- Save pandas DataFrame as CSV file
- Extract data from Excel using Python

No comments:

Post a Comment