简体   繁体   English

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

[英]How write values to individual cells with OpenPyXL?

I'm trying to figure out how to add data to an Excel spreadsheet with openpyxl but I haven't figured out to write values to individual Excel cells. 我试图弄清楚如何使用openpyxl将数据添加到Excel电子表格,但是我还没有想出如何将值写入单个Excel单元格。

What I'm wanting to do is to save the print results from the loop into the 1st four rows of Excel and save it as fundamental_data . 我想要做的是将循环中的打印结果保存到Excel的第一四行中,并将其另存为fundamental_data Here is the code. 这是代码。 Please let me know if you know of any good tutorials for openpyxl . 如果您知道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')

Looking for the prices on the specified URL works well, only you forget to specify in which sheets/cells you want to write the data. 在指定的URL上查找价格会很好,只有您忘记指定要在哪个工作表/单元格中写入数据。 Do this: 做这个:

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

And in the end (watch out it will just overwrite existing data): 最后(注意,它只会覆盖现有数据):

wb.save('fundamental_data.xlsx')

Also you can compare it with the following openpyxl documentation 您也可以将其与以下openpyxl文档进行比较

And if you want more information on the openpyxl module, you can open the python console: 如果您想了解更多有关openpyxl模块的信息,可以打开python控制台:

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

Or for a specific package content: 或针对特定的包装内容:

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

This is my most simple example. 这是我最简单的例子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM