python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python  xls转 xlsx

Python中实现 xls 文件转 xlsx的4种方法(示例详解)

作者:Python热爱者

在 Python 中,可以采用 pandas、pyexcel、win32com 和 xls2xlsx 这四个模块,实现 xls 转 xlsx 格式,本文以 Excel 示例文件test_Excel.xls 为例结合示例代码给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧

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

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

在这里插入图片描述

1.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 文件同样只保留了文本,没有保留格式信息。

2.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 文件可以同时保留文本和格式。

3.xls2xlsx

安装命令

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

具体使用方法

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 程序。

4.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 文件同样只保留了文本,没有保留格式信息。

到此这篇关于Python中实现 xls 文件转 xlsx的4种方法的文章就介绍到这了,更多相关Python xls 文件转 xlsx内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文