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

来源:互联网 发布:linux mysql开机自启 编辑:程序博客网 时间:2024/06/05 17:05

写一个小功能。

    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格式如下:


数据库中格式如下: