js導出Excel可分頁,可鏈式操作


function Point() {}
/*  Point.prototype = {
       x:null,
       y:null,
       setX: function(x) {
           this.x = x;
       },
       getX: function() {
           return this.x;
       },
       setY: function(y) {
           this.y = y;
       },
       getY: function() {
           return this.y;
       }
   } */

function TableModel() {
    this.colNames = [];
    this.pointList = [];
}
TableModel.prototype = {
    setColNames: function (names) {
        this.colNames = names;
    },
    getColNames: function () {
        return this.colNames;
    },
    setPointList: function (pointList) {
        this.pointList = pointList;
    },
    getPointList: function () {
        return this.pointList;
    }
};

function ExcelUtils() {}
ExcelUtils.paramXml = {
    uri: 'data:application/vnd.ms-excel;base64,',
    tmplWorkbookXML: '<?xml version="1.0"?><?mso-application progid="Excel.Sheet"?><Workbook xmlns="urn:schemas-' +
        'microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">' +
        '<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"><Author>Axel Richter</Author><Created>' +
        '{created}</Created></DocumentProperties>' +
        '<Styles>' +
        '<Style ss:ID="Currency"><NumberFormat ss:Format="Currency"></NumberFormat></Style>' +
        '<Style ss:ID="Date"><NumberFormat ss:Format="Medium Date"></NumberFormat></Style>' +
        '<Style ss:ID="s49"/>' +
        '<Style ss:ID="s50">' +
        '<Alignment ss:Horizontal="Center" ss:Vertical="Center"/>' +
        '<Font ss:FontName="宋體" x:CharSet="134" ss:Size="10"/>' +
        '<NumberFormat ss:Format="Medium Date"></NumberFormat>' +
        '</Style>' +
        '<Style ss:ID="s56">' +
        '<Alignment ss:Horizontal="Center" ss:Vertical="Center"/>' +
        '<Borders>' +
        '<Border ss:Position="Bottom" ss:LineStyle="Dash" ss:Weight="1"/>' +
        '</Borders>' +
        '<Font ss:FontName="宋體" x:CharSet="134" ss:Size="12" ss:Bold="1"/>' +
        '<Interior ss:Color="#FFFF00" ss:Pattern="Solid"/>' +
        '<NumberFormat ss:Format="d\-mmm\-yy"/>' +
        '</Style>' +
        '<Style ss:ID="s57">' +
        '<Alignment ss:Horizontal="Center" ss:Vertical="Center"/>' +
        '<Font ss:FontName="宋體" x:CharSet="134" ss:Size="10"/>' +
        '<NumberFormat ss:Format="d\-mmm\-yy"/>' +
        '</Style>' +
        '</Styles>' +
        '{worksheets}</Workbook>',
    tmplWorksheetXML: '<Worksheet ss:Name="{nameWS}"><Table>{column}{rows}</Table></Worksheet>',
    tmplCellXML: '<Cell{attributeStyleID}{attributeFormula}{mergeAcross}><Data ss:Type="{nameType}">{data}</Data></Cell>'

};
ExcelUtils.sheetsXml = [];
ExcelUtils.UserPointModel = Point;
ExcelUtils.colNames = ['col01', 'col02'];
ExcelUtils.addTableHeadJson = [];
/**
 * 添加caption部門,可以添加多個
 * @param headArr
 * @returns {ExcelUtils}
 */
ExcelUtils.addTableHead = function (headArr) {
    ExcelUtils.addTableHeadJson = headArr;
    return ExcelUtils;
};

/**
 * 將數據轉爲Html的table
 * @param tableModel
 * @returns {*|jQuery.fn.init|jQuery|HTMLElement}
 */
ExcelUtils.tableModelConvertToTable = function (tableModel) {
    var tableId = Math.random().toString(36);
    var $table = $('<table id="' + tableId + '"></table>');
    try {
        if (ExcelUtils.addTableHeadJson != null && ExcelUtils.addTableHeadJson != []) {
            $.each(ExcelUtils.addTableHeadJson, function (index, elem) {
                var $tr = $('<tr></tr>');
                var $td = $('<td colspan=' + elem.colspan + '>' + elem.text + '</td>');
                $tr.append($td);
                $table.append($tr);
            })
        }
        var $tr = $('<tr></tr>');
        //添加首行列名字
        $.each(tableModel.getColNames(), function (index, elem) {
            var $td = $('<td>' + elem + '</td>');
            $tr.append($td);
        })
        $table.append($tr);
        //數據填充table
        $.each(tableModel.getPointList(), function (index, point) {
            var $tr = $("<tr></tr>");
            $.each(Object.keys(point), function (index, attr) {
                if (typeof point[attr] != 'function')
                    var $td = $('<td>' + point[attr] + '</td>');
                $tr.append($td);
            })
            $table.append($tr);
        })
        $("#mytable").append($table)
    } catch (e) {
        ExcelUtils.exceptionCall(e);
    }
    return $table;
};

