Location>code7788 >text

Python implementation of Excel and TXT text format conversion between each other

Popularity:322 ℃/2024-07-22 14:55:22

Python Convert Excel to TXT Text File

The main methods used to convert Excel worksheets to TXT text format are(fileName: str, separator: str, encoding: Encoding) method. We can specify the desired output filename, delimiter (e.g. comma, tab, semicolon, etc.) and encoding format (e.g. UTF-8, Unicode, ASCII, etc.).

The Python sample code for converting Excel XLS/XLSX format to TXT file is as follows:

from  import *
from  import *
 
# Load a .xls or .xlsx file
workbook = Workbook()
("Quotation.xlsx")
 
# Getting the first worksheet
sheet = [0]
 
# Save worksheet as txt text file
("Excel to TXT Text.txt", " ", Encoding.get_UTF8())
()

Rendering:

 

Python Import TXT Text Data to Excel File

To use for Python to convert a TXT text file to Excel, we need to read the data in the text file line by line, remove the first and last whitespace characters, and then use thesplit() The method splits the data by separator and stores it in a list, and finally fills the list with the data in the corresponding Excel cells.

The Python example code for reading TXT text data and writing it to an Excel XLS/ XLSX file is as follows:

from  import *
from  import *
 
# Read TXT text files line by line
with open("Excel to TXT Text.txt", "r", encoding='utf-8') as file:
    lines = ()
 
# Remove the first and last blank characters of each line of text data, then split the data with a space as a separator and store it in a list.
data = [().split(" ") for line in lines]
 
# Creating Excel Workbooks
workbook = Workbook()
 
# Getting the first worksheet
sheet = [0]
 
# Iterate through each row and column in the list and populate the data into the corresponding Excel cells
for row_num, row_data in enumerate(data):
    for col_num, cell_data in enumerate(row_data):
        [row_num + 1, col_num + 1].Value = cell_data
        # Set title line font to bold
        [1, col_num + 1]. = True
 
# Automatic column width adjustment
()
 
# Save as .xlsx (or .xls) file
("TXT transfer", ExcelVersion.Version2016)
()

Rendering:


 

The for Python library supports a variety of Excel conversion functions, such asExcel and CSV InterconversionExcel to PDFExcel to PictureExcel to HTML as well asExcel to XMLetc. Click for more examples:

/xlsforpython/