python - 使用 Python 将 Excel 转为 PostgreSQL

标签 python excel postgresql

我是 Python 的新手,我正在尝试将 excel 直接导出到 postgreSQL 而无需 CSV 文件。

我不知道这是否可能。

我一直遇到错误'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" 

最佳答案

Excel 将日期时间存储为数字。您可以使用 xlrd.xldate.xldate_as_datetime 来转换:

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

关于python - 使用 Python 将 Excel 转为 PostgreSQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39003159/

相关文章:

c# - 用于 C# 的最佳免费 Excel 编写器,用于将数据表输出到 excel

vba - 在使用与上一行的 %difference 时,需要帮助使用 vba 填写 excel 数据透视表留下的空白

php - PostGisl Pdo 准备插入 : functions quoted

postgresql - 如何向 Postgres 中的表添加多列?

postgresql - Heroku 上的 sailsjs 未在 postgresql 中创建模型

python - __getattr__ 和 getattr 是什么关系?

python - 如何在 url 字符串中传递列表中的值

python - 写入文本文件错误 - 必须是 str,而不是列表

python - 为(非系统)Python 安装 rpm 模块

excel - 无法将特定表格从 Web 提取到 Excel VBA (Mac) 中的电子表格中