Use openpyxl to merge multiple sheets into one sheet

        This chapter introduces the application of openpyxl—merging multiple sheets into one sheet. Here we have a randomly generated fake data of each class's grades, the purpose is to merge these 5 sheets into one.

        Go directly to the code:

import openpyxl
file = openpyxl.load_workbook(r"D:\临时\python试验\openpyxl\把多个sheet表合并成一个sheet表.xlsx")
sheets = file.worksheets       # 获取文件中的所有sheet表

new_sheet = file.create_sheet('各班合并后')       # 在文件中新建一个表,用于存放合并后的数据
new_sheet.append(['班级','姓名','语文','数学','英语','综合科'])      # 先把表头加上

for sheet in sheets:
    for row in sheet.iter_rows(2,sheet.max_row,1,sheet.max_column): # 从第二行开始,不包括表头
        row_list = [i.value for i in row]
        new_sheet.append(row_list)

file.save(r"D:\临时\python试验\openpyxl\各班合并后.xlsx")

        You must understand the meaning of each step by yourself, otherwise you will not know how to do it if the table is changed.

        The order of the code in line 3 is very important, you must first get all the tables in the file, and then create a new table. If you create a new table first and then get all the tables, then the new table will be read and written to the new table again when writing later, which will lead to data duplication.

        Since each table has a header, we start traversing from the second row. But in this way, the new table has no header, so first write the header in the new table, and then read the table of each shift to write data.

        The result of the operation is as follows:

        You can also use openpyxl flexibly, such as deleting the tables of each class after the merger, leaving only the merged table; creating a new file, writing the merged table into a new excel file; freezing cell B1 of the merged table Wait, as long as you have an idea, you can try it. If you try a lot, you will naturally be proficient and able to use it flexibly.

        The excel file in this article: Link: https://pan.baidu.com/s/1KVxFe3qNTYdu8GxT_CUHVg?pwd=f5zx 
Extraction code: f5zx

Guess you like

Origin blog.csdn.net/m0_71559726/article/details/130368007