我想将列表中的几个
xlsx
文件合并为一个文件,这样每个sheet
都有下一个合并文件的name
。单个 xlsx
文件有一个 sheet
和 data
存储在列和行中。要创建单个文件,我正在使用 openpyxl
库。
xlsx_files = ['u_gen_inf.xlsx', 'u_dates_inf.xlsx', 'u_ctrl_inf.xlsx']
循环我想创建
from openpyxl import load_workbook, Workbook
for f in xlsx_files:
? load_workbook() - universal code independent of the number of xlsx files
wb_master.save('master_users_inf.xlsx')
你很接近,你只需要实现(在你的
for
循环内)create_sheet
在主文件中创建一个新工作表,然后使用iter_rows
从所有行中获取所有值.
这里是一个命题(没有你的评论来做一个简短的代码):
from openpyxl import load_workbook, Workbook
wb_master = Workbook()
xlsx_files = ['u_gen_inf.xlsx', 'u_dates_inf.xlsx', 'u_ctrl_inf.xlsx']
for f in xlsx_files:
sub_wb = load_workbook(f)
sub_ws = sub_wb.active
wb_master_sheet = wb_master.create_sheet(sub_ws.title)
for row in sub_ws.iter_rows():
for cell in row:
wb_master_sheet[cell.coordinate].value = cell.value
#wb_master_sheet.column_dimensions["A"].width = 20 #uncomment this line to set a width
wb_master.remove_sheet("Sheet") #or del wb_master["Sheet"]
wb_master.save('master_users_inf.xlsx')