从数据框字典创建 Excel 个表

Create Excel Tables from Dictionary of Dataframes

我有数据框字典。

dd = {
'table': pd.DataFrame({'Name':['Banana'], 'color':['Yellow'], 'type':'Fruit'}),
'another_table':pd.DataFrame({'city':['Atlanta'],'state':['Georgia'], 'Country':['United States']}),
'and_another_table':pd.DataFrame({'firstname':['John'], 'middlename':['Patrick'], 'lastnme':['Snow']}),
     }

我想创建一个 Excel 文件,其中包含从这些数据帧创建的 Excel Table 个对象。每个 Table 都需要位于单独的 Tab/Sheet 上,并且 Table 名称应与数据框名称相匹配。

这可能与 Python 相关吗?

到目前为止,我只能正常将数据导出到 Excel,而没有使用 xlsxwriter

转换为表格
writer = pd.ExcelWriter('Results.xlsx', engine='xlsxwriter')

for sheet, frame in  dd.items():
    frame.to_excel(writer, sheet_name = sheet)

writer.save()

要从 Pandas 写入多个工作表,请使用 openpyxl 库。另外,为防止覆盖,每次更新前设置工作簿表。

试试这个代码:

import pandas as pd
import openpyxl

dd = {
'table': pd.DataFrame({'Name':['Banana'], 'color':['Yellow'], 'type':'Fruit'}),
'another_table':pd.DataFrame({'city':['Atlanta'],'state':['Georgia'], 'Country':['United States']}),
'and_another_table':pd.DataFrame({'firstname':['John'], 'middlename':['Patrick'], 'lastnme':['Snow']}),
}

filename = 'Results.xlsx'  # must exist

wb = openpyxl.load_workbook(filename)

writer = pd.ExcelWriter(filename, engine='openpyxl')

for sheet, frame in  dd.items():
    writer.sheets = dict((ws.title, ws) for ws in wb.worksheets) # need this to prevent overwrite
    frame.to_excel(writer, index=False, sheet_name = sheet)

writer.save()

# convert data to tables
wb = openpyxl.load_workbook(filename)
for ws in wb.worksheets:
   mxrow = ws.max_row
   mxcol = ws.max_column
   tab = openpyxl.worksheet.table.Table(displayName=ws.title, ref="A1:" + ws.cell(mxrow,mxcol).coordinate)
   ws.add_table(tab)

wb.save(filename)

输出