Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

python - writing pandas data frame to existing workbook

I want to save a data frame to the second sheet of a file but I can't do that and I don't know why.

yfile = openpyxl.load_workbook(new_file, data_only=True) 
ws = yfile.worksheets[0] 
sheet2 = yfile.create_sheet() 
ws2 = yfile.get_sheet_by_name("Sheet").title = "Analysis" 
writer = pd.ExcelWriter(yfile, engine='xlsxwriter') 
df3.to_excel(writer, sheet_name='Analysis') 
writer.save()
yfile.save(new_file)                                          

I have created the sheet 'Analysis' but when I save in it I received the following response: "AttributeError: 'Workbook' object has no attribute 'write'"

What I have to modify?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the append_df_to_excel() helper function, which is defined in this answer:

Demo:

In [127]: df = pd.DataFrame(np.random.rand(5, 3), columns=list('abc'))

In [128]: df
Out[128]:
          a         b         c
0  0.597353  0.770586  0.671231
1  0.628605  0.161283  0.397493
2  0.476206  0.701582  0.476809
3  0.045590  0.302834  0.857033
4  0.414820  0.478016  0.563258

In [129]: df.to_excel(filename)

In [130]: append_df_to_excel(filename, df, sheet_name="Sheet2", startrow=1, startcol=1)

In [131]: append_df_to_excel(filename, df, sheet_name="Sheet3", index=False)

In [132]: append_df_to_excel(filename, df, sheet_name="Sheet1", startcol=2, index=False)

Result:

Sheet1:

enter image description here

Sheet2:

enter image description here

Sheet3:

enter image description here

PS tested using the following versions:

  • python: 3.6.4
  • pandas: 0.22.0
  • openpyxl: 2.4.10

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...