如何使用openpyxl写入python中的新单元格 [英] how to write to a new cell in python using openpyxl
问题描述
我编写的代码打开一个excel文件,并遍历每一行,并将值传递给另一个函数。
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
我可以写返回的值 x1
到行[1]
列。可以写入excel(即使用 row [1]
)而不是访问单个单元格,如 ws。['c1'] = x1
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
推荐答案
尝试这样:
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
这将分别将单元格A1,B2和C3分别设置为1,2和3(设置单元格值的三种不同方式一个工作表)。
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
这篇关于如何使用openpyxl写入python中的新单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!