Just do your best!!!

Handsontable自用封装

代码如下:

var form1_obj = {};
//Excel导出的form
var form1 = document.createElement("form");
form1.setAttribute("method","post");
form1.setAttribute("action","exportExcelDocument.do");
//jsonData
form1_obj.jsonData = document.createElement("input");
form1_obj.jsonData.setAttribute("type","hidden");
form1_obj.jsonData.setAttribute("name","jsonData");
form1_obj.jsonData.setAttribute("id","jsonData");
//titles
form1_obj.titles = document.createElement("input");
form1_obj.titles.setAttribute("type","hidden");
form1_obj.titles.setAttribute("name","titles");
form1_obj.titles.setAttribute("id","titles");
//fileName
form1_obj.fileName = document.createElement("input");
form1_obj.fileName.setAttribute("type","hidden");
form1_obj.fileName.setAttribute("name","fileName");
form1_obj.fileName.setAttribute("id","fileName");
//titleLengths
form1_obj.titleLengths = document.createElement("input");
form1_obj.titleLengths.setAttribute("type","hidden");
form1_obj.titleLengths.setAttribute("name","titleLengths");
form1_obj.titleLengths.setAttribute("id","titleLengths");
//mergeCells
form1_obj.mergeCells = document.createElement("input");
form1_obj.mergeCells.setAttribute("type","hidden");
form1_obj.mergeCells.setAttribute("name","mergeCells");
form1_obj.mergeCells.setAttribute("id","mergeCells");
//form1.setAttribute("action","post");
form1.appendChild(form1_obj.jsonData);
form1.appendChild(form1_obj.titles);
form1.appendChild(form1_obj.fileName);
form1.appendChild(form1_obj.titleLengths);
form1.appendChild(form1_obj.mergeCells);
//append to body
document.getElementsByTagName("body")[0].appendChild(form1);

var container = document.getElementById('tab'), 
conf, hooks, hot1, table_data, table_headers,
//excel导出相关参数
/*
jsonData;//json数据
titles;//表头
fileName;//下载的excel文件名
titleLengths;//列宽
mergeCells;//合并单元格
 */
jsonData,titles,fileName,titleLengths,mergeCells;

