我正在使用xlsxwriter引擎将一些数据帧推送到带有pandas.to_excel()的excel表中,但我需要在每个表上方添加一个标题.
我没有看到任何方法使用pandas的ExcelWriter对象来简单地操作每个单元格的内容,当我尝试这样做时,我得到:
Exception: Sheetname ‘sample’, with case ignored, is already in use.
我猜xlsxwriter为自己锁定它.这是一个例子:
xlsx_writer = pd.ExcelWriter(
get_target_filepath(xlsx_name),
engine='xlsxwriter'
)
workbook = xlsx_writer.book
worksheet = workbook.add_worksheet(sheet_name)
worksheet.write(1, 1, 'ABC')
_, sample_table = dataframe_tuples[0]
sample_table.to_excel(xlsx_writer, startrow=3, startcol=2, sheet_name=sheet_name)
我可以保存数据帧并使用openpyxl再次检查它,但我真的不喜欢它们格式化的方式,我接下来要做的,如果我在xlsxwriter中格式化然后用openpyxl重新打开它,它就无法正确地保存格式,openpyxl破坏了它.
我不能将excel本身放到服务器上以使用VBA宏进行样式化.
解决方法:
您可以通过从pandas获取工作表引用并在其上调用标准XlsxWriter方法来执行以下操作.像这样:
import pandas as pd
# Create some Pandas dataframes from some data.
df1 = pd.DataFrame({'Data': [11, 12, 13, 14]})
df2 = pd.DataFrame({'Data': [21, 22, 23, 24]})
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_example.xlsx', engine='xlsxwriter')
# Position the dataframes in the worksheet.
df1.to_excel(writer, sheet_name='Sheet1', index=False, startrow=2)
df2.to_excel(writer, sheet_name='Sheet1', index=False, startrow=9)
# Get the worksheet object.
worksheet = writer.sheets['Sheet1']
# Write some titles above the dataframes.
worksheet.write(1, 0, 'Some random title 1')
worksheet.write(8, 0, 'Some random title 2')
# Close the Pandas Excel writer and output the Excel file.
writer.save()
另见Working with Python Pandas and XlsxWriter.
输出: