Hướng dẫn pandas add header to excel file - gấu trúc thêm tiêu đề vào tệp excel

Một ví dụ về việc chuyển đổi DataFrame của Pandas thành tệp Excel với định dạng tiêu đề do người dùng xác định bằng Pandas và XLSXWriter.

##############################################################################
#
# An example of converting a Pandas dataframe to an xlsx file
# with a user defined header format.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright 2013-2022, John McNamara, 
#

import pandas as pd

# Create a Pandas dataframe from some data.
data = [10, 20, 30, 40, 50, 60]
df = pd.DataFrame({'Heading': data,
                   'Longer heading that should be wrapped' : data})

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter("pandas_header_format.xlsx", engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object. Note that we turn off
# the default header and skip one row to allow us to insert a user defined
# header.
df.to_excel(writer, sheet_name='Sheet1', startrow=1, header=False)

# Get the xlsxwriter workbook and worksheet objects.
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

# Add a header format.
header_format = workbook.add_format({
    'bold': True,
    'text_wrap': True,
    'valign': 'top',
    'fg_color': '#D7E4BC',
    'border': 1})

# Write the column headers with the defined format.
for col_num, value in enumerate(df.columns.values):
    worksheet.write(0, col_num + 1, value, header_format)

# Close the Pandas Excel writer and output the Excel file.
writer.save()

Tôi có nhiều khung dữ liệu trông như thế này, dữ liệu không liên quan.

Hướng dẫn pandas add header to excel file - gấu trúc thêm tiêu đề vào tệp excel

Tôi muốn nó trông như thế này, tôi muốn chèn một tiêu đề trên các tiêu đề cột.

Hướng dẫn pandas add header to excel file - gấu trúc thêm tiêu đề vào tệp excel

Tôi muốn kết hợp chúng thành nhiều tab trong một tệp excel.

Có thể thêm một hàng khác trên các tiêu đề cột và chèn một tiêu đề vào ô đầu tiên trước khi lưu tệp vào Excel.

Tôi hiện đang làm điều đó như thế này.

with pd.ExcelWriter('merged_file.xlsx',engine='xlsxwriter') as writer:
    for filename in os.listdir(directory):
        if filename.endswith('xlsx'):
            print(filename)
            if 'brands' in filename:
                some function
            elif 'share' in filename:
                somefunction
            else:
                some function
            df.to_excel(writer,sheet_name=f'{filename[:-5]}',index=True,index_label=True)
writer.close()

Nhưng sheet_name quá dài, đó là lý do tại sao tôi muốn thêm tiêu đề trên các tiêu đề cột.

Tôi đã thử mã này,

columns = df.columns
columns = list(zip([f'{filename[:-5]}'] * len(df.columns), columns))             
columns = pd.MultiIndex.from_tuples(columns) 
df2 = pd.DataFrame(df,index=df.index,columns=columns) 
df2.to_excel(writer,sheet_name=f'{filename[0:3]}',index=True,index_label=True)

Nhưng cuối cùng nó trông như thế này với tất cả dữ liệu đã biến mất,

Hướng dẫn pandas add header to excel file - gấu trúc thêm tiêu đề vào tệp excel

Nó sẽ giống như thế này

Hướng dẫn pandas add header to excel file - gấu trúc thêm tiêu đề vào tệp excel