Python 实现 xls 文件转 xlsx 的若干方法
在 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
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 上周热点回顾(2.17-2.23)
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)