在 Python 中,可以采用 pandas、pyexcel、win32com 和 xls2xlsx 这四个模块,实现 xls 转 xlsx 格式。
以 Excel 示例文件 test_Excel.xls 为例,具体内容如下图所示:
安装命令
1 |
pip install pandas -i https://mirrors.aliyun.com/pypi/simple |
具体使用方法
1 2 3 4 5 6 7 |
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 文件同样只保留了文本,没有保留格式信息。
安装命令
1 |
python -m pip install pywin32 -i https://mirrors.aliyun.com/pypi/simple |
具体使用方法
1 2 3 4 5 6 7 8 9 10 11 12 |
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 文件可以同时保留文本和格式。
安装命令
1 |
pip install xlrd xls2xlsx -i https://mirrors.aliyun.com/pypi/simple |
具体使用方法
1 2 3 4 5 6 7 8 |
from xls2xlsx import XLS2XLSX #学习中遇到问题没人解答?小编创建了一个Python学习交流群:725638078 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 |
pip install pyexcel -i https://mirrors.aliyun.com/pypi/simple |
具体使用方法
1 2 3 4 5 |
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 文件同样只保留了文本,没有保留格式信息。