Python script demonstrating conversion of Excel (XLSX/XLS) to CSV using Spire.XLS

If you’re looking to convert xlsx to csv in Python, or even handle .xls files, this guide is for you. CSV files are lightweight, easy to parse, and widely supported across databases and data tools—making them ideal for automation and data exchange.

In this article, we’ll show you how to convert Excel to CSV in Python using Spire.XLS for Python. The library supports .xlsx, .xls, and other common Excel spreadsheet formats, and doesn’t rely on any third-party components. You’ll learn how to export the entire workbook, handle multiple worksheets, and ensure encoding—all with clean and efficient Python code.

What’s Covered:

Convert XLSX to CSV in Python

To follow along, install Spire.XLS for Python (pip install spire.xls) or Free Spire.XLS for Python (pip install spire.xls.free) for lightweight tasks.

The most common use case is converting .xlsx files to .csv. Here’s a simple script using Spire.XLS:

from spire.xls import Workbook, FileFormat

# Initialize a workbook and load the xlsx file
workbook = Workbook()
workbook.LoadFromFile("Sample.xlsx")

# Save the workbook as a csv file
workbook.SaveToFile("output/XLSXToCSV.csv", FileFormat.CSV)
workbook.Dispose()

Result:

Result of converting XLSX file to CSV using Python and Spire.XLS

⚠️ Note: The SaveToFile() method saves only the first worksheet. If you need to convert all sheets, see the next section.

This method is perfect for simple, single-sheet Excel-to-CSV conversions in Python.

Convert Excel (XLS/XLSX) to CSV: All Sheets, Old Files & Batch

Whether you're working with modern .xlsx, older .xls, or multi-sheet Excel files, Spire.XLS offers multiple ways to export everything to CSV in Python.

Export All Worksheets to Separate CSV Files

To export every worksheet into its own CSV file—for example, monthly tabs or department data:

from spire.xls import Workbook, Encoding

# Initialize a workbook and load the Excel file
workbook = Workbook()
workbook.LoadFromFile("Sample.xlsx")

# Iterate through each sheet
for i in range(workbook.Worksheets.Count):
    # Save the current sheet to CSV format
    sheet = workbook.Worksheets.get_Item(i)
    sheet.SaveToFile(f"output/Sheets/Sheet{i}.csv", ",", Encoding.get_UTF8())
workbook.Dispose()

Result:

Output files after exporting all Excel worksheets to separate CSVs with Python

Each worksheet becomes an individual CSV, ideal for segmented data processing and distribution.

Convert XLS to CSV in Python

Legacy Excel files (.xls) are still common in many industries. Fortunately, Spire.XLS fully supports them:

workbook = Workbook()
workbook.LoadFromFile("legacy.xls")
workbook.SaveToFile("legacy_output.csv", FileFormat.CSV)

This converts the first worksheet by default. To convert all .xls sheets, apply the loop method shown above.

You may also like: Convert XLS Files to XLSX Files with Python

Batch Convert Excel Files to CSV

To automate conversion of multiple .xlsx and .xls files stored in a folder:

import os
from spire.xls import Workbook, FileFormat

excel_dir = "./excels"
output_dir = "./csvs"

for file in os.listdir(excel_dir):
    if file.endswith(".xlsx") or file.endswith(".xls"):
        workbook = Workbook()
        workbook.LoadFromFile(os.path.join(excel_dir, file))
        base_name = os.path.splitext(file)
        workbook.SaveToFile(os.path.join(output_dir, base_name + ".csv"), FileFormat.CSV)

Note: This script saves only the first worksheet. Use sheet.SaveToFile() in a loop if you want all sheets.

Advanced Conversion: Customize CSV Output in Python

Need to export only specific cells, rows, or columns from Excel to CSV? You can read worksheet content manually and write customized CSV output:

import csv
from itertools import chain

from spire.xls import Workbook

# Initialize a Workbook object and load the Excel file
workbook = Workbook()
workbook.LoadFromFile("Sample.xlsx")
# Get the first worksheet
sheet = workbook.Worksheets.get_Item(0)

