Openpyxl&Python
我想弄清楚如何使用openpyxl将数据添加到Excel电子表格中,但我还没有想出将值写入单独的Excel单元格。 我想要做的是将循环打印结果保存到Excel的前四行,并将其保存为基本数据。 这里是代码,谢谢你的提示,请让我知道,如果你知道任何好的教程openpyxl。
from openpyxl import Workbook import urllib import re symbolslist = ["aapl","spy","goog","nflx"] from openpyxl import load_workbook wb2 = load_workbook('fundamental_data.xlsx') i=0 while i<len(symbolslist): 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 i+=1 wb = Workbook() wb.save('fundamental_data.xlsx')
寻找指定url上的价格效果很好,只有您忘记指定要写入数据的表单/单元格。 做这个:
wb = Workbook() # select sheet ws = wb.active i = 0 while i<len(symbolslist): 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 # specify in which cell you want to write the price # in this case: A1 to A4, where the row is specified by the index i # rownumber must start at index 1 ws.cell(row=i+1, column=1).value = price[0] i += 1
最后(注意它会覆盖现有的数据):
wb.save('fundamental_data.xlsx')
您也可以将它与以下的openpyxl文档进行比较
如果你想了解更多关于openpyxl模块的信息,你可以打开python控制台:
>>> import openpyxl >>> help(openpyxl)
或者对于特定的包内容:
>>> help(openpyxl.workbook)
import openpyxl CreateFile = openpyxl.load_workbook(filename= 'excelworkbook.xlsx') Sheet = CreateFile.active Sheet['A1']=('What Ever You Want to Type') CreateFile.save('excelworkbook.xlsx')
这是我最简单的例子。