即使行范围从 1 到 2000,列范围从 1 到 50,代码在保存工作簿时会抛出索引错误。这是代码:
import pandas as pd
import openpyxl
from openpyxl import Workbook, load_workbook
files= ["psi.xlsx", "vsi.xlsx", "log_odds.xlsx", "KS.xlsx"]
output_file = "supplemental.xlsx"
workbook= openpyxl.Workbook()
workbook.save(output_file)
for file in files:
wb= openpyxl.load_workbook(file)
output_wb= openpyxl.load_workbook(output_file)
for sheet_name in wb.sheetnames:
ws= wb[sheet_name]
if sheet_name in output_wb.sheetnames:
output_wb.remove(output_wb[sheet_name])
output_sheet= output_wb.create_sheet(sheet_name)
for row in range(1, 2000):
for col in range(1, 50):
output_sheet.cell(row, col).value= ws.cell(row, col).value
output_sheet.cell(row, col)._style= ws.cell(row, col)._style
output_wb.save(output_file)
我之前曾尝试过不同的做法,但它在保存时也抛出了索引错误。
for row in ws.iter_rows():
for cell in row:
output_sheet[cell.coordinate].value=ws[cell.coordinate].value
output_sheet[cell.coordinate]._style=ws[cell.coordinate]._style
你能帮我找出问题所在吗? 还有什么更简单的解决方案可以在保留格式的同时将多个 excel 文件复制到一个最终的 excel 文件中?