我想插入日期时间值mysql。所以我制作了mysql时间戳并修复了excel日期YYYYMMDDHHmmss类型。当我尝试导入excel文件python到mysql成功获取excel col中的完整数据。但是包含空列有内部错误1292,“第1行的列'AriT'的日期时间值:''不正确”。我想要空列跳过或在mysql中保存null。怎么编码?
import xlrd
import pymysql
#open the workbook and define rhe worksheet
book = xlrd.open_workbook("d:/final/final.xls")
sheet = book.sheet_by_index(0)
#sheet = book.sheet_by_index(0)
#establish a mysql connection
database = pymysql.connect(host="localhost", user='root', password='1234',db='test')
#get the cursor, which is used to traverse the database, line by line
cursor = database.cursor()
#create the insert into sql quety
query = """INSERT INTO test2 (AriT) VALUES (%s)"""
#create a for loop to iterate through each row in the xls file, starting at row 2 to skip the headers
for r in range(1, sheet.nrows):
AriT = sheet.cell(r,9).value
#assign calues from each row
values = (AriT )
#execute sql query
cursor.execute(query, values)
#close the cursor
cursor.close()
#commit the transaction
database.commit()
#close the databases connection
database.close()
发布于 2018-07-30 09:39:58
如果要将值检索为在Excel中指定的格式,则应使用Text
。
例如,公式ActiveCell
是=Now()
,我们已经设置了格式YYYYMMDDHHmmss
让我们在立即窗口中尝试(在VBA编辑器中按Ctrl + G)
? ActiveCell.Value
30/7/2018 09:20:28
? ActiveCell.Value2
43311.3892158565
? ActiveCell.Text
20180730092028
但是,如果你的单元格值超过单元格宽度,.Text
则将变为###
。
在你的情况下,你可以使用Format(ActiveCell.Value2, "YYYYMMDDHHmmss")
检索值。
这样你就不必担心单元格的格式化了。
? Format(ActiveCell.Value2, "YYYYMMDDHHmmss")
20180730092738
https://stackoverflow.com/questions/-100001706
复制相似问题