以下是在 Python 中实现 xls
文件转 xlsx
的 4 种方法:
方法一:使用 pandas
库
import pandas as pd def convert_xls_to_xlsx_pandas(xls_file_path, xlsx_file_path): data = pd.read_excel(xls_file_path) data.to_excel(xlsx_file_path, index=False)
方法二:使用 openpyxl
库
from openpyxl import load_workbook from openpyxl import Workbook def convert_xls_to_xlsx_openpyxl(xls_file_path, xlsx_file_path): wb = load_workbook(xls_file_path) new_wb = Workbook() for sheet_name in wb.sheetnames: ws = wb[sheet_name] new_ws = new_wb.create_sheet(sheet_name) for row in ws.iter_rows(): for cell in row: new_ws[cell.coordinate].value = cell.value new_wb.save(xlsx_file_path)
方法三:使用 xlrd
和 xlwt
库
import xlrd import xlwt def convert_xls_to_xlsx_xlrd_xlwt(xls_file_path, xlsx_file_path): workbook = xlrd.open_workbook(xls_file_path) new_workbook = xlwt.Workbook() for sheet_index in range(workbook.nsheets): sheet = workbook.sheet_by_index(sheet_index) new_sheet = new_workbook.add_sheet(sheet.name) for row_index in range(sheet.nrows): for col_index in range(sheet.ncols): new_sheet.write(row_index, col_index, sheet.cell_value(row_index, col_index)) new_workbook.save(xlsx_file_path)
方法四:使用 win32com
库(在 Windows 系统中)
import win32com.client def convert_xls_to_xlsx_win32com(xls_file_path, xlsx_file_path): excel = win32com.client.Dispatch("Excel.Application") workbook = excel.Workbooks.Open(xls_file_path) workbook.SaveAs(xlsx_file_path, 51) # 51 代表 xlsx 格式 workbook.Close() excel.Quit()
例如,如果您有一个 example.xls
文件,想要将其转换为 converted.xlsx
,可以使用上述方法中的任何一种,并传入相应的文件路径进行转换。