python结合xlrd和xlwt操作已有excel文件(不改变格式)

tech2025-12-16  3

python结合xlrd和xlwt操作已有excel文件(不改变格式)

使用中间库xlutils

Pip install xlutils

直接源码

import xlrd from xlutils.filter import process, XLRDReader, XLWTWriter import glob def Change_yaer(file_list): log = open('error_log.txt','w') for file in file_list: print(file) file_name = file.split('.')[0].split('\\')[-1] try: rb = xlrd.open_workbook(file,formatting_info=True) #创建xlwt实例,实际为copy方法的解封装,可查看源码 w = XLWTWriter() #process进行xlrd与xlwt间操作,复制一份。 process(XLRDReader(rb, 'unknown.xls'), w) #w.output[0][1]为copy后返回的对象 wb = w.output[0][1] #style_list为原文件的单元格格式信息,列表对象 style_list = w.style_list for n, sheet in enumerate(rb.sheets()): sheet2 = wb.get_sheet(n) for r in range(sheet.nrows): for c, cell in enumerate(sheet.row_values(r)): #若循环到第一个sheet的(3,6)单元格,修改值为2020 if n==0 and r == 3 and c == 6: values = '2020' else: values = sheet.cell_value(r,c) style = style_list[sheet.cell_xf_index(r, c)] sheet2.write(r, c, values, style) wb.save(f'{file_name}.xls') except Exception as e: log.write(file_name+e+'\n') log.close()
最新回复(0)