[英]How to Merge all worksheets within the same excel workbook using Xlwings & Python
I'm trying to Merge all Worksheets within the same Excel Workbook using Xlwings if anyone could please advise on how this could be done?我正在尝试使用 Xlwings 合并同一 Excel 工作簿中的所有工作表,如果有人可以请告知如何做到这一点?
The code below is able to grab all worksheets and combine them into a created output file but the worksheet tabs remain separated instead of being merged.下面的代码能够抓取所有工作表并将它们组合到创建的输出文件中,但工作表选项卡保持分离而不是合并。
import xlwings as xw
import glob
import sys
folder = sys.argv[1]
inputFile = sys.argv[2]
outputFile = sys.argv[3]
path = r""+folder+""
excel_files = glob.glob(path + "*" + inputFile + "*")
with xw.App(visible=False) as app:
combined_wb = app.books.add()
for excel_file in excel_files:
print(excel_file)
wb = app.books.open(excel_file)
for sheet in wb.sheets:
sheet.copy(after=combined_wb.sheets[0])
wb.close()
combined_wb.sheets[0].delete()
combined_wb.save(outputFile)
combined_wb.close()
You will need to do something like this;你需要做这样的事情;
Select the [used] cells in the sheet and then copy/paste to the combined_wb sheet[X].选择工作表中的 [used] 单元格,然后复制/粘贴到 combined_wb 工作表 [X]。
The example below modifies your code somewhat to do that, and pastes down column A separating each sheet contents by 10 rows.下面的示例稍微修改了您的代码以执行此操作,并将 A 列粘贴到将每个工作表内容分隔 10 行。 Obviously you'd need to determine where each original sheet gets pasted into that one sheet in combined_wb.
显然,您需要确定将每个原始工作表粘贴到 combine_wb 中的那个工作表的位置。
Note;笔记; this copy/paste should also include the data styling like font name, color, size and format.
此复制/粘贴还应包括数据样式,如字体名称、颜色、大小和格式。
new_row = 1
with xw.App(visible=False) as app:
combined_wb = app.books.add()
for excel_file in excel_files:
print(excel_file)
wb = app.books.open(excel_file)
ws = wb.sheets[0]
ws.used_range.copy()
# for sheet in wb.sheets:
# sheet.copy(after=combined_wb.sheets[0])
combined_wb.sheets[0].range('A{0}'.format(new_row)).paste(paste='all')
wb.close()
new_row += 10
# combined_wb.sheets[0].delete()
combined_wb.save(outputFile)
combined_wb.close()
You could loop over the worksheets and use an index on the range object of used_range
, ie used_range[-1:,:]
to position the worksheets in a output workbook/worksheet.您可以遍历工作表并在
used_range
的范围对象上使用索引,即used_range[-1:,:]
将工作表定位在输出工作簿/工作表中。
import xlwings as xw
path_input = r"C:\Users\trunk\Desktop\Tab1.xlsx"
path_save = r"C:\Users\trunk\Desktop\finished.xlsx"
with xw.App(visible=False) as app:
wb_init = xw.Book(path_input)
wb_res = xw.Book()
sheets = wb_init.sheets
ws_res = wb_res.sheets[0]
for ws in sheets:
ws.used_range.copy()
ws_res.used_range[-1:,:].offset(row_offset=1).paste()
ws_res["1:1"].delete() # This is just to delete the first row, which is empty.
wb_res.save(path_save)
wb_res.close(); wb_init.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.