我正在尝试使用python将excel工作表中的数据导入到postgresql数据库,当我这样做时,出现以下错误。
我已经将我的excel转换为csv,然后尝试使用'copy'语句将数据导入到postgres数据库。
import psycopg2
conn = psycopg2.connect("host=localhost dbname=djangotest user=postgres password=*******")
cur = conn.cursor()
with open('C:\\Users\\********\\Desktop\\excelsheet.csv', 'r') as f:
next(f) # Skip the header row.
cur.copy_from(f, 'us_arrays', sep=',')
conn.commit()
psycopg2.errors.BadCopyFileFormat: missing data for column "ip_address_or_service_machine"
CONTEXT: COPY us_arrays, line 1: "(CMDB)",.Device Type,.Frame or Data Tier,.Corp Device,.Encrypt Enabled,.Dedicated Device,".IP Addres..."```
根据错误文本(missing data for column
)判断,似乎us_arrays
表中的列数与CSV文件中的列数不匹配。调用columns
来指定应从文件填充的数据库表列时,也可以使用copy_from
关键字属性。进一步了解here。
常见的情况是,数据库表包含3列,例如id
,num
,data
和CSV文件只有两列num
和data
。如果不指定columns
,则copy_from
函数会将CSV文件中的num
导入到id
数据库列中,将data
导入到num
中,并且将没有数据可导入到data
数据库列中。
您的问题被标记为Django,所以我认为您想导入链接到Model
的内容。
我详细说明了如何在this response中加快XL加载速度现在,如果性能不是问题(您的数据集不是太大,并且没有FK),则可以简单地使用Django Import Export
向管理员添加mixins,您不必担心文件转换,并且在加载文件时会给您diff