【问题标题】:Write dataframe to excel with a title将数据框写入带有标题的excel
【发布时间】:2016-04-18 11:35:46
【问题描述】:

我想在 Excel 中打印出一个数据框。我使用 ExcelWriter 如下:

writer = pd.ExcelWriter('test.xlsx')
df = DataFrame(C,ind)    # C is the matrix and ind is the list of corresponding indices 
df.to_excel(writer, startcol = 0, startrow = 5)
writer.save()

这会产生我需要的内容,但另外我想为表格顶部的数据添加带有一些文本(解释)的标题(startcol=0startrow=0)。

如何使用 ExcelWriter 添加字符串标题?

【问题讨论】:

    标签: python excel pandas dataframe xlsx


    【解决方案1】:

    您应该能够使用write_string 方法在单元格中写入文本,在您的代码中添加一些对 XlsxWriter 的引用:

    writer = pd.ExcelWriter('test.xlsx')
    df = DataFrame(C,ind)    # C is the matrix and ind is the list of corresponding indices 
    df.to_excel(writer, startcol = 0, startrow = 5)
    
    worksheet = writer.sheets['Sheet1']
    worksheet.write_string(0, 0, 'Your text here')
    
    writer.save()
    

    【讨论】:

    • 感谢一百万法比奥。我尝试使用 write_string 但由于错误的实现而出现了一些错误。现在它完美地工作了。
    【解决方案2】:

    这样就可以了:

    In[16]: sheet = writer.sheets['Sheet1'] #change this to your own
    In[17]: sheet.write(0,0,"My documentation text")
    In[18]: writer.save()
    

    【讨论】:

    • 感谢 Yannis 的评论。干杯。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-26
    • 2015-06-28
    • 1970-01-01
    • 2018-08-13
    相关资源
    最近更新 更多