html table 粘贴 excel

   $('table').bind('paste', function (e) {
                //消除默认粘贴
                if (document.all)   //判断IE浏览器
                    window.event.returnValue = false;
                else event.preventDefault();
                //获取粘贴板数据
                var data = null;
                var clipboardData = window.clipboardData || e.originalEvent.clipboardData; // IE || chrome  
                data = clipboardData.getData('Text');
                console.log(data.replace(/\t/g, '\\t').replace(/\n/g, '\\n')); //data转码
                //解析数据
                var arr = data.split('\n')
        .filter(function (item) {    //兼容Excel行末\n,防止出现多余空行
            return (item !== "")
        }).map(function (item) {
            return item.split("\t");
        });
                //输出至网页表格
                var tab = this;  //表格DOM
                var td = $(e.target).parents('td');
                var startRow = td.parents('tr')[0].rowIndex;
                var startCell = td[0].cellIndex;
                var rows = tab.rows.length;  //总行数
                for (var i = 0; i < arr.length && startRow + i < rows; i++) {
                    var cells = tab.rows[startRow + i].cells.length;  //该行总列数
                    for (var j = 0; j < arr[i].length && startCell + j < cells; j++) {
                        var cell = tab.rows[startRow + i].cells[startCell + j];
                        $(cell).find(':text').val(arr[i][j]);  //找到cell下的input:text,设置value
                    }
                }
            });

你可能感兴趣的:(JQUERY)