2013-10-02 46 views
0

我想弄清楚如何使用openpyxl將數據添加到Excel電子表格中,但我還沒有想出將值寫入單個Excel單元格。我想要做的是將循環打印結果保存到Excel的前四行並將其保存爲基本數據。這裏是代碼,謝謝你的提示,並請讓我知道,如果你知道任何優秀的教程openpyxl。Openpyxl&Python

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') 

回答

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 documentation

對照,並更有關openpyxl模塊的信息,您可以打開python控制檯:

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

或特定包內容:

>>> help(openpyxl.workbook) 
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') 

這是我最簡單的例子。

+0

不錯,最小的工作示例。請注意:所有小寫字母的變量名都是常規的。 TitleCase保留用於類定義。請參閱PEP 8:https://www.python.org/dev/peps/pep-0008/#method-names-and-instance-variables – Ogaday