优化代码,使写入的数据与“汇总表”文字格式一致:import openpyxl # 打开申请表工作簿和汇总表工作簿 wb_app = openpyxl.load_workbook('申请名单.xlsx') wb_sum = openpyxl.load_workbook('汇总表.xlsx') # 获取申请表Sheet1和汇总表Sheet1 ws_app = wb_app['Sheet1'] ws_sum = wb_sum['Sheet1'] # 复制申请表数据到汇总表底部 for row in ws_app.iter_rows(min_row=2, values_only=True): ws_sum.append(row) # 保存汇总表工作簿 try: wb_sum.save('汇总表.xlsx') except Exception as e: print('保存汇总表失败,错误信息:', e) finally: # 关闭两个工作簿 wb_app.close() wb_sum.close()
时间: 2023-07-16 14:12:56 浏览: 109
import openpyxl
# 打开申请表工作簿和汇总表工作簿
wb_app = openpyxl.load_workbook('申请名单.xlsx')
wb_sum = openpyxl.load_workbook('汇总表.xlsx')
# 获取申请表Sheet1和汇总表Sheet1
ws_app = wb_app['Sheet1']
ws_sum = wb_sum['Sheet1']
# 复制申请表数据到汇总表底部
for row in ws_app.iter_rows(min_row=2, values_only=True):
ws_sum.append(row)
# 使写入的数据与“汇总表”文字格式一致
for col in ws_sum.columns:
max_length = 0
column = col[0].column_letter
# 找到最长的单元格
for cell in col:
try:
if len(str(cell.value)) > max_length:
max_length = len(str(cell.value))
except:
pass
# 根据最长的单元格设置列宽
adjusted_width = (max_length + 2)
ws_sum.column_dimensions[column].width = adjusted_width
# 保存汇总表工作簿
try:
wb_sum.save('汇总表.xlsx')
except Exception as e:
print('保存汇总表失败,错误信息:', e)
finally:
# 关闭两个工作簿
wb_app.close()
wb_sum.close()
阅读全文