利用ExtJS導出Excel


Ext.ns("Msp.Component");

//config = {
//    fileName : "凈值及頭寸核對",
//    exportDate : "2014-01-20",
//    dataSource : [
//        {grid : grid1, param : param1, showType : true},
//        {grid : grid2, param : param2, showType : false}
//    ],
//    hiddenColumnArr : ["assetName"],
//    isMail : true,
//    filePath : "C:\\mspMail\\"
//}

Msp.Component.PageToExcel = function(config){
    this.initialConfig = config;
    this.excel = null;
    this.workBook = null;
    this.sheet = null;
    
    //是否發送郵件
    this.isMail = false;
    //如果是發送郵件,生成excel附件的存放目錄
    this.filePath = "C:\\mspMail\\";
    //導出日期,默認為當天
    this.exportDate = getCurDate();
    //定時執行垃圾回收的標識
    this.idTmr = "";
    this.dataSource = [];
    
    //過濾自定義不顯示的列
    this.hiddenColumnArr = ['checked','checkerId','checkTime'];
    Ext.apply(this,config);
};

Msp.Component.PageToExcel.prototype = {
    
    /**
     * 創建excel對象
     */
    createExcel : function(){
        try{
            this.excel = new ActiveXObject("Excel.Application");
            //控制execl是否打開  true 打開  ,false  不打開
            this.excel.Visible = false;
            this.workBook = this.excel.Workbooks.Add();
            this.sheet = null;
        }catch(e){
            sofa.alert("請確認安裝了非綠色版本的excel!"+e.description);
        }
    },
    
    /**
     * 關閉excle對象
     */
    closeExcel : function(){
        if(this.workBook != null){
            this.workBook.Close(SaveChanges=false);
        }
        if(this.excel != null){
            this.excel.Quit();
        }
        this.workBook = null;   
        this.sheet = null;
        //EXCEL.EXE進程清理
        this.idTmr = window.setInterval(this.cleanup,1);
    },
    
    /**
     * EXCEL.EXE進程清理
     */
    cleanup : function(){
        window.clearInterval(this.idTmr);
          window.CollectGarbage();
    },
    
    /**
     * 默認的sheet不夠用時,添加額外的sheet
     */
    addSheetsExt : function(){
        //默認的sheet數量,經測試win7默認3個sheet,xp默認1個sheet
        var    defaultSheetNum = this.workBook.Sheets.count,
            count = 0;//需要sheet的個數
        for(var i = 0; i < this.dataSource.length; i++){
            //判斷是否需要生成新的sheet,如果默認的sheet不夠用則生成新的sheet
            if(this.dataSource[i].showType){
                count++;
                if(count > defaultSheetNum){
                    this.workBook.Sheets.add;
                }
            }
        }    
    },
    
    /**
     * 生成一個excel文件
     */
    handleExcel : function(){
        
        if(this.dataSource && this.dataSource.length > 0){
            var layerNum = 0,//sheet的層數
                rowIndex = 0;//行索引
            
            this.addSheetsExt();
            
            for(var i = 0; i < this.dataSource.length; i++){
                if(this.dataSource[i].showType){
                    layerNum ++;
                    this.sheet = this.workBook.Worksheets(layerNum);
                    this.sheet.name = "第【"+layerNum+"】層";
                    
                    //行索引歸零
                    rowIndex = 0;
                }
                //生成數據到sheet,並返回當前grid的總記錄數
                var totalRecords = this.changeGridToExcel(this.dataSource[i].grid,this.dataSource[i].param,this.sheet,rowIndex);
                //保存grid查詢出來的總記錄數,方便以后統計異常記錄數
                this.dataSource[i].total = totalRecords;
                if(totalRecords > 0){
                    rowIndex = rowIndex + totalRecords + 3;
                }
            }
        }
            
    },
    
    /**
     * 構建工作表的標題
     * @param {} sheet 工作表
     * @param {} rowIndex 行索引
     * @param {} colNum 總列數
     * @param {} titleName 標題名稱
     */
    buildTitle : function(sheet, rowIndex, colNum, titleName){
        /***************************************標題開始***********************************************/
        //合並標題單元格
        sheet.Range("A"+(rowIndex+1),sheet.Cells(rowIndex+1,colNum)).MergeCells=true;
        //居中顯示
        sheet.Cells(rowIndex+1,1).HorizontalAlignment=3;
        //設置粗體
        sheet.Cells(rowIndex+1,1).Font.Bold=true;
        //字體大小
        sheet.Cells(rowIndex+1,1).Font.Size=15;
        //字體顏色
        sheet.Cells(rowIndex+1,1).Font.ColorIndex=10;
        //模塊名稱
        sheet.Cells(rowIndex+1,1).value = titleName;
        /***************************************標題結束***********************************************/
        
        /***************************************導出日期開始*******************************************/
        //合並時間單元格
        sheet.Range("A"+(rowIndex+2),sheet.Cells(rowIndex+2,colNum)).MergeCells=true;
        //居左顯示
        sheet.Cells(rowIndex+2,1).HorizontalAlignment=2;
        //導出日期
        sheet.Cells(rowIndex+2,1).value = this.exportDate;
        /***************************************導出日期結束*******************************************/
    },
    
    /**
     * 構建工作表的內容
     * @param {} sheet 工作表
     * @param {} rowArr 行數組
     * @param {} columnArr 列數組
     * @param {} rowIndex 行索引
     * @return {} 工作表的列數
     */
    buildContent : function(sheet, rowArr, columnArr, rowIndex){
        //標題行、日期行、表頭行占三行
        var startIndex = rowIndex + 3;
        /***************************************內容設置開始***********************************************/
        for (var i = 0;i< rowArr.length; i++){ 
            var count = 1;
            for(var j = 0;j< columnArr.length;j++){
                //列出不隱藏的列
                if(columnArr[j].hidden == undefined && !Ext.isEmpty(columnArr[j].dataIndex) ){
                    //過濾自定義不顯示的列
                    if(this.hiddenColumnArr && this.hiddenColumnArr.indexOf(columnArr[j].dataIndex) > -1){
                        continue;
                    }    
                    //居中顯示
                    sheet.Cells(startIndex+1+i,count).HorizontalAlignment=3;
                    //邊框樣式
                    sheet.Cells(startIndex+1+i,count).Borders.LineStyle=1;
                    //單元格邊框顏色
                    sheet.Cells(startIndex+1+i,count).Borders.ColorIndex=10;
                    //將單元置為文本,避免非數字列被自動變成科學計數法和丟失前綴的0
                    sheet.Cells(startIndex+1+i,count).NumberFormat = "@";
                    
                    var viewValue = rowArr[i][columnArr[j].dataIndex];
                    if(columnArr[j].renderer != undefined && !Ext.isEmpty(viewValue)){
                        //頁面渲染時需要使用當前行的數據作為判斷條件
                        var rdata = {};
                        rdata.data = rowArr[i];
                        viewValue = columnArr[j].renderer(viewValue,null,rdata);
                    }
                    if(viewValue == undefined){
                        viewValue = '';
                    }
                    if(viewValue != null){
                        viewValue = Ext.util.Format.trim(viewValue.toString());//去空格
                    }
                    //viewValue 前面加空格是為了處理 2/2的數據格式,cells默認會理解為日期
                    sheet.Cells(startIndex+1+i,count).value = " "+viewValue;
                    count++;
                }
            } 
        }
        /***************************************內容設置結束***********************************************/
        return count - 1;
    },
    
    /**
     * 構建工作表的列頭
     * @param {} sheet 工作表
     * @param {} columnArr 列頭數組
     * @param {} rowIndex 行索引
     */
    buildHeader : function(sheet, columnArr, rowIndex){
        /***************************************列頭設置開始***********************************************/
        //標題行、日期行、表頭行占三行
        var startIndex = rowIndex + 3;
        var count = 1;
        for (var i = 0 ;i < columnArr.length; i++){
            //列出不隱藏的列頭項並排除序號列和復選框列
            if(!columnArr[i].hidden && 
               (columnArr[i].header && columnArr[i].header.length>0 && columnArr[i].header != '序號') &&
                columnArr[i].id != 'checker'){
                //過濾自定義不顯示的列
                if(this.hiddenColumnArr && this.hiddenColumnArr.indexOf(columnArr[i].dataIndex) > -1){
                    continue;
                }    
                //居中顯示
                sheet.Cells(startIndex,count).HorizontalAlignment=3;
                //設置粗體
                sheet.Cells(startIndex,count).Font.Bold=true;
                //列頭名稱
                sheet.Cells(startIndex,count).value = columnArr[i].header;
                //邊框樣式
                sheet.Cells(startIndex,count).Borders.LineStyle=1;
                //單元格邊框顏色
                sheet.Cells(startIndex,count).Borders.ColorIndex=10;
                //單元格底色
                sheet.Cells(startIndex,count).Interior.ColorIndex=2;
                count++;
            }
        }
        /***************************************列頭設置結束***********************************************/
    },
    
    /**
     * 將grid的數據寫入到sheet中
     * @param {} grid 表格
     * @param {} param 查詢參數
     * @param {} sheet 當前工作表
     * @param {} rowIndex 行索引,記錄寫入行的起始位置
     * @return {} 總記錄數
     */
    changeGridToExcel : function(grid, param, sheet,rowIndex){
        var totalRecords = 0;
        sofa.api.request({
              url:grid.url,
              params : param,
              method:'post',
              async:false,
              success: function(response){
                  var rowArr = null;//行數組
                  if(typeof response.responseText == 'string'){
                      rowArr = Ext.decode(response.responseText);
                  }
                  if(rowArr == null || rowArr.length == 0){
                      return 0;
                  }
                  var columnArr = grid.getColumnModel().config;//列數組
                try{
                    //生成內容
                    var colNum = this.buildContent(sheet, rowArr, columnArr, rowIndex);
                    //生成列頭
                    this.buildHeader(sheet, columnArr, rowIndex);
                    //標題
                    var titleName = (sheet.name == '第【1】層' ? this.fileName : rowArr[0]['bizName']);
                    //生成標題
                    this.buildTitle(sheet, rowIndex, colNum,titleName);
                    //列自增長
                    sheet.Columns.AutoFit();
                    totalRecords = rowArr.length;
                }catch(e){
                }
            },
            scope:this
        });
        return totalRecords;
    },
    
    /**
     * 保存
     */
    saveExcel :function(){
        var savePath = null;
        //導出發送郵件用的excel文件
        if(this.isMail){
            //無異常記錄不保存
            if(this.dataSource[0].total != 0){
                savePath = this.filePath+this.fileName+".xls";
                if(!Ext.isEmpty(savePath)){
                    this.sheet.SaveAs(savePath);
                }
            }
        //默認的excel導出
        }else{
            savePath = this.excel.Application.GetSaveAsFilename(this.fileName+".xls","Excel Spreadshsheets (*.xls),*.xls,(*.xlsx),*.xlsx");
            if(!Ext.isEmpty(savePath)){
                this.sheet.SaveAs(savePath);
            }
        }    
    },
    
    /**
     * excel導出
     */
    exportExcel : function(){
        try{
            this.createExcel();
            this.handleExcel();
            this.saveExcel();
        }catch(e){
        }finally{
            this.closeExcel();
        }
    }
};


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM