将数据从Excel导入Mysql Python

2024-04-25 08:52:58 发布

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

这段代码适用于字符串,但是数据库中的浮点列不一样,我不明白它是如何工作的,例如在Excel文件中,数据库“254.0835”中的值“215325”以及其他许多值都发生了更改。在

import MySQLdb
import xlrd

list= xlrd.open_workbook("prod.xls")
sheet= list.sheet_by_index(0)

database = MySQLdb.connect (host="localhost" , user="root" , passwd="" ,db="table")
cursor = database.cursor()

query= """INSERT INTO produits (idProduit, idCategorie, LibelleProduit, PrixProduit) VALUES (%s, %s, %s, %s)"""



for r in range(1,sheet.nrows):
    idProduit = sheet.cell(r,0).value
    categorie = 999
    libelle=sheet.cell(r,1).value
    prix=sheet.cell(r,3).value #>>>>> HERE THE PROBLEM the Imported Value <<<<


    values = (idProduit,categorie,libelle,prix)

    cursor.execute(query,values)



cursor.close();
database.commit()

database.close()

print""
print "All done !"

columns= str(sheet.ncols)
rows=str(sheet.nrows)
print "i just import "+columns+" columns and " +rows+ " rows to MySQL DB"

另外,我试图将SQL类型改为Varchar,它也被改变了。在


Tags: columnsimport数据库valuecellquerycursordatabase
1条回答
网友
1楼 · 发布于 2024-04-25 08:52:58

从Excel读取数据时出现此问题。如果您知道它的浮点数据,那么可以在将其插入MySQL之前清除它。在

import re
prix=sheet.cell(r,3).value
prix = str(prix)
prix = re.sub('[^0-9.]+', '', prix )
print float(prix)

只有数字和。将保留所有其他垃圾将被丢弃。在

^{pr2}$

相关问题 更多 >

    热门问题