当前位置:   article > 正文

python把Excel写入pg_python导入表格到pg库

python导入表格到pg库

1.Excel列和数据库表字段相同

def radical_to_db():

    data1 = pd.read_excel("C:/work/20220714***/**/词**导入pg.xlsx")

    # drop first line
    data1 = data1.drop([0])

    # set upd_date
    # get current time
    now_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    data1["upd_date"] = now_time

    # trim
    data1["chinese_attr"] = data1["chinese_attr"].str.strip()
    data1["radical_full"] = data1["radical_full"].str.strip()
    data1["radical_abbr"] = data1["radical_abbr"].str.strip()
    data1["vers_no"] = data1["vers_no"].str.strip()
    data1["oper_indv"] = data1["oper_indv"].str.strip()

    # set operator
    data1["oper_indv"] = "admin"

    # dataframe类型转换为IO缓冲区中的str类型
    output = StringIO()
    # sep : set split column
    data1.to_csv(output, sep='\t', index=False, header=False)
    output1 = output.getvalue()

    conn = psycopg2.connect(host="10.0.0.10", user = "postgres", password = "123456", database ="postgres" )
    
    cur = conn.cursor()
    cur.copy_from(StringIO(output1), "tableName")
    conn.commit()
    cur.close()
    conn.close()
    print('done')

问题:

1.删除第一行标题

# drop first line
df= df.drop([0])

2.KeyError: 'chinese_attr'

检查原Excel的表头是否包含,报错的列名

可以用 print(df.head()) 查看原表头

3.psycopg2.DataError: extra data after last expected column

原因:Excel文本中有空格,导致 to_csv 分列时候,分出了多余的列。

# sep 修改分隔符为其他生僻的字段中不可能出现的分隔符
data1.to_csv(output, sep='\t', index=False, header=False)

解决办法:

把文本列trim一下

# trim
data1["chinese_attr"] = data1["chinese_attr"].str.strip()
data1["radical_full"] = data1["radical_full"].str.strip()
data1["radical_abbr"] = data1["radical_abbr"].str.strip()
data1["vers_no"] = data1["vers_no"].str.strip()
data1["oper_indv"] = data1["oper_indv"].str.strip()

4.指定Excel列的数据类型

eg:指定第4列 第3列..为 字符串类型

data1 = pd.read_excel("C:/work/20230224/resume/report_data_basic.xlsx",dtype={4:"str", 3:"str", 5:"str", 7:"str", 9:"str"})

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小舞很执着/article/detail/908426
推荐阅读
相关标签
  

闽ICP备14008679号