通过引入pandas实现写入excel的时候,发现文件没有生成,然后在网上找了一个例子,直接将代码copy过来运行,还是没有预期中的excel文件生成,也没有任何报错,代码如下:
import pandas as pd
# create some Pandas DateFrame from some data
df1 = pd.DataFrame({'Sheet1': [1, 2, 3, 4, 5, 6, 7]})
df2 = pd.DataFrame({'Sheet2': [8, 9, 10, 11, 12, 13]})
df3 = pd.DataFrame({'Sheet3': [14, 15, 16, 17, 18]})
# create a Pandas Excel writer using xlswriter
writer = pd.ExcelWriter("test1.xlsx")
df1.to_excel(writer, sheet_name='Sheet1', startcol=0, index=False)
df2.to_excel(writer, sheet_name='Sheet2', startcol=1, index=False)
df3.to_excel(writer, sheet_name='Sheet3', index=False)
然后网上百度各种例子都大同小异,没发现哪里有问题。后来才发现原来是缺少了
writer.save(),即代码应该是这样才对:
import pandas as pd
# create some Pandas DateFrame from some data
df1 = pd.DataFrame({'St1': [1, 2, 3, 4, 5, 6, 7]})
df2 = pd.DataFrame({'Sheet2': [8, 9, 10, 11, 12, 13]})
df3 = pd.DataFrame({'Sheet3': [14, 15, 16, 17, 18]})
# create a Pandas Excel writer using xlswriter
writer = pd.ExcelWriter("test1.xlsx")
df1.to_excel(writer, sheet_name='St1', startcol=0, index=False)
df2.to_excel(writer, sheet_name='Sheet2', startcol=1, index=False)
df3.to_excel(writer, sheet_name='Sheet3', index=False)
writer.save()
在此记录下这次遇到的坑,一方面给遇到同样情况的童鞋以提示,一方面希望网上写这些帖子的作者能够负责任一点,尽量写完整,避免误导我们这些小白,谢谢!
网友评论