Python 实现 xls 文件转 xlsx 的若干方法

发布时间 2023-10-29 15:03:58作者: klchang

在 Python 中,可以采用 pandas、pyexcel、win32com 和 xls2xlsx 这四个模块,实现 xls 转 xlsx 格式。

以 Excel 示例文件 test_Excel.xls 为例,具体内容如下图所示:

 

 pandas 

安装命令

pip install pandas -i https://mirrors.aliyun.com/pypi/simple

具体使用方法

import pandas as pd

filename = "test_Excel.xls"
outfile = "test_Excel-pandas.xlsx"
# Read Excel xls file
data = pd.read_excel(filename)
# Write to xlsx file with no row index
data.to_excel(outfile, index=False)

注:上面的方法输出的 xlsx 文件只保留了文本,没有保留格式信息。

 

pyexcel

安装命令

pip install pyexcel -i https://mirrors.aliyun.com/pypi/simple

具体使用方法

import pyexcel

filename = "test_Excel.xls"
outfile = "test_Excel-pyexcel.xlsx"
# Convert xls file to xlsx directly
pyexcel.save_book_as(file_name=filename, dest_file_name=outfile)

注:上面的方法输出的 xlsx 文件同样只保留了文本,没有保留格式信息。

 

win32com

安装命令

python -m pip install pywin32 -i https://mirrors.aliyun.com/pypi/simple

具体使用方法

import os
import win32com.client as win32

filename = "test_Excel.xls"
outfile = "test_Excel-win32.xlsx"
# Open up Excel 
excel = win32.gencache.EnsureDispatch("Excel.Application")
# Open xls file
wb = excel.Workbooks.Open(os.path.abspath(filename))
# Save as xlsx file
wb.SaveAs(os.path.abspath(outfile), FileFormat=51)
wb.Close()
excel.Application.Quit()

注:win32com 模块只适用于已安装 Excel 软件的Windows 系统下,但输出的 xlsx 文件可以同时保留文本和格式。

 

xls2xlsx

安装命令

pip install xlrd xls2xlsx -i https://mirrors.aliyun.com/pypi/simple

具体使用方法

from xls2xlsx import XLS2XLSX

filename = "test_Excel.xls"
outfile = "test_Excel-x2x.xlsx"
# Read xls file
x2x = XLS2XLSX(filename)
# Write to xlsx file
x2x.to_xlsx(outfile)

注:使用上面的方法得到的 xlsx 文件可以同时保留文本和格式信息,并且不依赖于 Windows 系统和 Excel 程序。

 

参考资料

[1] pandas: powerful Python data analysis toolkit. https://github.com/pandas-dev/pandas

[2] pyexcel: single API for reading, manipulating and writing data in csv, ods, xls, xlsx and xlsm files. https://github.com/pyexcel/pyexcel 

[3] win32com: Python for Windows (pywin32) Extensions. https://github.com/mhammond/pywin32

[4] xls2xlsx: convert xls file to xlsx (in Python 3). https://github.com/snoopyjc/xls2xlsx