如何使用Xlsxwriter在单元格中将数字(字符串格式,从拼写转换为数字)>>

问题描述 投票:3回答:1

目的:从sqlite数据库中读取证券数据,从Internet提取(抓取)报价,然后使用xlswriter将其插入到Excel工作表中

import os
import sqlite3
import xlsxwriter
from xlsxwriter.utility import xl_rowcol_to_cell
from urllib.request import urlopen
from bs4 import BeautifulSoup

def GetPrice(myurl):
    html = urlopen(myurl)
    soup = BeautifulSoup(html,'lxml')
    return soup.select_one('.h-price').text

db_filename = 'getdata.db'
db_is_new = not os.path.exists(db_filename)
conn = sqlite3.connect(db_filename)
workbook = xlsxwriter.Workbook("isin.xlsx")
worksheet = workbook.add_worksheet()

if db_is_new:
    print('Need db schema')
else:
    cur = conn.cursor()
    curr_row=0

    worksheet.write_string(0,0,'Isin')
    worksheet.write_string(0,1,'Description')
    worksheet.write_string(0,2,'Url')
    worksheet.write_string(0,3,'Price')
    money = workbook.add_format({'num_format': '$#,##0'})

    for row in cur.execute('SELECT * FROM tbIsin'):
        curr_row += 1
        worksheet.write_string(curr_row,0,row[1])
        worksheet.write_string(curr_row,1,row[3])
        worksheet.write_url(curr_row,2,row[2], string='LINK')
        oldval = GetPrice(row[2])
        newval=oldval.replace('.', '')
        worksheet.write(curr_row,3,newval)
        cella = xl_rowcol_to_cell(curr_row, 3)
        formula = '=VAL(%s)' % cella
        worksheet.write(curr_row,4,formula)

conn.close()
workbook.close() 

我的问题:价格为文本格式(例如9963.71为十进制意大利语格式),我无法将其转换为数字格式。我在单元格中输入的公式正确,但给出的结果是#NAME?。

最好的解决办法是直接在单元格中输入数字

今天我用双重替换解决了它:

oldval = GetPrice (row [2])
newval = oldval.replace ('.', '')
curval = float (newval.replace (',', '.'))

目的:从sqlite数据库中读取证券数据,从Internet提取(抓取)报价,然后使用xlswriter import os import sqlite3 import ...将它们插入excel表中]] >> [[

如果输入包含数字,例如'9963.71'这样的字符串,则可以使用strings_to_numbers构造函数选项,可让write()自动将其转换为数字:

workbook = xlsxwriter.Workbook('isin.xlsx', {'strings_to_numbers': True})

基本上在任何类似的地方都可以使用:

>>> float('9963.71') 9963.71

但是,如果数字包含数千个分隔符,或者逗号作为小数点分隔符,那么它将不起作用,您将需要以某种方式对字符串进行预处理。

>>> float('9,963.71') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for float(): 9,963.71

excel sqlite beautifulsoup xlsxwriter
1个回答
0
投票
如果输入包含数字,例如'9963.71'这样的字符串,则可以使用strings_to_numbers构造函数选项,可让write()自动将其转换为数字:
© www.soinside.com 2019 - 2024. All rights reserved.