Monday, 04 September 2023 01:28

Python: Convert CSV to PDF

A CSV (Comma-Separated Values) file is a plain text file used to store tabular data. Although CSV files are widely supported by spreadsheet programs, there may still be times when you need to convert them to PDF files to ensure broader accessibility and also enable security features. This article will demonstrate how to convert CSV to PDF 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 CSV to PDF in Python

The Workbook.SaveToFile() method provided by Spire.XLS for Python allows to save a CSV file as a PDF file. The following are the detailed steps.

  • Create a Workbook object.
  • Load a CSV file using Workbook.LoadFromFile() method.
  • Set the Workbook.ConverterSetting.SheetFitToPage property as true to ensure the worksheet is rendered to one PDF page.
  • Get the first worksheet in the Workbook using Workbook.Worksheets[] property.
  • Loop through the columns in the worksheet and auto-fit the width of each column using Worksheet.AutoFitColumn() method.
  • Convert the CSV file to PDF 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("sample.csv", ",", 1, 1)

# Set the SheetFitToPage property as true
workbook.ConverterSetting.SheetFitToPage = True

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

# Autofit columns in the worksheet
i = 1
while i < sheet.Columns.Length:
    sheet.AutoFitColumn(i)
    i += 1

# Save the CSV file to PDF
workbook.SaveToFile("CSVToPDF.pdf", FileFormat.PDF)
workbook.Dispose()

Python: Convert CSV to PDF

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.

Published in Conversion
Thursday, 24 August 2023 00:54

Python: Convert Excel to Images

Converting Excel spreadsheets to image formats can be extremely valuable and versatile in a wide range of situations. Whether you need to share data with others who don’t have Excel installed on their devices, present information in a document or presentation, or publish content online, converting Excel to image format offers a convenient solution. In this article, we will introduce how to programmatically convert Excel to images 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 an Excel Worksheet to an Image in Python

You can easily convert a whole Excel worksheet to an image by using the Worksheet.SaveToImage() method provided by Spire.XLS for Python. The detailed steps are as follows:

  • Create a Workbook object.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get a specific worksheet by its index using Workbook.Worksheets[int index] property.
  • Convert the worksheet to an image using Worksheet.ToImage() method.
  • Save the image to a PNG file (you can also save the image as other image formats such as JPG and BMP).
  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()
# Load an Excel file
workbook.LoadFromFile("Sample.xlsx")

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

# Save the worksheet to an image
image = sheet.ToImage(sheet.FirstRow, sheet.FirstColumn, sheet.LastRow, sheet.LastColumn)
# Save the image to a PNG file
image.Save("SheetToImage.png")
workbook.Dispose()

Python: Convert Excel to Images

Convert an Excel Worksheet to an Image without White Margins in Python

When converting an Excel worksheet to an image, you may find the resulting image has unwanted white margins surrounding the cells. If you want to convert the worksheet to an image without any extraneous margins, you can remove the page margins set in the original worksheet. The detailed steps are as follows:

  • Create a Workbook object.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get a specific worksheet by its index using Workbook.Worksheets[int index] property.
  • Remove all margins from the worksheet by setting its left, right, top, and bottom margin values to zero.
  • Convert the worksheet to an image using Worksheet.ToImage() method.
  • Save the image to a PNG file.
  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()
# Load an Excel file
workbook.LoadFromFile("Sample.xlsx")

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

# Set all margins of the worksheet to zero
sheet.PageSetup.LeftMargin = 0
sheet.PageSetup.BottomMargin = 0
sheet.PageSetup.TopMargin = 0
sheet.PageSetup.RightMargin = 0

# Convert the worksheet to an image
image = sheet.ToImage(sheet.FirstRow, sheet.FirstColumn, sheet.LastRow, sheet.LastColumn)
# Save the image to a PNG file
image.Save("SheetToImageWithoutMargins.png")
workbook.Dispose()

Python: Convert Excel to Images

