首页 > 解决方案 > 从数据框字典创建 Excel 表

问题描述

我有数据框字典。

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 表对象。每个表格都需要位于单独的选项卡/工作表上,并且表格名称应与数据框名称匹配。

这可能与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()

标签: pythondictionaryopenpyxlexport-to-excelxlsxwriter

解决方案


要从 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)

输出

Excel表格


推荐阅读