python-excel表格自動導入數據到數據庫和數據庫中指定的數據導出到excel

一   excel表格自動將數據導入數據庫,限制文件後綴名爲.xlsx

文件1: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'




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章