flask導出Excel報表詳解

在日常開發中,導出數據報表可謂必備技能,在後臺管理中,很多模塊都需要數據報表,現在我們一起來學習一下 flask 如何導出數據報表。

沒有實例的講解很不容易理解,本文我們依然從實際項目來講解,對 “flask+mysql微信小程序開源項目” 進一步擴展 ,教大家以項目爲驅動來學習軟件開發技術 。

1、後臺接口編寫

flask 可以使用 xlwt 擴展插件來完成對 Excel 的操作,若你的虛擬環境中沒有安裝 xlwt ,執行下面命令進行安裝

pip install xlwt

安裝成功後,在 controller/api/api.py 頭部引入 xlwt

import xlwt as xlwt

創建導出 Excel 數據報表的接口路由

# 導出數據
@api.route('exportData', methods=['POST'])
def exportData():
    wb = xlwt.Workbook()
    ws = wb.add_sheet('報修數據報表')
    first_col = ws.col(0)  # xlwt中是行和列都是從0開始計算的
    second_col = ws.col(1)
    third_col = ws.col(2)
    four_col = ws.col(3)
    five_col = ws.col(4)
    first_col.width = 128 * 20
    second_col.width = 230 * 20
    third_col.width = 230 * 20
    four_col.width = 128 * 20
    five_col.width = 230 * 20
    ws.write(0, 0, "報修人")
    ws.write(0, 1, "聯繫電話")
    ws.write(0, 2, "報修地點")
    ws.write(0, 3, "報修描述")
    ws.write(0, 4, "報修備註")
    ws.write(0, 5, "報修時間")
    dataw = RepairServiceSheet.query.order_by(RepairServiceSheet.id.desc()).all()
    if dataw is not None:
        for i in range(0, len(dataw)):
            pet = dataw[i]
            repairDate = ''
            if pet.repairDate is not None:
                repairDate = pet.repairDate.strftime('%Y-%m-%d %Z %H:%M:%S')
            ws.write(i + 1, 0, pet.applicantName)
            ws.write(i + 1, 1, pet.mobile)
            ws.write(i + 1, 2, pet.address)
            ws.write(i + 1, 3, pet.description)
            ws.write(i + 1, 4, pet.remarks)
            ws.write(i + 1, 5, repairDate)
    now = str(time.time())
    path = "/static/excel/"
    fileName = "repair_" + now + ".xls"
    file_path = basedir + path
    if not os.path.exists(file_path):
        os.makedirs(file_path)
    file_path = file_path + fileName
    try:
        f = open(file_path, 'r')
        f.close()
    except IOError:
        f = open(file_path, 'w')
    wb.save(file_path)
    return path+fileName

代碼詳解:

1)使用創建 xlwt 創建 Workbook,並添加一個 sheet 頁

    wb = xlwt.Workbook() # 創建一個workbook
    ws = wb.add_sheet('報修數據報表') #添加一個excel sheet頁 

2) 獲取 excel 的列,行列均是從0開始,這裏我們導出的Excel,只有 5 列,因此獲取 excel 中的 5 列對象。

    first_col = ws.col(0)  # xlwt中是行和列都是從0開始計算的
    second_col = ws.col(1)
    third_col = ws.col(2)
    four_col = ws.col(3)
    five_col = ws.col(4)
    six_col = ws.col(6)

3)對每列設置不同的寬度 ,可以不設置即使用默認寬度,也可對不同列設置不同的寬度。

    first_col.width = 128 * 20
    second_col.width = 230 * 20
    third_col.width = 230 * 20
    four_col.width = 128 * 20
    five_col.width = 230 * 20
    six_col.width=230 * 20

4) 寫入表頭 ,即Excel的第一行標題行

在這裏插入圖片描述
寫入標題行使用 ws.write() 方法,第一個參數表示第1行,第二個參數表示第幾列,第三個參數表示第幾行第幾列顯示的文本內容。

    ws.write(0, 0, "報修人")
    ws.write(0, 1, "聯繫電話")
    ws.write(0, 2, "報修地點")
    ws.write(0, 3, "報修描述")
    ws.write(0, 4, "報修備註")
    ws.write(0, 5, "報修時間")

5)從數據庫中查詢出報修記錄,遍歷集合並從第二行開始設置單元格顯示的內容,遍歷寫入單元格依然使用 ws.write() 方法。

  dataw = RepairServiceSheet.query.order_by(RepairServiceSheet.id.desc()).all()
    if dataw is not None:
        for i in range(0, len(dataw)):
            pet = dataw[i]
            repairDate = ''
            if pet.repairDate is not None:
                repairDate = pet.repairDate.strftime('%Y-%m-%d %Z %H:%M:%S')
            ws.write(i + 1, 0, pet.applicantName)
            ws.write(i + 1, 1, pet.mobile)
            ws.write(i + 1, 2, pet.address)
            ws.write(i + 1, 3, pet.description)
            ws.write(i + 1, 4, pet.remarks)
            ws.write(i + 1, 5, repairDate)

6)定義 Excel 文件名、文件保存路徑、若目錄不存在則創建

    now = str(time.time()) # 獲取當前時間,作爲文件名後綴
    path = "/static/excel/" # 保存 Excel 的相對路徑
    fileName = "repair_" + now + ".xls" # Excel 文件名
    file_path = basedir + path # 保存 Excel 的絕對路徑 
    if not os.path.exists(file_path): # 判斷目錄是否存在
        os.makedirs(file_path) # 目錄不存在則創建 
    file_path = file_path + fileName # 需要保存的文件

7) 使用 open() 打開文件,注意 open() 使用後必須記得 close() ,使用 wb.save(file_path) 將 sheet 數據寫入文件。return path+fileName 返回文件地址給前臺供前臺下載 Excel 使用。

    try:
        f = open(file_path, 'r')
        f.close()
    except IOError:
        f = open(file_path, 'w')
        f.close()
    wb.save(file_path)
    return path+fileName

2、編寫前臺頁面

1)在 listView.html 中增加一個按鈕 button, 如下:

<div class="content">
    <button class="layui-btn layui-btn-warm" onclick="exportData()">導出報表</button>
    <fieldset class="layui-elem-field layui-field-title">
        <legend>報修管理</legend>
    </fieldset>
    ...
</div>

2)在 javascript 中增加 js 函數,如下:

   function exportData() {
        $.ajax({
            cache: true,
            type: "POST",
            url: "/api/exportData",
            async: false,
            error: function (request) {
                return false;
            },
            success: function (result) {
                console.log(result);
                window.location.href = result;
            },
            complete: function () {
            },
            error: function (data) {
                layer.msg('導出失敗,請重試!', {icon: 5});
            }
        });

其中 window.location.href = result; 即直接連接到文件地址,瀏覽器會自動下載。

總結:

導出Excel 數據報表是後端開發人員必會技能 ,在本文中我們對報修小程序源碼進行拓展,導出數據報表也是報修小程序必備的功能。你應該學會如何編寫導出 Excel 數據報表的功能,同時動手將你的源碼擴展,加入導出 Excel 數據報表的功能 ,自己動手、豐衣足食~!


開源報修小程序源碼介紹地址:

開源 flask + mysql 校園報修微信小程序系統

如果你遇見任何問題,可掃碼關注我,與我交流!
在這裏插入圖片描述

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