Pandas and xlsxwriter: how to create a new sheet without exporting a dataframe?

僤鯓⒐⒋嵵緔 提交于 2021-01-29 09:08:57

问题


If I call the xlsxwriter module directly, it is very easy to create a new sheet in a new file, and write to its cells, e.g.:

import xlsxwriter
workbook = xlsxwriter.Workbook('test 1.xlsx')
wks1=workbook.add_worksheet('Test sheet')
wks1.write(0,0,'some random text')
workbook.close()

Howeer, my question is: how can I create a new sheet using a Pandas.ExcelWriter object? The object can create a new sheet when exporting a dataframe, but what if I don't have any dataframes to export?

E.g. say I have exported 4 dataframes to 4 separate sheets, and now I just want to write some text to a new sheet. The only solution I have found is to create an empty dataframe, export that (which creates the new sheet), then write to the sheet:

import pandas as pd
writer = pd.ExcelWriter('test 2 .xlsx',  engine='xlsxwriter')
df=pd.DataFrame()
df.to_excel(writer, 'new sheet', index=False, startrow=0,startcol=0)
writer.sheets['new sheet'].write(0,0,'some random text')
writer.close()

Is there another way? add_worksheet() seems to be a method of the workbook class only, not of ExcelWriter


回答1:


I don't see anything wrong with the way you are doing it but you could also use the XlsxWriter workbook object from the ExcelWriter as follows:

writer = pd.ExcelWriter('test 2 .xlsx', engine='xlsxwriter')

workbook = writer.book
worksheet = workbook.add_worksheet('new sheet')
worksheet.write(0, 0, 'some random text')


来源:https://stackoverflow.com/questions/55221750/pandas-and-xlsxwriter-how-to-create-a-new-sheet-without-exporting-a-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!