# Export data to CSV
with open("output/FilteredOutput.csv", "w", newline="", encoding="utf-8") as csvfile:
    writer = csv.writer(csvfile)
    for row in range(sheet.AllocatedRange.RowCount):  # Export rows 1 to 5
        row_data = []
        for col in chain(range(0, 2), range(3, sheet.AllocatedRange.ColumnCount)):  # Export columns A to C
            row_data.append(sheet.Range.get_Item(row + 1, col + 1).Value)
        writer.writerow(row_data)

Result:

Customized CSV output from specific Excel rows and columns using Python code

This provides full control for custom Excel to CSV conversion in Python, such as skipping headers or exporting limited ranges.

Explore More: Export & Import Data Between Excel Files and Databases | Python

Bonus Tip: Convert CSV Back to Excel (XLSX)

While this guide focuses on Excel to CSV, you can also convert CSV files back to Excel using Spire.XLS:

from spire.xls import Workbook, FileFormat

workbook = Workbook()
workbook.LoadFromFile("output.csv", ",")
workbook.SaveToFile("restored.xlsx", FileFormat.Version2016)

This is useful for restoring structured Excel files after processing raw CSV data.

Want to explore more? Check out our dedicated guide on how to convert CSV to Excel using Python for more advanced methods, formatting options, and batch conversion tips.


Frequently Asked Questions

Q1: How to convert an XLSX file to CSV in Python?

A: You can use Python libraries like Spire.XLS to load the XLSX file and save it as CSV. See the detailed steps in Convert XLSX to CSV in Python.

Q2: How to convert xlsx into csv?

A: Convert XLSX to CSV by loading the file and exporting to CSV format, either saving the first sheet or iterating through all sheets to save separately. Check Convert Excel (XLS/XLSX) to CSV: All Sheets, Old Files & Batch for multi-sheet and batch examples.

Q3: How to convert xlsx to csv from the command line?

A: While this article focuses on Python, you can create Python scripts using Spire.XLS or other libraries and run them from the command line to batch convert XLSX to CSV files. See the Batch Convert Excel Files to CSV section for related code.

Q4: How to convert Excel to text in Python?

A: Converting Excel to text typically means extracting cell values and saving them as CSV or TXT. Using libraries like Spire.XLS or pandas in Python, you can export Excel data into plain text formats easily. For more advanced output, check Advanced Conversion: Customize CSV Output in Python.


Conclusion

In this guide, you’ve learned effective ways to convert XLSX and XLS files to CSV using Python, including exporting entire workbooks or specific sheets, handling batch conversions, and restoring Excel files from CSV. You also gained insights on customizing CSV outputs by selecting precise cell ranges.

Whether you want to automate your Excel to CSV conversion in Python, process legacy Excel files, or streamline data workflows, Spire.XLS provides a robust, code-friendly solution without requiring Microsoft Excel.

Get a Free License for the Full Version

While the free version of Spire.XLS for Python covers basic Python Excel to CSV tasks, if you need the full features and enhanced performance, you can apply for a temporary free license of the full version. This lets you unlock all capabilities and simplify your Python Excel to CSV processing even further.

Java: Convert Excel to Text (TXT)

2023-08-08 05:37:02 Written by Koohji

Converting Excel files to text files has several benefits. For example, it reduces file size, making data easier to store and share. In addition, text files are usually simple in structure, and converting Excel to text can make the document more straightforward for certain tasks. This article will demonstrate how to programmatically convert Excel to TXT format using Spire.XLS for Java.

Install Spire.XLS for Java

First of all, you're required to add the Spire.Xls.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.xls</artifactId>
        <version>15.11.3</version>
    </dependency>
</dependencies>

Create Excel to TXT in Java

Spire.XLS for Java offers the Worksheet.saveToFile(String fileName, String separator, java.nio.charset.Charset encoding) method to convert a specified worksheet to a txt file. The following are the detailed steps.

  • Create a Workbook instance.
  • Load a sample Excel file using Workbook.loadFromFile() method.
  • Get a specified worksheet by its index using Workbook.getWorksheets().get() method.
  • Convert the Excel worksheet to a TXT file using Worksheet.saveToFile() method.
  • Java
