How to write a new cell in python using openpyxl

I wrote code that opens an excel file and iterates through each line and passes the value to another function.

import openpyxl wb = load_workbook(filename='C:\Users\xxxxx') for ws in wb.worksheets: for row in ws.rows: print row x1=ucr(row[0].value) row[1].value=x1 # i am having error at this point 

When you try to run the file, the following error appears.

 TypeError: IndexError: tuple index out of range 

Is it possible to write the return value x1 in the column row[1] . Is it possible to write excel (ie Using row[1] ) instead of accessing individual cells, for example ws.['c1']=x1

+6
source share
1 answer

Try the following:

 import openpyxl wb = load_workbook(filename='xxxx.xlsx') ws = wb.worksheets[0] ws['A1'] = 1 ws.cell(row=2, column=2).value = 2 ws.cell(coordinate="C3").value = 3 # 'coordinate=' is optional here 

This sets cells A1, B2, and C3 to 1, 2, and 3, respectively (three different ways to set cell values ​​on a sheet).

The second method (specify the row and column) is most useful for your situation:

 import openpyxl wb = load_workbook(filename='xxxxx.xlsx') for ws in wb.worksheets: for index, row in enumerate(ws.rows, start=1): print row x1 = ucr(row[0].value) ws.cell(row=index, column=2).value = x1 
+18
source

All Articles