[Python] Combine multiple Excel sheets into one

Excel for Mac is quite inconvenient because you cannot specify multiple tables at once when creating a pivot table. (It should have been done in the old version ...) First of all, we will make it easier to handle the data by combining the data of multiple sheets into one sheet with python.

Library used

Use openpyxl. It is a library for performing operations such as reading and writing Excel. https://openpyxl.readthedocs.io/en/stable/

Advance preparation

Install openpyxl

pip install openpyxl

Read file

#Read file
read_path = "./input.xlsx"
output_path = "./output.xlsx"
wb = load_workbook(read_path)

Get data for all sheets

#Get data for all sheets
sheet_names = wb.get_sheet_names()
first_row = 1
l_2d_output = []
for sheet_name in sheet_names:
    sheet = wb.get_sheet_by_name(sheet_name)
    
    for row in sheet.iter_rows(min_row=first_row):
        l = []
        for cell in row:
            l.append(str(cell.value))
        l_2d_output.append(l)
        
    #Skip reading headers from next sheet
    first_row = 2

writing

#Write to file
def write_list_2d(sheet, l_2d, start_row, start_col):
    for y, row in enumerate(l_2d):
        for x, cell in enumerate(row):
            sheet.cell(row=start_row + y,
                       column=start_col + x,
                       value=l_2d[y][x])

#writing
output_wb = openpyxl.Workbook()
output_ws = output_wb.active
write_list_2d(output_ws, l_2d_output, 1, 1)
output_wb.save(output_path)

Finally

The code has too much room for improvement, I was able to use it as much as I used, so I'm happy with it.

Recommended Posts

[Python] Combine multiple Excel sheets into one
Combine multiple python files into one python file
[Python & Unix] Combine multiple PDF files into one.
Combine multiple Excel files loaded using pandas into one
Combine python function arguments into one variable
Python that merges a lot of excel into one excel
Combine accessors into one method
Combine multiple csv files into one csv file with python (assuming only one line of header)
Consolidate multiple disks into one using LVM
Put text scraped in Python into Google Sheets
Multiple graphs are displayed in one window (python)
Excel with Python
Python text reading for multiple lines and one line
One liner in Python
[Python] Create multiple directories
Run python from excel
Handle Excel with python
Python programming in Excel
Python pdf cheat sheets
Operate Excel with Python (1)
Operate Excel with Python (2)
[Python] Send gmail with python: Send one by one with multiple image files attached
Manipulate the clipboard in Python and paste the table into Excel
Stylish technique for pasting CSV data into Excel with Python