【QuotationTool】View的實(shí)現(xiàn),輸出Excel

項(xiàng)目鏈接:https://gitee.com/duyang2903/quotationTools

通過(guò)Controller和Model的配合,我們已經(jīng)獲得了最后我們來(lái)討論一下,如何生成Excel。這在MVC模式中就相當(dāng)于View,也就是展示層。

這一層的代碼放在framework/libs/view/XlsWriterClass.py中。

總體思想

同樣,我們希望每個(gè)sheet的格式(顏色,寬度)什么的都不一樣,所以可以把這些配置參數(shù)都單列出來(lái)。

我們它們放到tpl這個(gè)文件夾下。

準(zhǔn)備工作

首先需要把tpl中的模板加載進(jìn)來(lái)

我們可以先看一下tpl中模板,比如說(shuō)下面的為價(jià)格明細(xì)清單的

header={'num_format':'#,##0','font_name':'Arial','font_size':10,'font_color':'#000000','bg_color':'#c0c0c0','bold':True,'bottom':0}
headerOff={'num_format':'#,##0','font_name':'Arial','font_size':10,'font_color':'#000000','bg_color':'#c0c0c0','bold':True,'bottom':0}
site={'num_format':'0','font_name':'Arial','font_size':10,'font_color':'#ffffff','bg_color':'#339966','bold':False,'bottom':0}
siteOff={'num_format':'0.00%','font_name':'Arial','font_size':10,'font_color':'#ffffff','bg_color':'#339966','bold':False,'bottom':0}
subtotal={'num_format':'#,##0','font_name':'Arial','font_size':10,'font_color':'#000000','bg_color':'#c0c0c0','bold':True,'bottom':1}
subtotalOff={'num_format':'0.00%','font_name':'Arial','font_size':10,'font_color':'#000000','bg_color':'#c0c0c0','bold':True,'bottom':1}
total={'num_format':'#,##0','font_name':'Arial','font_size':10,'font_color':'#000000','bg_color':'#c0c0c0','bold':True,'bottom':1}
totalOff={'num_format':'0.00%','font_name':'Arial','font_size':10,'font_color':'#000000','bg_color':'#c0c0c0','bold':True,'bottom':1}

general={'num_format':'#,##0','font_name':'Arial','font_size':10,'font_color':'#000000','bold':False,'bottom':0}
generalOff={'num_format':'0.00%','font_name':'Arial','font_size':10,'font_color':'#000000','bold':False,'bottom':0}

同樣我們把行分為site,total,general,subtotal等多種類型,同時(shí)因?yàn)檎劭哿行枰褂?,所以單獨(dú)區(qū)分開(kāi)了。而且很有規(guī)律,是site+off

可以使用如下的函數(shù)進(jìn)行加載

   # ***************加載format*****************
   def addFormat(self):
       # 默認(rèn)在tpl文件中設(shè)置每個(gè)sheet的格式
       tpl = __import__("tpl." + self.view)
       sheet = getattr(tpl , self.view);
       types = getattr(sheet , "types");
       typeDict = {};
       # # 對(duì)所列出來(lái)的顏色類型的名稱一一的列舉
       for type in types:
           typeDict [type] = self.workbook.add_format(getattr(sheet , type ));
       return typeDict;

同樣可以使用assign把要傳遞進(jìn)去的變量搞進(jìn)去

    def assign(self, lists, outputKeys, sheetName, view):
        self.lists = lists;
        self.outputKeys = outputKeys;
        self.sheetName = sheetName;
        self.view = view;
        # 從文件中讀取format的類型,獲得format數(shù)組
        self.dFormat = {};
        self.dFormat = self.addFormat();
        # 將要輸出的outputKeys與每一列的序號(hào)組成dict,方便后面調(diào)度
        colOrdinal = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
                      'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
        # 先組合成為dict
        self.colIndexes = dict(zip(self.outputKeys, colOrdinal));
        

打印數(shù)組

然后是調(diào)用XlsxWriter進(jìn)行打印。

首先需要獲取要打印的sheet名稱

    # 如果sheetName對(duì)應(yīng)的sheet還沒(méi)建立則建立,若已建立則獲取
    if self.workbook.get_worksheet_by_name(sheetName) is None:
        worksheet = self.workbook.add_worksheet(sheetName);
    else:
        worksheet = self.workbook.get_worksheet_by_name(sheetName);

然后就是把傳進(jìn)來(lái)的list遍歷

按照預(yù)先設(shè)定的輸出Excel列進(jìn)行打印

