繁体   English   中英

将数据从Excel导入到Mysql Python

[英]Import Data from Excel to Mysql Python

这段代码对String效果很好,但是数据库中的float列不一样,我不明白它的工作方式,例如在Excel文件中,数据库“ 254.0835”中的值“ 215,325”,并且还有许多其他值已更改。

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,它也进行了更改。

从Excel读取数据时出现问题。 如果您知道其浮动数据,则可以在将其插入MySQL之前对其进行清理。

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

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

import MySQLdb
import re
database = MySQLdb.connect (host="localhost" , user="test" , passwd="" ,db="test")
cursor = database.cursor()
query= """INSERT INTO test (id, num) VALUES (%s, %s)"""

prix = "215,325"
prix = str(prix)
prix = re.sub('[^0-9.]+', '', prix )
prix = float(prix)
values = (23,prix)

cursor.execute(query,values)
cursor.close();
database.commit()
database.close()
print "Done"

暂无
暂无

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

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