首页 > 解决方案 > 如何使用带有索引的 OpenPyXl 将多级索引导出到 excel

问题描述

如何使用带有列标题和索引值的openpyxl将 pandas **多索引数据框 ** 的结果导出到 excel 中?

我假设我需要在 dataframe_to_rows() 方法中设置 index=True 。但是,当我这样做时,它会抛出一个 ValueError:说明它无法将 IndexLabel 值转换为 excel。例如:

ValueError:无法将('Elf','Elrond')转换为 Excel

我期望加载到 excel 中的内容与此类似:

在此处输入图像描述

我当前的代码

import openpyxl
from openpyxl import Workbook
from openpyxl.utils.dataframe import dataframe_to_rows
from pathlib import Path

multi_df = df.set_index(['Film', 'Chapter', 'Race', 'Character']).sort_index()
subset_df = multi_df.loc[('The Fellowship Of The Ring', '01: Prologue'), :]

# Read in TEMPLATE file from which a copy of the Template will be populated 
outfile = 'TEST_Pivot2XL_TEMPLATE.xlsx'
template_filename = 'YYMMDD-YYMMDD_LOTR_TEMPLATE.xlsx'
wb = openpyxl.load_workbook(Path(Path.cwd() / "ReportFiles" / "Summary" / str(template_filename)))

ws = wb["myPivot"]
for r in dataframe_to_rows(subset_df, index=True, header=True):
    ws.append(r)

wb.save(file)

注意:我有一个现有的 excel 模板文件,其中包含一个标题为“myPivot”的空工作表,我想将数据透视表写入其中。

我使用的数据集在这里: https ://www.kaggle.com/mokosan/lord-of-the-rings-character-data?select=WordsByCharacter.csv

标签: pythonexcelpandasopenpyxlmulti-index

解决方案


似乎这应该为您解决问题:

import pandas as pd
from openpyxl import load_workbook

df = pd.DataFrame({('A', 'A1'): [1, 2, 3],
              ('A', 'A2'): [4, 5, 6],
              ('B', 'B1'): [7, 8, 9]}).T
print(f'original dataframe:\n {df.head()}')
filename = 'test.xlsx'
writer = pd.ExcelWriter(filename, engine='openpyxl', mode='a')
writer.book = load_workbook(filename)
writer.sheets = dict((ws.title, ws) for ws in writer.book.worksheets)
df.to_excel(writer, 'sheet1')
writer.save()

输出:

original dataframe:
       0  1  2
A A1  1  2  3
  A2  4  5  6
B B1  7  8  9

Excel文件:
在此处输入图像描述

test.xlsx工作目录中应该存在一个名为的文件,代码才能正常工作。请注意,它将写入工作表的开头,而不是附加到已经存在的内容。

ps - 分配writer.bookwriter.sheets似乎无用,但ExcelWriter使用它们来确定哪些工作表已经存在,而不是写新的工作表。


推荐阅读