orak
orak

Reputation: 2419

Write pandas dataframe values to excel to specific cell in a specific sheet.

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

Answers (3)

orak
orak

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

Bharath M Shetty
Bharath M Shetty

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

yoav_aaa
yoav_aaa

Reputation: 387

Use slicing for the relevant rows/columns selection followed by the to_excel function to dump into an Excel sheet.

to_write_df =  ws[(ws['Row']==1) & (ws['Column']==1)]
to_write_df.to_excel('output_file_path')

to_excel

Upvotes: 0

Related Questions