[英]Python Writing to Excel Iteratively
I'm trying to make my code write to cells A1
, A2
, A3
and A4
in Excel. 我正在尝试将代码写入Excel中的单元格A1
, A2
, A3
和A4
。 However, when I use it, I get this error message 但是,当我使用它时,出现此错误信息
Invalid Cell coordinates (A) 无效的像元坐标(A)
'A' stays constant but 'i' changes with each repetition. “ A”保持不变,但“ i”随每次重复而变化。 How would I fix the problem on line 27? 我该如何解决第27行的问题? I want to make Python accept "A" as a column reference. 我想让Python接受“ A”作为列引用。
This was line 27: 这是第27行:
ws.cell('A',i).value = "The price of", symbolslist[i], " is ", price"
and my entire Python script: 和我的整个Python脚本:
from openpyxl import Workbook
import urllib
import re
from openpyxl.cell import get_column_letter
wb = Workbook()
dest_filename = r'empty_book.xlsx'
ws = wb.create_sheet()
ws.title = 'Stocks'
symbolslist = ["aapl","spy","goog","nflx"]
i=0
while i<len(symbolslist):
#counts each object as 1 in the list
url = "http://finance.yahoo.com/q?s="+symbolslist[i]+"&q1=1"
htmlfile = urllib.urlopen(url)
htmltext = htmlfile.read()
regex = '<span id="yfs_l84_'+symbolslist[i]+'">(.+?)</span>'
pattern = re.compile(regex)
price = re.findall(pattern,htmltext)
print "The price of", symbolslist[i], " is ", price
ws.cell(1,i+1).value = "The price of" + symbolslist[i] + " is " + price
i+=1
wb.save(filename = dest_filename)
I am also using this as a reference , from openpyxl. 我还将openpyxl用作参考 。
EDIT 编辑
Your i=0 on the first pass but there is no zero column. 您的i = 0在第一遍,但没有零列。 Also, I think the cell is looking for row index which is a number not a character 'A'. 另外,我认为单元格正在寻找行索引,该行索引不是数字“ A”。
ws.cell(1,i+1).value = "The price of" + symbolslist[i] + " is " + price
It is the use of ws.cell().value that is not correct. ws.cell()。value的使用是不正确的。 I had the error saying 'int' object has no attribute 'replace', but after I changed the line to the following, the error dispappeared: ws.cell(row=1,column=i+1).value = "The price of" + str(symbolslist[i]) + " is " + str(price) 我遇到错误,说“ int”对象没有属性“ replace”,但是在将行更改为以下内容后,错误消失了:ws.cell(row = 1,column = i + 1).value =“价格“ + str(symbolslist [i])+”的值为“ + str(price)
By the way, I am using Python 2.7 and the latest version of openpyxl 顺便说一句,我正在使用Python 2.7和最新版本的openpyxl
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.