0

我试图弄清楚如何将数据添加到 Excel 电子表格中,openpyxl但我还没有想出将值写入单个 Excel 单元格。

我想要做的是将循环中的打印结果保存到 Excel 的第一四行并将其保存为fundamental_data. 这是代码。如果你知道任何好的教程,请告诉我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')
4

2 回答 2

3

在指定的 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)
于 2013-10-07T10:28:47.457 回答
1
import openpyxl
CreateFile = openpyxl.load_workbook(filename= 'excelworkbook.xlsx')
Sheet = CreateFile.active
Sheet['A1']=('What Ever You Want to Type')
CreateFile.save('excelworkbook.xlsx')

这是我最简单的例子。

于 2015-11-26T04:11:28.670 回答