Python: Convert Excel to CSV and Vice Versa

Excel spreadsheets are widely used for organizing and analyzing data, while CSV files offer a simpler and more universal format for data exchange. The process of converting between these formats allows for greater flexibility in working with data across different platforms and applications. In this article, you will learn how to convert Excel to CSV and vice versa 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

Convert Excel to CSV in Python

Spire.XLS for Python offers the Worksheet.SaveToFile() method, allowing users to export a certain worksheet within a workbook as an individual CSV file. The detailed steps to convert an Excel worksheet to CSV are as follows.

  • Create a Workbook object.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get a specific worksheet through Workbook.Worksheets[index] property.
  • Convert the worksheet to a CSV file using Worksheet.SaveToFile() method.
  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()

# Load an Excel document
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.xlsx")

# Get the first sheet
sheet = workbook.Worksheets[0]

# Convert it to CSV file
sheet.SaveToFile("output/ToCSV.csv", ",", Encoding.get_UTF8())
workbook.Dispose()

Python: Convert Excel to CSV and Vice Versa

Convert CSV to Excel in Python

The Workbook.LoadFromFile() method provided by Spire.XLS for Python can not only load Excel but also CSV files. After a CSV file is loaded, it can be saved as an Excel document using Workbook.SaveToFile() method. The following are the detailed steps to convert CSV to Excel using Spire.XLS for Python.

  • Create a Workbook object.
  • Load a CSV file using Workbook.LoadFromFile() method.
  • Convert the workbook to an Excel file using Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()

# Load a CSV file
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\CSV.csv", ",", 1, 1)

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

# Display numbers as text
sheet.AllocatedRange.IgnoreErrorOptions = IgnoreErrorType.NumberAsText

# Autofit column width
sheet.AllocatedRange.AutoFitColumns()

# Save to an Excel file
workbook.SaveToFile("output/ToExcel.xlsx", ExcelVersion.Version2013)

Python: Convert Excel to CSV and Vice Versa

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.