如何使用openpyxl在python中写入新单元格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31395058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to write to a new cell in python using openpyxl
提问by Priyaranjan
I wrote code which opens an excel file and iterates through each row and passes the value to another function.
我编写了打开 excel 文件并遍历每一行并将值传递给另一个函数的代码。
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
我可以写返回值x1
的row[1]
列。是否可以写入excel(即使用row[1]
)而不是访问单个单元格,例如ws.['c1']=x1
回答by Jake Griffin
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).
这将分别将单元格 A1、B2 和 C3 设置为 1、2 和 3(在工作表中设置单元格值的三种不同方式)。
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