Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write strings/text and pandas dataframe to excel

I'd like to save some text and a dataframe to an excel file like that: enter image description here

Thus, I've got the following variables:

text1 = "some text here"
text2 = "other text here"
df = pd.DataFrame({"a": [1,2,3,4,5], "b": [6,7,8,9,10], "c": [11,12,13,14,15]})

As I've figured out there is the possibility to use the xlsxwriter to do this which means that I basically have to iterate over the whole dataframe to write each entry to a different cell in the excel workbook. This is quite cumbersome.

So, I thought there must an easier way to do this; something like this:

writer = pd.ExcelWriter("test.xlsx", engine="xlsxwriter")
writer.write(text1, startrow=0, startcol=0)
writer.write(text1, startrow=1, startcol=0)
df.to_excel(writer, startrow=4, startcol=0)

Is there an easier way?

like image 689
John Avatar asked Apr 21 '17 08:04

John


People also ask

How do I write pandas Dataframes to an existing Excel spreadsheet?

You can write any data (lists, strings, numbers etc) to Excel, by first converting it into a Pandas DataFrame and then writing the DataFrame to Excel. To export a Pandas DataFrame as an Excel file (extension: . xlsx, . xls), use the to_excel() method.

How do I write data in a specific column in excel using Python?

You could change ws[cell] = row[0] to ws[cell] = row['Col_C'] and it would work. Hopefully this answers your question.


1 Answers

You need write or write_string:

text1 = "some text here"
text2 = "other text here"
df = pd.DataFrame({"a": [1,2,3,4,5], "b": [6,7,8,9,10], "c": [11,12,13,14,15]})

writer = pd.ExcelWriter("test.xlsx", engine="xlsxwriter")
df.to_excel(writer, startrow=4, startcol=0)

worksheet = writer.sheets['Sheet1']
worksheet.write(0, 0, text1)
worksheet.write(1, 0, text2)
#another solution
#worksheet.write_string(0, 0, text1)
#worksheet.write_string(1, 0, text2)

writer.save()

Note: write and write_string are actually xlsxwriter package functions. To use them, the package must be installed and pd.ExcelWriter must be initialized with the xlsxwriter engine (in pandas 1.0.5 it defaults to the io.excel.<extension>.writer engine)

like image 84
jezrael Avatar answered Oct 11 '22 23:10

jezrael