def multiple_dfs(file_name, sheet, *args):
"""
Put multiple dataframes into one xlsx sheet
"""
row=2
writer = pd.ExcelWriter(file_name, engine='openpyxl')
df = pd.DataFrame({'user': ['Bob', 'Jane', 'Alice'],
'income': [40000, 50000, 42000]})
df2 = pd.DataFrame(['Title'])
df.to_excel(writer, sheet, startrow=row, index=False)
df2.to_excel(writer, sheet, startrow=0, startcol=0, header=None, \
index=False)
如果Title
无效,我希望使用pandas
(或使用openpyxl
来调整此代码中的pandas
。有没有办法准确地做到" pythonically"?
我知道我们可以使用http://openpyxl.readthedocs.io/en/default/styles.html,但我不知道如何在代码中使用它。
根据@AndyHayden的说法,通常下面的代码应该加粗标题,但这似乎不起作用。
import pandas as pd
import io, os, openpyxl
from openpyxl import Workbook
from openpyxl.utils.dataframe import dataframe_to_rows
from openpyxl.styles import (PatternFill, Border, Side, Alignment, Protection, Font)
def multiple_dfs(sheet):
row=2
writer = pd.ExcelWriter("testing.xlsx", engine='openpyxl')
df = pd.DataFrame(['Title'])
df2 = pd.DataFrame({'user': ['Bob', 'Jane', 'Alice'],
'income': [40000, 50000, 42000]})
df.to_excel(writer, sheet, startrow=0, startcol=0, header=None, \
index=False)
df2.to_excel(writer, sheet, startrow=row, index=False)
wb = Workbook()
ws = wb.active
for r in dataframe_to_rows(df, index=False, header=False):
ws.append(r)
title = ws["A1"]; title.font = Font(bold=True)
wb.save("testing.xlsx")
writer.save()
writer.close()
multiple_dfs('aaa')
标题永远不会以粗体显示。我怎么能解决这个问题?
如果问题不清楚,请告诉我。
答案 0 :(得分:1)
openpyxl docs提供了一种巧妙的方法:
from openpyxl import Workbook
from openpyxl.utils.dataframe import dataframe_to_rows
wb = Workbook()
ws = wb.active
for r in dataframe_to_rows(df, index=True, header=True):
ws.append(r)
for cell in ws['A'] + ws[1]:
cell.style = 'Pandas'
wb.save("pandas_openpyxl.xlsx")
注意:如果您事先进行其他插入(如您在上一个问题中的建议,则必须使用不同的行号。