import com.spire.xls.*;

import java.nio.charset.Charset;

public class toText {
    public static void main(String[] args) {
        //Create a Workbook object
        Workbook workbook = new Workbook();

        //Load a sample Excel file
        workbook.loadFromFile("sample.xlsx");

        //Get the first worksheet
        Worksheet worksheet = workbook.getWorksheets().get(0);

        //Save the worksheet as a txt file
        Charset charset = Charset.forName("utf8");
        worksheet.saveToFile("ExceltoTxt.txt", " ", charset);

    }
}

Java: Convert Excel to Text (TXT)

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

The Excel spreadsheet is extensively utilized for organizing, analyzing, and presenting data in a tabular format. The capacity to programmatically interact with Excel files holds great value as it facilitates automation and integration of Excel functionality within software applications. Specifically, knowing how to create new Excel documents, retrieve information from existing ones, and update or modify them as needed through code would be very helpful. This article will demonstrate how to create, read, or update Excel documents in Python using Spire.XLS for Python.

Install Spire.XLS for Python

This scenario requires Spire.XLS for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.XLS

If you are unsure how to install, please refer to this tutorial: How to Install Spire.XLS for Python on Windows

Create an Excel Document in Python

Spire.XLS for Python offers a variety of classes and interfaces that you can use to create and edit Excel documents. Here is a list of important classes, properties and methods involved in this article.

Member Description
Workbook class Represents an Excel workbook model.
Workbook.Worksheets.Add() method Adds a worksheet to workbook.
Workbook.SaveToFile() method Saves the workbook to an Excel document.
Worksheet class Represents a worksheet in a workbook.
Worksheet.Range property Gets a specific cell or cell range from worksheet.
Worksheet.Range.Text property Gets or sets the text value of a cell.
Worksheet.Rows property Gets a collection of rows in worksheet.
CellRange class Represents a cell or cell range in worksheet.

The following are the steps to create an Excel document from scratch using Spire.XLS for Python.

  • Create a Workbook object.
  • Add a worksheet using Workbook.Worksheets.Add() method.
  • Write data to specific cells through Worksheet.Range.Text property.
  • Save the workbook to an Excel document using Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
wb = Workbook()

# Remove default worksheets
wb.Worksheets.Clear()

# Add a worksheet and name it "Employee"
sheet = wb.Worksheets.Add("Employee")

# Merge the cells between A1 and G1
sheet.Range["A1:G1"].Merge()

# Write data to A1 and apply formatting to it
sheet.Range["A1"].Text = "Basic Information of Employees of Huanyu Automobile Company"
sheet.Range["A1"].HorizontalAlignment = HorizontalAlignType.Center
sheet.Range["A1"].VerticalAlignment = VerticalAlignType.Center
sheet.Range["A1"].Style.Font.IsBold = True
sheet.Range["A1"].Style.Font.Size = 13

# Set row height of the first row
sheet.Rows[0].RowHeight = 30

# Write data to specific cells
sheet.Range["A2"].Text = "Name"
sheet.Range["B2"].Text = "Gender"
sheet.Range["C2"].Text = "Birth Date"
sheet.Range["D2"].Text = "Educational Background"
sheet.Range["E2"].Text = "Contact Number"
sheet.Range["F2"].Text = "Position"
sheet.Range["G2"].Text = "ID"

sheet.Range["A3"].Text = "Allen"
sheet.Range["B3"].Text = "Male"
sheet.Range["C3"].Text = "1990-02-10"
sheet.Range["D3"].Text = "Bachelor"
sheet.Range["E3"].Text = "24756854"
sheet.Range["F3"].Text = "Mechanic"
sheet.Range["G3"].Text = "0021"

sheet.Range["A4"].Text = "Patrick"
sheet.Range["B4"].Text = "Male"
sheet.Range["C4"].Text = "1985-06-08"
sheet.Range["D4"].Text = "Master"
sheet.Range["E4"].Text = "59863247"
sheet.Range["F4"].Text = "Mechanic"
sheet.Range["G4"].Text = "0022"