/**
 * 處理數據
 * @param userPointFunction
 * @param dataList
 * @returns {[]}
 */
ExcelUtils.getAxisData = function (userPointFunction, ...dataList) {
    var pointList = [];
    //$.each(dataList,function())
    try {
        if (dataList != null && dataList.length > 0) {
            //初始化模型列表
            $.each(dataList[0], function () {
                pointList.push(new userPointFunction())
            })
            //填充數據
            $.each(Object.keys(new userPointFunction()), function (index, attrName) {
                $.each(dataList[index], function (index, elem) {
                    var point = pointList[index];
                    point[attrName] = elem;
                })
            })
            return pointList;
        } else {
            throw new Error("數據數組不能爲空");
        }
    } catch (e) {
        ExcelUtils.exceptionCall(e);
    }

};
ExcelUtils.base64 = function (s) {
    return window.btoa(unescape(encodeURIComponent(s)))
};
ExcelUtils.format = function (s, c) {
    return s.replace(/{(\w+)}/g, function (m, p) {
        return c[p];
    })
};

/**
 *將table對象轉爲Sheet
 * @param sheetName
 * @param table
 * @returns {string}
 */
ExcelUtils.tableConvertToSheet = function (sheetName, table) {
    var appname = "Excel";
    var ctx = "";
    var workbookXML = "";
    var worksheetsXML = "";
    var rowsXML = "";
    try {
        var table = table[0];
        //控制要導出的行數
        for (var j = 0; j < table.rows.length; j++) {
            if (ExcelUtils.addTableHeadJson != undefined && ExcelUtils.addTableHeadJson != [] && j < ExcelUtils.addTableHeadJson.length) {
                rowsXML += '<Row ss:Height="26">';
            } else {
                rowsXML += '<Row ss:Height="20">';
            }
            for (var k = 0; k < table.rows[j].cells.length; k++) {
                var dataType = table.rows[j].cells[k].getAttribute("data-type");
                var dataStyle = table.rows[j].cells[k].getAttribute("data-style");
                var dataValue = table.rows[j].cells[k].getAttribute("data-value");
                dataValue = (dataValue) ? dataValue : table.rows[j].cells[k].innerHTML;
                var dataFormula = table.rows[j].cells[k].getAttribute("data-formula");
                var colspan = table.rows[j].cells[k].getAttribute("colspan");
                dataFormula = (dataFormula) ? dataFormula : (appname == 'Calc' && dataType == 'DateTime') ? dataValue : null;
                var styleId = "s50";
                if (ExcelUtils.addTableHeadJson != undefined && ExcelUtils.addTableHeadJson != [] && j < ExcelUtils.addTableHeadJson.length) {
                    styleId = "s56";
                }
                ctx = {
                    attributeStyleID: ' ss:StyleID="' + styleId + '"',
                    nameType: (dataType == 'Number' || dataType == 'DateTime' || dataType == 'Boolean' || dataType == 'Error') ? dataType : 'String',
                    data: (dataFormula) ? '' : dataValue,
                    attributeFormula: (dataFormula) ? ' ss:Formula="' + dataFormula + '"' : '',
                    mergeAcross: (colspan) ? ' ss:MergeAcross="' + (colspan - 1) + '"' : '' //合併單元格

                };
                rowsXML += ExcelUtils.format(ExcelUtils.paramXml.tmplCellXML, ctx);
            }
            rowsXML += '</Row>'
        }
        var columnStr = '';
        //設置單元格寬度
        for (var j = 0; j < table.rows.length; j++) {
            columnStr += '<Column ss:Index="' + (j + 1) + '" ss:StyleID="s50" ss:AutoFitWidth="0" ss:Width="156.75"/>'
        }
        ctx = {
            rows: rowsXML,
            nameWS: sheetName,
            column: columnStr
        };

        worksheetsXML += ExcelUtils.format(ExcelUtils.paramXml.tmplWorksheetXML, ctx);
        rowsXML = "";
    } catch (e) {
        ExcelUtils.exceptionCall(e);
    }
    return worksheetsXML;
}

/**
 *
 * @param sheetName 單個sheet的名稱
 * @param userPointFunction 用戶自定義的Point
 * @param colNames 列名數組
 * @param dataList 每列的數據數組
 * @returns {ExcelUtils} 單個sheetXml
 */
