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?
You can write any data (lists, strings, numbers etc) to Excel, by first converting it into a Pandas DataFrame and then writing the DataFrame to Excel. To export a Pandas DataFrame as an Excel file (extension: . xlsx, . xls), use the to_excel() method.
How to write to an existing Excel file without overwriting data using Python Pandas? To write to an existing Excel file without overwriting data using Python Pandas, we can use ExcelWriter . to create the ExcelWriter instance with the Excel file path. And then we call save to save the changes.
To write to multiple sheets it is necessary to create an ExcelWriter object with a target file name, and specify a sheet in the file to write to. Multiple sheets may be written to by specifying unique sheet_name . With all data written to the file it is necessary to save the changes.
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:
Sheet2:
Sheet3:
PS tested using the following versions:
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With