python——快速读取excel文件并插入数据库

Posted Lenskit

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python——快速读取excel文件并插入数据库相关的知识,希望对你有一定的参考价值。

写一个小功能。

    import cStringIO
    import pandas as pd
   from sqlalchemy import create_engine
    path = "D://Users//xxxx/Desktop//"
    file = pd.read_excel(path+'test.xlsx')
    file['ismodified'] = 0
    engine = create_engine('postgresql+psycopg2://xxx:xxx@ip:port/xxxx')
    output = cStringIO.StringIO()
    # ignore the index
    file.to_csv(output, sep='\\t', index=False, header=False)
    output.getvalue()
    # jump to start of stream
    output.seek(0)
    connection = engine.raw_connection()
    cursor = connection.cursor()
    # null value become ''
    cursor.copy_from(output, 'table_name', null='')
    connection.commit()
    cursor.close()

此脚本用于读取excel文件并且加上index以及用于标识是否修改的列(默认为0,即未做修改)。随后插入postgre数据库。

excel格式如下:


数据库中格式如下:


以上是关于python——快速读取excel文件并插入数据库的主要内容,如果未能解决你的问题,请参考以下文章

python读取excel数据插入sqlite中

python读取excel文件

python读取excel文件

pandas读取excel文件指定列

csharp 读取Excel文件并插入带有序列化的List

python 读取excel数据插入到另外一个excel