'Is there a faster way to write python outputs back to excel using xlwings in Python?
I have excel file column A, B and C as inputs and then I want to do calculation in python and then return the outputs back o the excel column D and E. Is there faster way than for loop?
import xlwings as xw
import pandas as pd
def square(inputs):
age = inputs['AGE']
weight = inputs['WEIGHT']
outputs = {}
outputs['output_age_square'] = age*age
outputs['output_weight_square'] = weight*weight
return outputs
wb = xw.Book(r'C:\Users\TEST.xlsx') #connect to the daily file xlsm
sheet = wb.sheets['Sheet1']
end_row_num = sheet.range('A' + str(sheet.cells.last_cell.row)).end('up').row
df = sheet.range('A1'+':'+'C'+str(end_row_num)).options(pd.DataFrame, header=1, index=False).value #read all inputs
inputs = df.to_dict('records') #inputs is a list of dicts
outputs = [square(single_input) for single_input in inputs]
for i in range(len(inputs)):
row = 2+i
###########Is there faster way to return back outputs to excel cells#######
sheet.range('D'+str(row)).value = outputs[i]['output_age_square']
sheet.range('E'+str(row)).value = outputs[i]['output_weight_square']
Solution 1:[1]
With xlwings (as with VBA), you have to assign whole arrays to the range, instead of looping through individual cells to make it fast. E.g., you can assign a DataFrame directly to the top left cell like so:
sheet.range('D1').value = df
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Felix Zumstein |