ExcelUtils.addSheet = function (sheetName, userPointFunction, colNames, ...dataList) {
    try {
        var pointList = ExcelUtils.getAxisData(userPointFunction, ...dataList);
        var tableModel = new TableModel();
        tableModel.setPointList(pointList);
        tableModel.setColNames(colNames || ExcelUtils.colNames);
        console.log(tableModel.getColNames())
        var $table = ExcelUtils.tableModelConvertToTable(tableModel);
        var sheetXml = ExcelUtils.tableConvertToSheet(sheetName, $table);
        ExcelUtils.sheetsXml.push(sheetXml);
    } catch (e) {
        ExcelUtils.exceptionCall(e);
    }
    return ExcelUtils;
};

/**
 * 下載Excel
 * @param fileName Excel名稱
 * @param workbookXML 整個ExcelXml
 */
ExcelUtils.downExcel = function (fileName, workbookXML) {
    try {
        var link = document.createElement("A");
        link.href = ExcelUtils.paramXml.uri + ExcelUtils.base64(workbookXML);
        link.download = fileName || 'Workbook.xls';
        link.target = '_blank';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    } catch (e) {
        ExcelUtils.exceptionCall(e);
    }

};

/**
 * 清除數據,以及恢復默認值
 */
ExcelUtils.clear = function () {
    ExcelUtils.sheetsXml = [];
    ExcelUtils.UserPointModel = Point;
    ExcelUtils.colNames = ['x軸', 'y軸'];
}

/**
 * 導出函數,執行一些列的導出工作
 * @param fileName
 */
ExcelUtils.export = function (fileName) {
    try {
        var strXml = '';
        $.each(ExcelUtils.sheetsXml, function (index, xml) {
            strXml += xml;
        })
        var ctx = {
            created: (new Date()).getTime(),
            worksheets: strXml
        };
        var workbookXML = ExcelUtils.format(ExcelUtils.paramXml.tmplWorkbookXML, ctx);
        ExcelUtils.downExcel(fileName, workbookXML);
        ExcelUtils.clear();
    } catch (e) {
        ExcelUtils.exceptionCall(e);
    }

}

/**
 * 默認異常回調執行函數
 */
ExcelUtils.defaultExceptionCall = function (e) {
    console.log("導出Excel出現異常:" + e);
}
/**
 * 異常回調函數
 */
ExcelUtils.exceptionCall = function (e) {
    ExcelUtils.defaultExceptionCall(e);
}

/**
 * 設置自定義異常回調函數
 */
ExcelUtils.setExceptionCall = function (fn) {
    ExcelUtils.defaultExceptionCall = fn;
    return ExcelUtils;
}

**

案例

**

//每個sheet需要導出多少個列就用幾個屬性的Point,Point可自定義,下面我只給出2個屬性和3個屬性的,自己可定義4個5個....定義幾個屬性,就要傳多少個數據數組,每個數組時每一列的數據數組。
想添加sheet,直接調用addSheet即可,支持鏈式操作。

 function UserPoint() {
        this.x = null;
        this.y = null;
    }

    function UserPoint2() {
        this.x = null;
        this.y = null;
        this.z = null;
    }
    let headArr1 = [{
        text: "設備名稱/" + deviceName,
        colspan: 2
    }, {
        text: '時間/' + updateTime,
        colspan: 2
    },{
        text: '數據類型/相位-放電次數',
        colspan: 2
    }];
    let headArr2 = [{
        text: "設備名稱/" + deviceName,
        colspan: 3
    }, {
        text: '時間/' + updateTime,
        colspan: 3
    },{
        text: '數據類型/相位-週期-幅值',
        colspan: 3
    }];

    let headArr3 = [{
        text: "設備名稱/" + deviceName,
        colspan: 2
    }, {
        text: '時間/' + updateTime,
        colspan: 2
    },{
        text: '數據類型/相位-幅值',
        colspan: 2
    }];
    ExcelUtils
        .setExceptionCall(()=>{
           //發生異常處理事件
            createDialog3("導出提示","<p style='color: red'>導出Excel發生異常</p>","350","150");
        })
        .addTableHead(headArr1)
        .addSheet("sheet1", UserPoint, ['相位', '放電/次數'], phaseList, dischargingList)
        .addTableHead(headArr2)
        .addSheet("sheet2", UserPoint2, ['相位', '週期', '幅值/V'], x, y, z)
        .addTableHead(headArr3)
        .addSheet("sheet3", UserPoint, ['相位', '幅值/V'], phaseList, amplitudeList)
        .export(excelName + ".xls");

**

效果圖:

**
在這裏插入圖片描述
![在這裏插入圖片描述]
在這裏插入圖片描述
在這裏插入圖片描述

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