之前不是說(shuō)過(guò)折扣列格式不同嗎?而且折扣列的格式一般為"xxxOff"這種,我們可以拼接在一起

    # 定義全局變量
    col = 0;
    arr = self.lists;
for row in range(len(arr)):
    # 依次取每個(gè)要輸出的每一列對(duì)應(yīng)的key值
    for outkey in self.outputKeys:
        formatKey = "";
        # 若outkey等于discount,rate則單獨(dú)設(shè)置格式
        if outkey == "discount" or outkey == 'rate':
            formatKey = arr[row]["colorTag"] + "Off";
        else :
            formatKey = arr[row]["colorTag"];
        
        # 打印每個(gè)單元格
        worksheet.write(row , col , arr[row][outkey] , self.dFormat[formatKey])
        col += 1;

        col = 0;

設(shè)置其他行寬,列寬

打印完成以后還可以設(shè)置行寬,列寬

# *************設(shè)置每列的寬度*************
def setColumn(self):
    # 列序號(hào)
    worksheet = self.workbook.get_worksheet_by_name(self.sheetName);
    tpl = __import__("tpl." + self.view)
    sheet = getattr(tpl , self.view);
    colBreath = getattr(sheet , "colbreath");
    for outputKey in self.outputKeys:
        worksheet.set_column(self.colIndexes[outputKey] + ":" + self.colIndexes[outputKey], colBreath[outputKey]);
# *************設(shè)置哪些列進(jìn)行隱藏*************
def setHidden(self, hideCols):
    worksheet = self.workbook.get_worksheet_by_name(self.sheetName);
    debug(self.sheetName)
    debug(self.workbook)
    debug(worksheet);
    # 取出hideCols與outputKeys中重合的部分
    hideColumns = [i for i in hideCols if i in self.outputKeys];
    for hideCol in hideColumns:
        worksheet.set_column(self.colIndexes[hideCol] + ":" + self.colIndexes    [hideCol], None,None, {'hidden': 1});
        
# *************設(shè)置自動(dòng)篩選*************
def setAutofilter(self):
    worksheet = self.workbook.get_worksheet_by_name(self.sheetName);
    begin = "A1";
    # 末尾的列序號(hào)是outputKeys的最后一位
    endColumn = self.colIndexes[self.outputKeys[-1]];
    worksheet.autofilter("A1:" + endColumn + str(len(self.lists)));
    
# *************凍結(jié)首行*************
def freezeTopRow(self):
    worksheet = self.workbook.get_worksheet_by_name(self.sheetName);
    worksheet.freeze_panes(1, 0)
    return

# *************打印URL*************
def writeURL(self):
    worksheet = self.workbook.get_worksheet_by_name(self.sheetName);
    arr = self.lists;
    for i in range(1, len(arr) - 1):
        cellIndex = self.colIndexes['description'] + str(i + 1);
        worksheet.write_url(cellIndex, arr[i]['url'], self.dFormat['link'],arr[i]['description']);

如何調(diào)用

同樣可以在Controller中進(jìn)行調(diào)用

xlswriter = XlsWriter(outputPath);
# —————————————————————————打印價(jià)格明細(xì)—————————————————————————
xlswriter.assign(lists,list(outputParam.keys()),sheetName,"totalConfigformat");
# xlswriter.setHidden(hideCols);
xlswriter.display();    
info("成功打印價(jià)格明細(xì)")
image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 使用首先需要了解他的工作原理 1.POI結(jié)構(gòu)與常用類 (1)創(chuàng)建Workbook和Sheet (2)創(chuàng)建單元格 (...
    長(zhǎng)城ol閱讀 8,744評(píng)論 2 25
  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,602評(píng)論 19 139
  • 很多事情,明明知道,還是不由自主的去做。明明不確定未來(lái),就是知道沒(méi)有結(jié)果,還是忍不住給自己希望。想要的不確定是否真...
    d0cf46af0d87閱讀 241評(píng)論 0 0
  • 他的眼神 如藍(lán)天白云般清澈 那雙眼睛 曾虔誠(chéng)仰望佛祖 他的歌聲 如撩撥弦琴般悠悠 那片嘴唇 曾焚香閉目誦經(jīng) 他的身...
    嬌子分享閱讀 83評(píng)論 0 1
  • 從好男人文章,到好男人陳赫,到劉愷威,再到林丹,出軌早已成了娛樂(lè)圈司空見(jiàn)慣,屢見(jiàn)不鮮的新聞,廣大吃瓜群眾一如既往樂(lè)...
    本天才傳說(shuō)閱讀 243評(píng)論 0 0

友情鏈接更多精彩內(nèi)容