问题
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