Convert a Specific Cell Range to an Image in Python

In addition to converting a whole worksheet to an image, Spire.XLS for Python also supports converting a specific cell range of a worksheet to an image. The detailed steps are as follows:

  • Create a Workbook object.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get a specific worksheet by its index using Workbook.Worksheets[int index] property.
  • Convert a specific cell range of the worksheet to an image using Worksheet.ToImage() method and pass the index of the start row, start column, end row, and end column of the cell range to the method as parameters.
  • Save the image to a PNG file.
  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()
# Load an Excel file
workbook.LoadFromFile("Sample.xlsx")

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

# Convert a specific cell range of the worksheet to an image
image = sheet.ToImage(5, 2, 17, 5)
# Save the image to a PNG file
image.Save("CellRangeToImage.png")
workbook.Dispose()

Python: Convert Excel to Images

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.

Published in Conversion

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.

Published in Conversion
Sunday, 25 June 2023 01:43

Python: Convert Excel to PDF

Converting Excel files to PDF format can be a useful way to share and distribute spreadsheets, especially if you want to ensure that the formatting and layout of the file remains consistent across different devices and software. In addition, PDFs often appear more polished and professional than Excel files, making them a popular choice for official reports, presentations, and other business documents. In this article, you will learn how to convert Excel to PDF 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 a Whole Excel Document to PDF in Python

The Workbook.SaveToFile() method is used to convert a complete Excel document into a single PDF file. Once the conversion is done, each worksheet will appear as a separate page in the resultant PDF file. To control the conversion settings, use the Workbook.ConverterSetting property.

The following are the detailed steps to convert an Excel document to a PDF file in Python.

  • Create a Workbook object.
  • Load an Excel document using Workbook.LoadFromFile() method.
  • Set the margins of every worksheet through Worksheet.PageSetup property, which will later become the blank edges of the generated PDF.
  • Set the Excel to PDF conversion options through the properties under Workbook.ConverterSetting object.
  • Convert the whole Excel document to PDF using Workbook.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")

# Iterate through the worksheets in the workbook
for sheet in workbook.Worksheets: 

    # Get the PageSetup object
    pageSetup = sheet.PageSetup

    # Set page margins
    pageSetup.TopMargin = 0.3
    pageSetup.BottomMargin = 0.3
    pageSetup.LeftMargin = 0.3
    pageSetup.RightMargin = 0.3

# Set worksheet to fit to page when converting
workbook.ConverterSetting.SheetFitToPage = True

# Convert to PDF file
workbook.SaveToFile("output/ToPdf.pdf", FileFormat.PDF)
workbook.Dispose()

Python: Convert Excel to PDF

Convert a Particular Worksheet to PDF in Python

The Worksheet.SaveToPdf() method is used to convert a specific worksheet into a PDF document. The detailed steps are as follows.

  • Create a Workbook object.
  • Load an Excel document using Workbook.LoadFromFile() method.
  • Get a particular worksheet through Workbook.Worksheets[] property.
  • Set the margins of the worksheet through Worksheet.PageSetup property, which will later become the blank edges of the generated PDF.
  • Set the Excel to PDF conversion options through the properties under Workbook.ConverterSetting object.
  • Convert the worksheet to PDF using Worksheet.SaveToPdf() 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\\input.xlsx")

# Get a particular worksheet
sheet = workbook.Worksheets[1]

# Get the PageSetup object
pageSetup = sheet.PageSetup

# Set page margins
pageSetup.TopMargin = 0.3
pageSetup.BottomMargin = 0.3
pageSetup.LeftMargin = 0.3
pageSetup.RightMargin = 0.3

# Set worksheet to fit to page when converting
workbook.ConverterSetting.SheetFitToPage = True

# Convert the worksheet to PDF file
sheet.SaveToPdf("output/WorksheetToPdf.pdf")
workbook.Dispose()

Python: Convert Excel to PDF

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.

Published in Conversion
Page 3 of 3