Excel to PostgreSQL using Python

↘锁芯ラ 提交于 2021-02-07 08:36:54

问题


I'm new to Python and I'm trying to export excel directly into postgreSQL without CSV files.

I don't know if it's possible.

I keep running into the error 'column "daily_date" is of type date but expression is of type numeric'.

import psycopg2
import xlrd

book = xlrd.open_workbook("pytest.xlsx")
sheet = book.sheet_by_name("Source")

database = psycopg2.connect (database = "RunP", user="postgres", password="", host="localhost", port="5432")

cursor = database.cursor()

query = """INSERT INTO orders (Daily_Date, Days, First, Second, Leader) VALUES (%s, %s, %s, %s, %s)"""

for r in range(1, sheet.nrows):
    Daily_Date = sheet.cell(r,0).value
    Days = sheet.cell(r,1).value
    First = sheet.cell(r,2).value
    Second = sheet.cell(r,3).value
    Leader = sheet.cell(r,4).value

    values = (Daily_Date, Days, First, Second, Leader)

    cursor.execute(query, values)

cursor.close()

database.commit()

database.close()

print ""
print ""
columns = str(sheet.ncols)
rows = str(sheet.nrows)
print "I just imported Excel into postgreSQL" 

回答1:


Excel stores datetimes as numbers. You can use xlrd.xldate.xldate_as_datetime to convert:

    Daily_Date = xlrd.xldate.xldate_as_datetime(sheet.cell(r,0).value,book.datemode)


来源:https://stackoverflow.com/questions/39003159/excel-to-postgresql-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!