7

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?

Michele Della Mea
  • 966
  • 2
  • 16
  • 35
  • 1
    One issue is that you are creating `yfile` as an `openpyxl` objectand then passing it to `pd.ExcelWriter` but telling it that it should use the `xlsxwriter` engine. These two objects are incompatible so that isn't going to work. However, I don't know if it will work even with an openpyxl object and engine created in this way. – jmcnamara Apr 06 '16 at 10:36

2 Answers2

7

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
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419
3

You can use such way as below. It writes dataframe to an excel-file row by row.

from openpyxl.utils.dataframe import dataframe_to_rows
filename = r'some_file.xlsx'
df = some_dataframe

wb = load_workbook(filename)
if 'sh2' in wb.sheetnames:#to check whether sheet you need already exists
    ws = wb['sh2']
else:
    ws = wb.active
for r in dataframe_to_rows(df, index=False, header=True):
    ws.append(r)
wb.save(filename)
Sergey Solod
  • 695
  • 7
  • 15
  • I've searched all internet and only this solution worked! Other ones worked in Jupyter but not in Shell for me (corrupting excel file) and this one does. Thanks! – Marta Jan 29 '21 at 14:34