I have an excel sheet, which already has some values in some cells.
For ex :-
A B C D
1 val1 val2 val3
2 valx valy
I want pandas to write to specific cells without touching any other cells,sheet etc
This is the code i tried.
import pandas as pd
from openpyxl import load_workbook
df2 = pd.DataFrame({'Data': [13, 24, 35, 46]})
book = load_workbook('b.xlsx')
writer = pd.ExcelWriter('b.xlsx', engine='openpyxl')
df2.to_excel(writer, "Sheet1", startcol=7,startrow=6)
writer.save()
However this code deletes the older cell values.
I have reffered to :- How to write to an existing excel file without overwriting data (using pandas)? but this solution does not work.
UPDATE2: appending data to existing Excel sheet, preserving other (old) sheets:
UPDATE: your Excel file doesn't have a header, so you should process it accordingly:
OLD answer:
You can use the following trick:
first read the existing contents of the excel file into a new DF:
now we can write it back and append a new DF2:
Using pandas to read the excel and append the file
I was not able to do what was asked by me in the question by using pandas, but was able to solve it by using
Openpyxl
.I will write few code snippets which would help in achieving what was asked.
So Openpyxl writes to a purticular cell, without touching the other sheets,cells etc. It basically writes to a new file respecting the properties of the original file