如何使用OpenPyXL将值写入各个单元格?

2024-05-13 21:26:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试如何使用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')

Tags: fromimportreurldataloadurllibxlsx
2条回答

在指定的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

最后(小心它只会覆盖现有数据):

^{pr2}$

您还可以将其与下面的openpyxl documentation进行比较

如果您想要更多关于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')

这是我最简单的例子。在

相关问题 更多 >