//表格需要用到的配置
var h_table = {
    // 获取并设置网页高度
    //有参数时,计算高度 - 参数1的值
    w_height : function() {
        var height = window.document.body.offsetHeight;
        if(arguments.length == 1){
            return height - arguments[0];
        }
        if (height && height < 600) {
            if (h_table.browser.isUser) {
                height = height / 2;
            } else {
                height = height / 2 - 25;
            }
        } else {
            height = height - 280;
        }
        return height;
    },
    // 设置表内容、样式、格式(如:"html")
    columns : [],
    //自定义菜单
    menuItem:["commentsAddEdit","commentsRemove"],
    //表头
    headers : null,
    //合并第一列的高度设置
    rowHeight : null,
    //填报,设置前几行是表头(不包含该行,从0开始计数)
    reportRowHeader : 1,
    //审核的批注
    checkComments : [],
    //表数据
    data : null,// json format data
    // rowHeaders:table_row_headers
    //审核批注的管理
    addOrUpdateComments : function(obj){
        if(obj){
            var flag = _.find(h_table.checkComments,function(o){
                if(o.row == obj.row && o.col == obj.col){
                    if(o.comment != obj.comment){
                        o.comment = obj.comment;
                    }
                    return true;
                }
                return false;
            });
            if(!flag){
                h_table.checkComments.push(obj);
            }
        }
    },
    //批注删除
    deleteComments:function(obj){
        if(obj){
            var flag = false;
            for(var a in h_table.checkComments){
                var o = h_table.checkComments[a];
                if(o.row == obj.row && o.col == obj.col && o.value == obj.value){
                    h_table.checkComments[a] = null;
                    flag = true;
                    break;
                }
            }
            if(flag){
                h_table.checkComments = _.compact(h_table.checkComments);
            }
        }
    },
    //判断是添加还是编辑批注
    checkSelectionCommentsConsistency : function(cell){
        var hasComment = false;
        if (hot1.getCellMeta(cell.row, cell.col).comment) {
          hasComment = true;
        }
        return hasComment;
    },
    //ajax 获取数据
    ajax:function(url,data,callback){
        $.ajax({
            type : "POST",
            url : url,
            data : data,
            dataType : "json",
            success : callback,
            error : function(e) {
                alert("出错了");
            }
        });
    },
    //检测浏览器类型
    browser : {
        userAgent : navigator.userAgent,
        getType : function() {
            if (h_table.browser.userAgent.indexOf("MSIE") != -1
                    || h_table.browser.userAgent.indexOf("Firefox") != -1) {
                return true;
            } else {
                return false;
            }
        },
        isUser : false
    },
    // 设置表头的样式
    oneRowRenderer : function (instance, td, row, col, prop, value, cellProperties) {
        Handsontable.renderers.TextRenderer.apply(this, arguments);
        // td.className = "td1";
        td.style.fontWeight = 'bold';
        td.style.color = 'black';
        td.style.textAlign = 'center';
        td.style.verticalAlign = 'middle';
        td.style.padding = '3px 3px';
        // td.style.background = '#CEC';
        td.style.background = 'rgb(198,229,250)';
        // td.style.background = 'url(../images/right-img6.jpg) repeat-x';
        td.style.fontSize = '12px';
    },
    // 设置“隔行变色”的样式
    changColorRenderer : function (instance, td, row, col, prop, value, cellProperties) {
        Handsontable.renderers.TextRenderer.apply(this, arguments);
        // td.className = "td1";
        // td.style.fontWeight = 'bold';
        td.style.fontSize = '12px';
        td.style.color = 'black';
        // td.style.textAlign='center';
        // td.style.verticalAlign = 'middle';
        // td.style.background = '#f9f9f9';
        td.style.padding = '3px 3px';
        //第一列设置自定义样式
        if(h_table.boldOneCol){
            h_table.boldOneCol(col,td,value);
        }
        // 隔行变色
        // 排除title行
        if (h_table.row != undefined && h_table.row != null && row > h_table.row && (row) % 2 == 0) {
            td.style.backgroundColor = '#EFF0F4';
        }
        if(col == 0){
            //根据数据判断是否根据数组的值进行设置高度
            if(h_table.rowHeight !== null && h_table.rowHeight.length > row){
                height = h_table.rowHeight[row];
                $(td).parent("tr").css("height",height+"px");
            }
        }
    },
    //合并第一列设置,通过设置表格TR的高度解决合并行后高度不相等问题
    oneColRenderer : function (instance, td, row, col, prop, value, cellProperties) {
        Handsontable.renderers.TextRenderer.apply(this, arguments);
        // td.className = "td1";
        td.style.fontWeight = 'bold';
        td.style.color = 'black';
        td.style.textAlign = 'center';
        td.style.verticalAlign = 'middle';
        td.style.padding = '2px 2px';
        // td.style.background = '#CEC';
        td.style.background = 'rgb(198,229,250)';
        if(col == 0){
            //根据数据判断是否根据数组的值进行设置高度
            if(h_table.rowHeight !== null && h_table.rowHeight.length > row){
                height = h_table.rowHeight[row];
                $(td).parent("tr").css("height",height+"px");
            }
        }
        td.style.fontSize = '12px';
    },
    //填报
    reportRenderer : function (instance, td, row, col, prop, value, cellProperties) {
        Handsontable.renderers.TextRenderer.apply(this, arguments);
        // td.className = "td1";
        //td.style.fontWeight = 'bold';
        td.style.color = 'black';
        td.style.textAlign = 'center';
        td.style.verticalAlign = 'middle';
        // td.style.background = '#CEC';
        //设置填报行的高度,防止填报时高度变成7px,需设置h_table.reportRowHeader属性(从0开始计数)
        if(row > h_table.reportRowHeader){
            $(td).parent("tr").css("height","28px");
        }else{
            td.style.padding = '2px 2px';
        }
        //设置只读行、列的背景(排除第一列)
        if(col != 0 && h_table.readOnlyCol && h_table.readOnlyRow && 
                (_.indexOf(h_table.readOnlyCol,col) != -1 || _.indexOf(h_table.readOnlyRow,row) != -1)){
            td.style.background = "#EEE";
        }
        td.style.fontSize = '12px';
    },
    onSelection:function (row, col, row2, col2) {
        var meta = this.getCellMeta(row2, col2);
        if (meta.readOnly) {
          this.updateSettings({fillHandle: false});
        }
        else {
          this.updateSettings({fillHandle: true});
        }
    },
    //excel导出
    exportExcel:function(jsonData,titles,fileName,titleLengths,mergeCells){
        if(arguments.length == 5 && jsonData && titles && fileName && titleLengths){
            form1_obj.jsonData.value = jsonData;
            form1_obj.titles.value = titles;
            form1_obj.fileName.value = fileName;
            form1_obj.titleLengths.value = titleLengths;
            if(mergeCells !==undefined && mergeCells !== null && mergeCells != ""){
                form1_obj.mergeCells.value = mergeCells;
            }
            form1.submit();
        }else{
            alert("导出出错!");
        }
    },
    //去除jsonData里的span标签
    escapeHtml:function(value){
        if(arguments.length == 1 && value){
            value = value.replace(/<([\s|\S]*?)>/,"");
            value = value.replace(/<.?span>/,"").trim();
            return value;
        }
    },
    //multiSelect下拉多选框选中的值
    getMutiValues : function(ele){
        return $(ele).map(function () { return $(this).val(); }).get().join(',');
    },
    //根据row col获取cell的值
    getCell : function(row,col){
        var val = hot1.getDataAtCell(row,col);
        if(val && typeof val == "string"){
            return val.trim();
        }
        return val;
    },
    //类属性检测
    getStr : function(ele){
        return Object.prototype.toString.call(ele);
    }
};

//初始化一些表格的配置
function init_h_table() {
    // 获取是否是要跳过的浏览器(用于根据浏览器的类型计算高度)
    h_table.browser.isUser = h_table.browser.getType();
}
init_h_table();

//渲染表格
h_table.initHandson = function(){
    hot1 = new Handsontable(container, conf);
}


// log("%o : %o",commentsPlugin,hot1)
// log输出
function log(s, arg) {
    if (console) {
        console.log.apply(console, arguments);
    } else {
        alert(s);
    }
}

资源下载:h-function.js
poi做的Handsontable通用导出的Servlet例子:handsontable_export_poi.zip

已有 2 条评论
  1. Ms.zhou

    哟西,虽然看不懂感觉楼主还是蛮厉害的。

    Ms.zhou
  2. Pharmb409

    Hello!

    Pharmb409