Openpyxl&蟒蛇

时间:2013-10-02 04:22:28

标签: python excel

我正在尝试弄清楚如何使用openpyxl将数据添加到Excel电子表格中,但我还没想到要将值写入单个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')

2 个答案:

答案 0 :(得分:3)

查找指定网址上的价格效果很好,只有您忘记指定要在哪些工作表/单元格中写入数据。这样做:

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 documentation

进行比较

如果您想了解有关openpyxl模块的更多信息,可以打开python控制台:

>>> import openpyxl
>>> help(openpyxl)

或者针对特定的包装内容:

>>> help(openpyxl.workbook)

答案 1 :(得分: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')

这是我最简单的例子。