繁体   English   中英

如何使用 Xlwings 和 Python 合并同一个 Excel 工作簿中的所有工作表

[英]How to Merge all worksheets within the same excel workbook using Xlwings & Python

我正在尝试使用 Xlwings 合并同一 Excel 工作簿中的所有工作表,如果有人可以请告知如何做到这一点?

下面的代码能够抓取所有工作表并将它们组合到创建的输出文件中,但工作表选项卡保持分离而不是合并。

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()

你需要做这样的事情;
选择工作表中的 [used] 单元格,然后复制/粘贴到 combined_wb 工作表 [X]。
下面的示例稍微修改了您的代码以执行此操作,并将 A 列粘贴到将每个工作表内容分隔 10 行。 显然,您需要确定将每个原始工作表粘贴到 combine_wb 中的那个工作表的位置。
笔记; 此复制/粘贴还应包括数据样式,如字体名称、颜色、大小和格式。

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()

您可以遍历工作表并在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM