how to write to a new cell in python using openpyxl

我的未来我决定 提交于 2019-11-27 02:50:44

问题


I wrote code which opens an excel file and iterates through each row 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

I am getting the following error when I tried to run the file.

TypeError: IndexError: tuple index out of range

Can I write the returned value x1 to the row[1] column. Is it possible to write to excel (i.e using row[1]) instead of accessing single cells like ws.['c1']=x1


回答1:


Try this:

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 will set Cells A1, B2 and C3 to 1, 2 and 3 respectively (three different ways of setting cell values in a worksheet).

The second method (specifying 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


来源:https://stackoverflow.com/questions/31395058/how-to-write-to-a-new-cell-in-python-using-openpyxl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!