python - 从数据框字典创建 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()
解决方案
要从 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)
输出
推荐阅读
- javascript - 关闭服务器后,Node-Cron 如何跟踪时间?
- android - 有没有办法通过一项活动发送意图?
- java - OpenJDK 安全配置中需要进行不明更改以允许 IcedTea-Web 使用库
- javascript - JSON 解码返回 JSON 字符串而不是数组或对象
- php - 会话可以参与包含功能吗?
- javascript - 应用更新后 xxx.chunk.js 返回 422 (Unprocessable Entity)
- javascript - 在 javascript 中解析服务器端文本文件的日期,然后在文件的另一行显示文本
- asp.net-core - .Net Core SignalR 服务器到服务器重新连接
- sql-server-2012 - SQL中的数据转换为十六进制
- c - 为什么 IRQF_SAMPLE_RANDOM 标志已被删除?