數據庫中數據轉爲Excel數據(Python實現)

以前寫的一個項目,數據源文件excel,但是後來搞着搞着吧Excel文件給刪了,現在有需要這個Excel文件,我發現數據庫中還有原來的數據存在,於是吧數據庫中的數據轉爲Excel文件就行啦!

數據庫中數據如下:

導出的Excel如下:

具體實現的代碼如下:

先寫一個數據庫讀取和寫的接口,Excel表讀取和寫的接口,程序如下:

import abc
class RW(object):
    @abc.abstractmethod
    def read(self,path,name):
        pass

    @abc.abstractmethod
    def write(self, path, name,value):
        pass

import xlrd
from xlrd import xldate_as_tuple
import datetime
import openpyxl

class ExcelData(RW):
    # 定義一個讀取excel表的方法
    def read(self, data_path, sheetname):
        data = xlrd.open_workbook(data_path)
        table = data.sheet_by_name(sheetname)
        keys = table.row_values(0)
        rowNum = table.nrows
        colNum = table.ncols
        datas = []
        for i in range(1, rowNum):
            sheet_data = {}
            for j in range(colNum):
                c_type = table.cell(i, j).ctype
                c_cell = table.cell_value(i, j)
                if c_type == 2 and c_cell % 1 == 0:  # 如果是整形
                    c_cell = int(c_cell)
                elif c_type == 3:
                    date = datetime.datetime(*xldate_as_tuple(c_cell, 0))
                    c_cell = date.strftime('%Y/%d/%m %H:%M:%S')
                elif c_type == 4:
                    c_cell = True if c_cell == 1 else False
                sheet_data[keys[j]] = c_cell
            datas.append(sheet_data)
        return datas

    # 定義一個寫excel表的方法
    def write(self,data_path, sheetname,value):
        index = len(value)
        workbook = openpyxl.Workbook()
        sheet = workbook.active
        sheet.title = sheetname
        for i in range(0, index):
            for j in range(0, len(value[i])):
                sheet.cell(row=i + 1, column=j + 1, value=str(value[i][j]))
        workbook.save(data_path)
        print("xlsx格式表格寫入數據成功!")


import pymysql

class DB(RW):
    def __init__(self):
        self.connect = pymysql.Connect(
            host='localhost',
            port=3306,
            user='root',
            passwd='',
            db='TT',
            charset='utf8'
        )
        self.cursor = self.connect.cursor()

    def read(self,tablespace,table):
        try:
            sql = "use "+tablespace
            self.cursor.execute(sql)
            self.connect.commit()
        except Exception as e:
            print(str(e))
            print("不存在{}表空間!".format(tablespace))
        try:
            sql = "select * from "+table
            self.cursor.execute(sql)
            self.connect.commit()
            description = self.cursor.description
            title = []

            for data in description:
                title.append(data[0])
            datas=[]
            for row in self.cursor.fetchall():
                sheelData = {}
                for col in range(len(row)):
                    sheelData[title[col]]=row[col]
                datas.append(sheelData)
            # print(datas)
            return datas
        except Exception as e:
            print(str(e))
            print("數據讀取錯誤")

    def write(self,tablespace,table,value):
        title = value[0]
        colnum=len(title)

        # 如果不存在tablespace表空間則新建之
        try:
            import warnings
            sql = "create schema if not exists "+tablespace
            warnings.filterwarnings("error",category=pymysql.Warning)
            self.cursor.execute(sql)
            self.connect.commit()
        except pymysql.Warning as e:
            print(str(e))
        except Exception as e:
            print(str(e))
            print("新建表空間表失敗")
            return

        # 使用對應表空間
        try:
            sql = "use "+tablespace
            self.cursor.execute(sql)
            self.connect.commit()
        except Exception as e:
            print(str(e))
            print("不存在{}表空間!".format(tablespace))

        # 如果表格存在則刪除之
        try:
            sql = "drop table if exists "+table
            self.cursor.execute(sql)
            self.connect.commit()
        except pymysql.Warning as e:
            print(str(e))
        except Exception as e:
            print(str(e))
            print("刪除表失敗")
            return

        # 建表
        try:
            sql = "create table "+table+"(" \
                  "id int primary key,"
            for index in range(colnum):
                sql+= "{} VARCHAR(50),".format(title[index])
            sql = sql.strip(",")
            sql +=");"
            self.cursor.execute(sql)
            self.connect.commit()
        except Exception as e:
            print(str(e))
            print("建表失敗")
            return

        # 插入數據
        try:
            base = "insert into "+table+"(id,"
            # EnglishName, ChineseName, Type) VALUES
            for index in range(colnum):
                base+="{},".format(title[index])
            base = base.strip(",")
            base += ") VALUES \n"
            # plus = "({},'{}','{}','{}'),"
            cnt=1
            for indexi in range(1,len(value)):
                sql=base
                sql+="({},".format(cnt)
                for indexj in range(colnum):
                    tmp = str(value[indexi][indexj])
                    tmp = self.__addslashes(tmp)
                    sql+="'{}',".format(tmp)
                sql = sql.strip(",")
                sql+=");"
                print(sql)
                self.cursor.execute(sql)
                cnt+=1
            self.connect.commit()
            print()
        except Exception as e:
            print(str(e))
            print("插入失敗!")
            print(sql)

    def __addslashes(self,s):
        d = {'"':'\\"', "'":"\\'", "\0":"\\\0", "\\":"\\\\"}
        return ''.join(d.get(c, c) for c in s)

再寫一個程序去調用之:

from Practice.Practice1.ReaderAndWriter import DB,ExcelData
db = DB()
excel = ExcelData()

values = db.read("BondSystem","Bond")
for value in values:
    print(value)

title = []
tmp = values[0]
for key in tmp:
    if key == "Bno":
        continue
    title.append(key)
toValue = []
toValue.append(title)
for value in values:
    tmp = []
    for key in value:
        if key =="Bno":
            continue
        tmp.append(value[key])
    toValue.append(tmp)
for value in toValue:
    print(value)
excel.write("bond.xlsx","bondInf",toValue)

Python可真是好用呢,解決了我不少麻煩!!!

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