sheet.Range["A5"].Text = "Jenna"
sheet.Range["B5"].Text = "Female"
sheet.Range["C5"].Text = "1989-11-25"
sheet.Range["D5"].Text = "Bachelor"
sheet.Range["E5"].Text = "79540352"
sheet.Range["F5"].Text = "Sales"
sheet.Range["G5"].Text = "0023"

sheet.Range["A6"].Text = "Tommy"
sheet.Range["B6"].Text = "Male"
sheet.Range["C6"].Text = "1988-04-16"
sheet.Range["D6"].Text = "Master"
sheet.Range["E6"].Text = "52014060"
sheet.Range["F6"].Text = "Mechanic"
sheet.Range["G6"].Text = "0024"

sheet.Range["A7"].Text = "Christina"
sheet.Range["B7"].Text = "Female"
sheet.Range["C7"].Text = "1998-01-21"
sheet.Range["D7"].Text = "Bachelor"
sheet.Range["E7"].Text = "35401489"
sheet.Range["F7"].Text = "HR"
sheet.Range["G7"].Text = "0025"

# Set row height of a range
sheet.Range["A2:G7"].RowHeight = 15

# Set column width
sheet.SetColumnWidth(3, 15)
sheet.SetColumnWidth(4, 21)
sheet.SetColumnWidth(5, 15)

# Set border style of a range
sheet.Range["A2:G7"].BorderAround(LineStyleType.Medium)
sheet.Range["A2:G7"].BorderInside(LineStyleType.Thin)
sheet.Range["A2:G2"].BorderAround(LineStyleType.Medium)
sheet.Range["A2:G7"].Borders.KnownColor = ExcelColors.Black

# Save to a .xlsx file
wb.SaveToFile("output/NewSpreadsheet.xlsx", FileFormat.Version2016)

Python: Create, Read, or Update Excel Documents

Read Data from a Worksheet in Python

The Worksheet.Range.Value property returns number value or text value of a cell as a string. To get data of a whole worksheet or a cell range, loop through the cells within it. The following are the steps to get data of a worksheet using Spire.XLS for Python.

  • Create a Workbook object.
  • Load an Excel document using Workbook.LoadFromFile() method.
  • Get a specific worksheet through Workbook.Worksheets[index] property.
  • Get the cell range contain data though Worksheet.AllocatedRange property.
  • Iterate through the rows and columns to get cells within the range, and return the value of each cell through CellRange.Value property.
  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
wb = Workbook()

# Load an existing Excel file
wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\NewSpreadsheet.xlsx");

# Get the first worksheet
sheet = wb.Worksheets[0]

# Get the cell range containing data
locatedRange = sheet.AllocatedRange

# Iterate through the rows
for i in range(len(sheet.Rows)):

    # Iterate through the columns
    for j in range(len(locatedRange.Rows[i].Columns)):

        # Get data of a specific cell
        print(locatedRange[i + 1, j + 1].Value + "  ", end='')
        
    print("")

Python: Create, Read, or Update Excel Documents

Update an Excel Document in Python

To change the value of a certain cell, just re-assign a value to it through Worksheet.Range.Value property. The following are the detailed steps.

  • Create a Workbook object.
  • Load an Excel document using Workbook.LoadFromFile() method.
  • Get a specific worksheet through Workbook.Worksheets[index] property.
  • Change the value of a particular cell though Worksheet.Range.Value property.
  • Save the workbook to an Excel file using Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
wb = Workbook();

# Load an existing Excel file
wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\NewSpreadsheet.xlsx")

# Get the first worksheet
sheet = wb.Worksheets[0]

# Change the value of a specific cell
sheet.Range["A1"].Value = "Updated Value"

# Save to file
wb.SaveToFile("output/Updated.xlsx", ExcelVersion.Version2016)

Python: Create, Read, or Update Excel Documents

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

page 77

Coupon Code Copied!

Christmas Sale

Celebrate the season with exclusive savings

Save 10% Sitewide

Use Code:

View Campaign Details