Write strings/text and pandas dataframe to excel

前端 未结 2 1244
猫巷女王i
猫巷女王i 2020-12-31 19:10

I\'d like to save some text and a dataframe to an excel file like that:

Thus, I\'ve got the following variables:

text1 = \"some text here\"
text2 =          


        
相关标签:
2条回答
  • 2020-12-31 19:22

    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)

    0 讨论(0)
  • 2020-12-31 19:26

    Above solution is correct... However

    The write function is part of the xlsxwriter library. When declaring the writer you need to indicate what engine you want pandas to use.

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

    xlsxwriters functions are then usable through pandas. All other code in the above solution stays the same.

    Ofcourse you require the library to be installed. Here is a programmatic check.

    Would comment but rep to low

    0 讨论(0)
提交回复
热议问题