python-excel表格自动导入数据到数据库和数据库中指定的数据导出到excel

一   excel表格自动将数据导入数据库,限制文件后缀名为.xlsx

文件1: model.py  我这里使用的postgresql,根据自己使用的数据库修改
import psycopg2
#封装的插入数据库方法
def insert(sql):
    try:
        conn = psycopg2.connect(database='test', user='postgres', password='root', host='localhost')
        cur = conn.cursor()
        #cur.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, 'Paul', 32, 'California', 20000.00 )")
        cur.execute(sql)
        conn.commit()
        return 'ok'
    except:
        print('插入失败')
        return 'error'
    finally:
        conn.close()

文件2: excelTodatabase.py
注意:每个sheet生成一张表,表名字为sheet的名字,自动将int类型和日期类型转成字符类型,数据库连接方式改成自己对应的数据库,我这里是postgresql
import xlrd
from datetime import datetime
from xlrd import xldate_as_tuple
#根据有多少个sheets去创建多少个表,path为excel表格的路径
def createtable(path):
    # 读取excel
    data = xlrd.open_workbook(path)
    # 根据sheet索引获取sheet的内容
    print("excel全部的sheet为:", data.sheet_names())
    sheet_names = data.sheet_names()
    table_one = data.sheet_by_index(0)
    print("一个sheet的全部列名为", table_one.row_values(0))
    conn = psycopg2.connect(database='test', user='postgres', password='root', host='localhost')
    cur = conn.cursor()
    for i in range(0, len(sheet_names)):
        #当前sheet的名字
        table_name = sheet_names[i]
        # 当前的sheet
        now_table = data.sheet_by_index(i)
        # 获得当前sheet的列数就是 属性数
        cols_num = now_table.ncols
        # 获得当前表格的行数,就是有多少的数据量
        rows_numn = now_table.nrows
        # 获得当前的属性的数组,其实就是第一例的值
        attrs = now_table.row_values(0)
        #判断表格是否存在
        cur.execute("SELECT to_regclass('%s') is not null" % table_name)
        flag = cur.fetchone()[0]
        print('flag',flag)
        if flag :
            print('存在了,直接将表的内容插入')
            # 将当前的sheet插入到数据库
            for k in range(1, rows_numn):
                row_vlaue = now_table.row_values(k)
                print(row_vlaue)
                print(','.join(attrs))
                # 处理要插入的数据,把非字符串的数据转换成字符串类型,同事将字符串变成 sql语句需要的类型
                for a in range(0, len(row_vlaue)):
                    ctype = now_table.cell(k, a).ctype
                    print('ctype', ctype)
                    #ctype: 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
                    if ctype ==2 and  row_vlaue[a] % 1 ==0 :
                        tmp = int(row_vlaue[a])
                        row_vlaue[a] = str(tmp)
                    if ctype == 3 :
                        d = datetime(*xldate_as_tuple(row_vlaue[a],0))
                        row_vlaue[a] = d.strftime('%Y-%m-%d')
                    c = row_vlaue[a]
                    row_vlaue[a] = "'" + c + "'"
                print(','.join(row_vlaue))
                sql = "INSERT INTO %s(%s) VALUES(%s)" % (table_name, ','.join(attrs), ','.join(row_vlaue))
                print(sql)
                cur.execute(sql)
                conn.commit()
        else:
            cur.execute("CREATE TABLE " + table_name + "();")
            conn.commit()
            # 为sheet进行建表,
            cur.execute("ALTER TABLE %s ADD COLUMN  id SERIAL primary key  ;" % table_name)
            conn.commit()
            #        cur.execute("CREATE SEQUENCE users_id_seq  START WITH 1  INCREMENT BY 1  NO MINVALUE  NO MAXVALUE  CACHE 1;" )
            #       conn.commit()
            cur.execute("alter table  %s alter column id set default nextval('users_id_seq'); " % table_name)
            conn.commit()
            for j in range(0, cols_num):
                cur.execute("ALTER TABLE %s ADD COLUMN %s VARCHAR(200);" % (table_name, attrs[j]))
                conn.commit()
            # 将当前的sheet插入到数据库
            for k in range(1, rows_numn):
                row_vlaue = now_table.row_values(k)
                print(row_vlaue)
                print(','.join(attrs))
                # 处理要插入的数据,把非字符串的数据转换成字符串类型,同事将字符串变成 sql语句需要的类型
                for a in range(0, len(row_vlaue)):
                    ctype = now_table.cell(k, a).ctype
                    print('ctype', ctype)
                    # ctype: 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
                    if ctype == 2 and row_vlaue[a] % 1 == 0:
                        tmp = int(row_vlaue[a])
                        row_vlaue[a] = str(tmp)
                    if ctype == 3:
                        d = datetime(*xldate_as_tuple(row_vlaue[a], 0))
                        row_vlaue[a] = d.strftime('%Y-%m-%d')
                    c = row_vlaue[a]
                    row_vlaue[a] = "'" + c + "'"
                print(','.join(row_vlaue))
                sql = "INSERT INTO %s(%s) VALUES(%s)" % (table_name, ','.join(attrs), ','.join(row_vlaue))
                print(sql)
                cur.execute(sql)
                conn.commit()
    conn.close()

二   数据库信息导出到excel表格,生成 .xls格式的表格(.xlsx格式打不开)

文件1 dbToExcel.py  

注意:修改对应数据库的连接方式,我这里是postgresql,返回结果"ok"代表成功

import xlwt
import psycopg2
import os
import datetime
def tableExportToXlsx(sql):#sql 为数据库查询语句,将会把查询的数据导出
    table_name = "acts"
    conn = psycopg2.connect(database='test',user='postgres',password='root',host='localhost')
    cur = conn.cursor()
    cur.execute(sql)
    #重置游标位置
    cur.scroll(0,mode='absolute')
    #搜取所有的结果
    results = cur.fetchall()
    #获取属性名
    attrs = cur.description

    workbook = xlwt.Workbook()
    sheet = workbook.add_sheet(table_name,cell_overwrite_ok=True)
    #写入表格的属性值
    for i in range(0,len(attrs)):
        sheet.write(0,i,attrs[i][0])
        print('表格属性:',attrs[i][0])

    #将数据库的数据导入表格
    row = 1
    col = 0
    for row in range(1,len(results)+1):
        print('写',row,'行数据')
        for col in range(0,len(attrs)):
            sheet.write(row,col,results[row-1][col])
            print(results[row-1][col])
    nowpath = os.path.dirname(__file__)
    print("现在的目录是" + nowpath)
    act_path = os.path.dirname(nowpath)
    app_path = os.path.dirname(act_path)
    file_path = app_path + '\\xlsx_tmp'
    export_time = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
    file_name = 'act-{0}.xls'.format(export_time)
    print('文件路径为' +os.path.join(file_path,file_name))
    workbook.save(os.path.join(file_path,file_name))

    if os.path.isfile(os.path.join(file_path,file_name)):
        print('数据库中成功导出数据')
        return {'path':file_path,'name':file_name}
    else:
        print('数据库导出错误')
        return  'error'




猜你喜欢

转载自blog.csdn.net/huangmengfeng/article/details/81005505