Python中4种方法实现 xls 文件转 xlsx
warning:
这篇文章距离上次修改已过437天,其中的内容可能已经有所变动。
在Python中,可以使用openpyxl、xlrd和pandas库将.xls文件转换为.xlsx。以下是实现这一功能的四种方法:
- 使用
pandas库。 - 使用
openpyxl和xlrd读取.xls文件,然后用openpyxl写入.xlsx。 - 使用
xlrd和openpyxl读取和写入。 - 使用
pandas和openpyxl。
以下是每种方法的示例代码:
import pandas as pd
# 方法1: 使用pandas
def convert_to_xlsx_1(input_file, output_file):
df = pd.read_excel(input_file)
df.to_excel(output_file, index=False)
# 方法2: 使用openpyxl和xlrd
import xlrd
from openpyxl import Workbook
def convert_to_xlsx_2(input_file, output_file):
workbook = Workbook()
sheet = workbook.active
xls_workbook = xlrd.open_workbook(input_file)
xls_sheet = xls_workbook.sheet_by_index(0)
for i in range(xls_sheet.nrows):
sheet.append(xls_sheet.row_values(i))
workbook.save(output_file)
# 方法3: 使用xlrd和openpyxl
import xlrd
from openpyxl import Workbook
def convert_to_xlsx_3(input_file, output_file):
workbook = Workbook()
sheet = workbook.active
xls_workbook = xlrd.open_workbook(input_file)
xls_sheet = xls_workbook.sheet_by_index(0)
for i in range(xls_sheet.nrows):
for j in range(xls_sheet.ncols):
sheet.cell(row=i+1, column=j+1, value=xls_sheet.cell(i, j).value)
workbook.save(output_file)
# 方法4: 使用pandas和openpyxl
import pandas as pd
from openpyxl import Workbook
def convert_to_xlsx_4(input_file, output_file):
df = pd.read_excel(input_file)
writer = pd.ExcelWriter(output_file, engine='openpyxl')
df.to_excel(writer, index=False)
writer.save()
# 使用函数
convert_to_xlsx_1('input.xls', 'output.xlsx')
convert_to_xlsx_2('input.xls', 'output.xlsx')
convert_to_xlsx_3('input.xls', 'output.xlsx')
convert_to_xlsx_4('input.xls', 'output.xlsx')在这些示例中,假设输入文件名为input.xls,输出文件名为output.xlsx。每个函数都会将input.xls转换为output.xlsx。请确保在运行这些示例之前已经安装了所需的库(pandas, openpyxl, 和 xlrd)。
评论已关闭