Skip to main content

Command Palette

Search for a command to run...

How to Convert Excel to TXT and Vice Versa in Python [Step-by-step Guide]

Published
4 min read

Ever needed to share your Excel data as plain text or turn a TXT report back into a spreadsheet? Converting between Excel and TXT files in Python makes this quick and hassle-free — whether you’re preparing data for analysis, exporting reports, or automating routine file tasks.

This guide will introduce how to convert Excel to TXT and vice versa using Spire.XLS for Python, a powerful Excel library, helping you complete the task quickly and easily.

Excel vs TXT: Reasons to Convert

Excel offers powerful tools for organizing, calculating, and visualizing data. It supports formulas, charts, and conditional formatting, making it perfect for analysis and reporting. However, Excel files can be large, slower to process in scripts, and less compatible with systems that rely on plain text input. They also carry formatting and metadata that aren’t always necessary for data exchange.

TXT, on the other hand, is lightweight, universally compatible, and easy to read across different platforms. It’s ideal for data transfer, logging, or feeding into programs that require raw text input. The downside is that TXT files lack structure, formulas, and formatting, which limits their use for complex data analysis or presentation.

Converting between Excel and TXT allows you to move seamlessly between structured, interactive data and simple, portable formats—ensuring flexibility in both automation and collaboration.

How to Convert Excel to TXT with Python in 3 Steps

After understanding the strengths and weaknesses of both Excel and TXT formats, let’s move on to our first topic — how to convert an Excel file to TXT. Since TXT is a plain text format, it’s easier to share, process, and use across different platforms or applications.

With Spire.XLS, the conversion only takes three simple steps: load the source Excel file, select the worksheet to export, and use the Worksheet.SaveToFile() method to save it as a TXT file.

The following code example shows how to convert the first worksheet in an Excel workbook to a TXT file.

from spire.xls import *
from spire.xls.common import *

# Load an Excel file
workbook = Workbook()
workbook.LoadFromFile("/input/Population.xlsx")

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

# Save the worksheet to a txt file
sheet.SaveToFile("/output/ExceltoTXT.txt", " ", Encoding.get_UTF8())
workbook.Dispose()

Here’s the preview of the result file:

Alt: How to Convert Excel Files to TXT Documents in Python

Easily Convert TXT to Excel in Python without Losing Format

Converting a TXT file back into an Excel sheet makes it easier to verify, analyze, and study data—an essential step in data analysis. When performing this task in Python, it’s important to pay attention to how the text is separated. For instance, if a cell contains multiple words, the content is often enclosed in quotation marks. In such cases, the csv module can automatically handle spaces and quotes, but the reader configuration should be adjusted based on the actual structure of your TXT file.

The following example demonstrates how to convert the TXT file extracted in the previous section back into an Excel file, along with the key steps involved in the process.

from spire.xls import *
from spire.xls.common import *
import csv

# Read TXT file line by line
with open("/output/ExceltoTXT.txt", "r", encoding="utf-8") as file:
    # Process spaces within quotes
    reader = csv.reader(file, delimiter=' ', quotechar='"', skipinitialspace=True)
    data = [list(filter(None, row)) for row in reader]  # Remove empty strings

# Create an Excel Workbook
workbook = Workbook()

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

# Loop through data and write to Excel
for row_num, row_data in enumerate(data):
    for col_num, cell_data in enumerate(row_data):
        sheet.Range[row_num + 1, col_num + 1].Value = cell_data
        # Set bold for title row
        sheet.Range[1, col_num + 1].Style.Font.IsBold = True

# Autofit columns
sheet.AllocatedRange.AutoFitColumns()

# Save the Excel file
workbook.SaveToFile("/output/TXTtoExcel1.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Here is the preview of the converted Excel file:

How to Convert TXT to Excel in Python Easily

To Wrap Up

Whether converting Excel to TXT for easier sharing or transforming TXT back into Excel for analysis and organization, mastering these conversions can significantly improve workflow efficiency. With Spire.XLS, these tasks can be performed quickly and accurately while maintaining data integrity. Choosing the appropriate format and conversion method based on your specific needs ensures smooth and effective data handling.

Check out my homepage for more tutorials about processing Excel files in Python!