Converting Excel (XLS/XLSX) to TXT in Python

Andrew Wilson
2 min readMar 22, 2024

--

TXT files are a simple, versatile, and easily manageable text format. For handling large datasets, converting Excel spreadsheets to TXT files can enhance processing efficiency. Furthermore, numerous programming languages and data processing tools provide built-in capabilities for reading and manipulating TXT files, which makes converting Excel to text files a practical choice for simplifying the data import process.

In this article, we will explore how to programmatically convert Excel to TXT with Python.

Python Excel to TXT Converter

In the below guide, we have used the third-party library — Spire.XLS for Python. It is a powerful Python Excel library for processing, reading and converting XLS or XLSX files. To install it, use the following pip command:

pip install Spire.XLS

Method for Converting Excel to Text Files

The main method used to convert an Excel worksheet to TXT file is the Worksheet.SaveToFile(fileName: str, separator: str, encoding: Encoding) method. You can the specify your desired output file name, separator (e.g. commas, tabs, semicolons, etc.), and the encoding format (e.g. UTF-8, Unicode, ASCII, etc.).

Python Code:

import os
import sys
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)
from spire.xls import *
from spire.xls.common import *

# Create a Workbook instance
workbook = Workbook()

# Load an Excel file
workbook.LoadFromFile("input.xlsx")

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

# Save the worksheet as a TXT file
sheet.SaveToFile("ExceltoText.txt", " ", Encoding.get_UTF8())
workbook.Dispose()
Python Excel to TXT

The Spire.XLS for Python library also supports converting Excel to CSV, PDF, image, HTML and many other file formats. Click to find more demos:

--

--

Andrew Wilson
Andrew Wilson

Written by Andrew Wilson

Explore C#, Java and Python solutions for processing Word/Excel/PowerPoint/PDF files.

No responses yet