Reputation: 2419
I have the following pandas dataframe:
Name Sheet Row Column Value
0 V1 Sheet1 1 1 89
1 V2 Sheet1 2 1 104
2 V3 Sheet2 1 2 6
3 V4 Sheet3 3 3 -5
I want to save the Value in the sheet, row and column specified in the dataframe. They are not in order and I don't know how many sheets there would be. I could just go through each row and write using xlwt package
ws = wb.add_sheet('Sheet1')
ws.write(1, 1, 89)
I was wondering if I could achieve this using pandas API or any better approach? Couldn't see pandas providing access to specific rows and columns of excel for writing.
Upvotes: 1
Views: 12046
Reputation: 2419
I couldn't find an API which would directly write, however, I found xlwings
module to be quite helpful and intutive. Used the following code:
import xlwings as xw
wb = xw.Book('out.xls')
for index, row in result.iterrows():
wb.sheets[row['Sheet_Name']].range((row['Row'], row['Column'])).value = row['transformed_value']
wb.save()
Upvotes: 1
Reputation: 30605
One of the way is with the help of a for loop and iterrows()
i.e
writer = pd.ExcelWriter('out.xlsx')
for _,i in df.iterrows():
t_df = pd.DataFrame([i['Value']])
t_df.to_excel(writer, startcol=i['Column'],startrow=i['Row'], sheet_name=i['Sheet'], header=None, index=False)
writer.save()
Hope it helps.
Upvotes: 1