将字符串/文本和 Pandas 数据框写入 excel
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43537598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Write strings/text and pandas dataframe to excel
提问by John
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 = "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.
正如我发现的那样,可以使用 xlsxwriter 来执行此操作,这意味着我基本上必须遍历整个数据帧才能将每个条目写入 Excel 工作簿中的不同单元格。这是相当麻烦的。
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?
有更容易的方法吗?
回答by jezrael
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")
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()
回答by SonOfLight
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.
write 函数是 xlsxwriter 库的一部分。在声明 writer 时,您需要指明希望 Pandas 使用什么引擎。
writer = pd.ExcelWriter("test.xlsx", engine="xlsxwriter")
xlsxwriters functions are then usable through pandas. All other code in the above solution stays the same.
然后可以通过 Pandas 使用 xlsxwriters 函数。上述解决方案中的所有其他代码保持不变。
Ofcourse you require the library to be installed. Hereis a programmatic check.
当然,您需要安装该库。这是一个程序化检查。
Would comment but rep to low
会评论但代表低