(纯前台)读取、解析并展示xls/xlsx

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lixin2151408/article/details/71411828

写一个当时让我弄了好几天的东西吧..

纯前台读取、解析Excel 表格,并展示在页面上的一个插件。(需要自行修改代码)。


地址是:


我通过修改了一些代码后,展示如图:



话不多说..我把他的代码拿上来


fn.loadexcel = function(){
var that = this;
var url = that.appPath + "Loadzjzl";
$.ajax({
type : 'get',
url : url,
dataType : "json",
success : function(data) {
if (data != null) {
$("#duoCXJG").val(data.jgmc);
$("#duoGZZBH").val(data.gzzh);
$("#duoGWZBH").val(data.gwzh);
$("#duoCXRXM").val(data.username);
$("#duoSPID").val(data.spid);
}
},
error : function(data) {
alert("err");
}
})
var X = XLSX;
var XW = {
/* worker message */
msg: 'xlsx',
/* worker scripts */
rABS: '/sharesearch/resources/assets/js/xlsx/xlsxworker2.js',
norABS: '/sharesearch/resources/assets/js/xlsx/xlsxworker1.js',
noxfer: '/sharesearch/resources/assets/js/xlsx/xlsxworker.js'
};


var rABS = typeof FileReader !== "undefined" && typeof FileReader.prototype !== "undefined" && typeof FileReader.prototype.readAsBinaryString !== "undefined";
if(!rABS) {
document.getElementsByName("userabs")[0].disabled = true;
document.getElementsByName("userabs")[0].checked = false;
}


var use_worker = typeof Worker !== 'undefined';
if(!use_worker) {
document.getElementsByName("useworker")[0].disabled = true;
document.getElementsByName("useworker")[0].checked = false;
}


var transferable = use_worker;
if(!transferable) {
document.getElementsByName("xferable")[0].disabled = true;
document.getElementsByName("xferable")[0].checked = false;
}


var wtf_mode = false;


function fixdata(data) {
var o = "", l = 0, w = 10240;
for(; l<data.byteLength/w; ++l) o+=String.fromCharCode.apply(null,new Uint8Array(data.slice(l*w,l*w+w)));
o+=String.fromCharCode.apply(null, new Uint8Array(data.slice(l*w)));
return o;
}


function ab2str(data) {
var o = "", l = 0, w = 10240;
for(; l<data.byteLength/w; ++l) o+=String.fromCharCode.apply(null,new Uint16Array(data.slice(l*w,l*w+w)));
o+=String.fromCharCode.apply(null, new Uint16Array(data.slice(l*w)));
return o;
}


function s2ab(s) {
var b = new ArrayBuffer(s.length*2), v = new Uint16Array(b);
for (var i=0; i != s.length; ++i) v[i] = s.charCodeAt(i);
return [v, b];
}


function xw_noxfer(data, cb) {
var worker = new Worker(XW.noxfer);
worker.onmessage = function(e) {
switch(e.data.t) {
case 'ready': break;
case 'e': console.error(e.data.d); break;
case XW.msg: cb(JSON.parse(e.data.d)); break;
}
};
var arr = rABS ? data : btoa(fixdata(data));
worker.postMessage({d:arr,b:rABS});
}


function xw_xfer(data, cb) {
var worker = new Worker(rABS ? XW.rABS : XW.norABS);
worker.onmessage = function(e) {
switch(e.data.t) {
case 'ready': break;
case 'e': console.error(e.data.d); break;
default: xx=ab2str(e.data).replace(/\n/g,"\\n").replace(/\r/g,"\\r"); console.log("done"); cb(JSON.parse(xx)); break;
}
};
if(rABS) {
var val = s2ab(data);
worker.postMessage(val[1], [val[1]]);
} else {
worker.postMessage(data, [data]);
}
}


function xw(data, cb) {
transferable = document.getElementsByName("xferable")[0].checked;
if(transferable) xw_xfer(data, cb);
else xw_noxfer(data, cb);
}


function get_radio_value( radioName ) {
var radios = document.getElementsByName( radioName );
for( var i = 0; i < radios.length; i++ ) {
if( radios[i].checked || radios.length === 1 ) {
return radios[i].value;
}
}
}


function to_json(workbook) {
var result = {};
workbook.SheetNames.forEach(function(sheetName) {
var roa = X.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
if(roa.length > 0){
result[sheetName] = roa;
}
});
return result;
}


function to_csv(workbook) {
var result = [];
workbook.SheetNames.forEach(function(sheetName) {
var csv = X.utils.sheet_to_csv(workbook.Sheets[sheetName]);
if(csv.length > 0){
result.push("");
result.push(csv);
var excelarr = csv.split(",");
}
});
return result;
}


function to_formulae(workbook) {
var result = [];
workbook.SheetNames.forEach(function(sheetName) {
var formulae = X.utils.get_formulae(workbook.Sheets[sheetName]);
if(formulae.length > 0){
result.push("SHEET: " + sheetName);
result.push("");
result.push(formulae.join("\n"));
}
});
return result.join("\n");
}


var tarea = document.getElementById('b64data');
function b64it() {
if(typeof console !== 'undefined') console.log("onload", new Date());
var wb = X.read(tarea.value, {type: 'base64',WTF:wtf_mode});
process_wb(wb);
}


function process_wb(wb) {
var output = "";
switch(get_radio_value("format")) {
case "json":
output = JSON.stringify(to_json(wb), 2, 2);
break;
case "form":
output = to_formulae(wb);
break;
default:
output = to_csv(wb);
}
var excelarr = output[1].split(",");
var j = Math.ceil(excelarr.length/6);
if(out.innerText === undefined) out.textContent = output;
else{
var k=1;
$("#duocxresult").css("display","block");
$(".excelbody").empty();
for(var i = 1;i<j-1;i++){
if(excelarr[6*i].substring(1,excelarr[6*i].length)!==""||excelarr[6*i+1]!==""||excelarr[6*i+2]!==""||excelarr[6*i+3]!==""||excelarr[6*i+4]!==""||excelarr[6*i+5]!=="")
{$(".excelbody").append("<tr class='duoCXTR' duospid='' duoresultxml=''><td>"+k+"</td><td class='duoBCXRXM'>"+excelarr[6*i].substring(1,excelarr[6*i].length)+"</td><td class='duoZJZL'>"+excelarr[6*i+1]+"</td><td class='duoZJHM'>"+excelarr[6*i+2]+"</td><td class='duoQZHZMH'>"+excelarr[6*i+3]+"</td><td class='duoZL'>"+excelarr[6*i+4]+"</td><td class='duoFCID'>"+excelarr[6*i+5]+"</td><td><a class='duoRESULTCOUNT'></a></td></tr>")
k++}
}


}
if(typeof console !== 'undefined') console.log("output", new Date());
}


var drop = document.getElementById('drop');
function handleDrop(e) {
e.stopPropagation();
e.preventDefault();
rABS = document.getElementsByName("userabs")[0].checked;
use_worker = document.getElementsByName("useworker")[0].checked;
var files = e.dataTransfer.files;
var f = files[0];
{
var reader = new FileReader();
var name = f.name;
reader.onload = function(e) {
if(typeof console !== 'undefined') console.log("onload", new Date(), rABS, use_worker);
var data = e.target.result;
if(use_worker) {
xw(data, process_wb);
} else {
var wb;
if(rABS) {
wb = X.read(data, {type: 'binary'});
} else {
var arr = fixdata(data);
wb = X.read(btoa(arr), {type: 'base64'});
}
process_wb(wb);
}
};
if(rABS) reader.readAsBinaryString(f);
else reader.readAsArrayBuffer(f);
}
}


function handleDragover(e) {
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
}


if(drop.addEventListener) {
drop.addEventListener('dragenter', handleDragover, false);
drop.addEventListener('dragover', handleDragover, false);
drop.addEventListener('drop', handleDrop, false);
}




var xlf = document.getElementById('xlf');
var newxlf =document.getElementById('xlf');
//判断是否是excel文件:
$('input[id=xlf]').change(function() {
var value = $(this).val();
var value1 = value.split("\\");
var i = value1.length;
var value2 = value1[i-1];
var value3 = value2.split(".");
var j = value3.length;
var value4 = value3[j-1];
if(value4!=="xls"&&value4!="xlsx"){
alert("请选择excel文件")
return;
}
else{
$('#excelCover').val(value2);
}
});

function handleFile(e) {
rABS = document.getElementsByName("userabs")[0].checked;
use_worker = document.getElementsByName("useworker")[0].checked;
var files = e.target.files;
var f = files[0];
{
var reader = new FileReader();
var name = f.name;
reader.onload = function(e) {
if(typeof console !== 'undefined') console.log("onload", new Date(), rABS, use_worker);
var data = e.target.result;
if(use_worker) {
xw(data, process_wb);
} else {
var wb;
if(rABS) {
wb = X.read(data, {type: 'binary'});
} else {
var arr = fixdata(data);
wb = X.read(btoa(arr), {type: 'base64'});
}
process_wb(wb);
}
};
if(rABS) reader.readAsBinaryString(f);
else reader.readAsArrayBuffer(f);
}
}


if(newxlf.addEventListener) newxlf.addEventListener('change', handleFile, false);
}

fn.duosearchinfo = function(){
var that = this;
var duoSPID="";
$("#duosearch").on('click',function(){
var index = layer.load(0, {
shade: [0.4,'#fff'] //0.1透明度的白色背景
})
var url = that.appPath + "Searchinfo";
var duoRESULTCOUNT=0;
$(".duoCXTR").each(function(){
var thisTR = this;
var duoCXJG = $("#duoCXJG").val();
var duoGZZBH = $("#duoGZZBH").val();
var duoGWZBH = $("#duoGWZBH").val();
var duoCXRXM = $("#duoCXRXM").val();
var duoBCXRXM = $(this).children('td').eq(1).html();
var duoZJZL = $(this).children('td').eq(2).html();
var duoZJH = $(this).children('td').eq(3).html();
var duoQZHZMH = $(this).children('td').eq(4).html();
var duoZL = $(this).children('td').eq(5).html();
var duoFCID = $(this).children('td').eq(6).html();

var infos = {};
infos = {
bcxrxm : duoBCXRXM,
zjzl : duoZJZL,
zjhm : duoZJH,
qzhzmh : duoQZHZMH,
zl : duoZL,
fcid : duoFCID,
cxjg : duoCXJG,
cxrxm : duoCXRXM,
gzzbh : duoGZZBH,
gwzbh : duoGWZBH
// szfj:$('#szfj').val(),
// spid:$('#spid').val()
};
$.ajax({
type : 'post',
url : url,
async : true,
dataType : "json",
data : infos,
beforeSend:function(){

},
success:function(data){
duoRESULTCOUNT=parseInt(data.Resultcount);
$(thisTR).children("td").eq(7).children('a').html(duoRESULTCOUNT)
$(".duoRESULTCOUNT").hover(function(){
$(this).css({"cursor":"pointer"});
})
$(thisTR).attr("duospid",data.spid);
}
})
})
layer.close(index);
})
}
fn.openduodetail = function(){
var that = this;
$("#out").off('click').on('click','.duoRESULTCOUNT',function(){
var spid = $(this).parent().parent().attr("duospid");
var resultxml="";
$.when($.get(that.appPath+"detalis/xcxq/"+spid)).done(function(data){
var urls=that.appPath+"search/edtidy/cxsp";
var width = $(top.document).width() * 0.9;
var height = $(top.document).height() * 0.85;
top.layer.open({
 type: 1,
 title:'查询详情',
 shadeClose : true,
 shade : 0.6,
 zIndex : 1000000, // 重点1
 maxmin : true, // 开启最大化最小化按钮
 area : [ width + 'px', height + 'px' ], // 宽高
 content: "<iframe src ='" + urls+'?spid='+spid+"&lx=wdcx&id="+spid+"&resultxml="+data
+ "' width='100%' height='100%' frameborder='0'></iframe>"
});
});
})
$("#out").on('dblclick','.duoCXTR',function(){
$(this).children("td").eq(7).children('a').click()
})
}



这里主要修改的代码是:

var excelarr = output[1].split(",");
var j = Math.ceil(excelarr.length/6);
if(out.innerText === undefined) out.textContent = output;
else{
var k=1;
$("#duocxresult").css("display","block");
$(".excelbody").empty();
for(var i = 1;i<j-1;i++){
if(excelarr[6*i].substring(1,excelarr[6*i].length)!==""||excelarr[6*i+1]!==""||excelarr[6*i+2]!==""||excelarr[6*i+3]!==""||excelarr[6*i+4]!==""||excelarr[6*i+5]!=="")
{$(".excelbody").append("<tr class='duoCXTR' duospid='' duoresultxml=''><td>"+k+"</td><td class='duoBCXRXM'>"+excelarr[6*i].substring(1,excelarr[6*i].length)+"</td><td class='duoZJZL'>"+excelarr[6*i+1]+"</td><td class='duoZJHM'>"+excelarr[6*i+2]+"</td><td class='duoQZHZMH'>"+excelarr[6*i+3]+"</td><td class='duoZL'>"+excelarr[6*i+4]+"</td><td class='duoFCID'>"+excelarr[6*i+5]+"</td><td><a class='duoRESULTCOUNT'></a></td></tr>")
k++}
}

我是通过console.log(output),发现了规律,从而对output进行修改,将其改成我需要的格式,然后动态添加进table中。

大部分内容我是一点都没动,(因为我看不懂)。不过还好我会用脑子...感觉现在写代码全靠脑子啊,因为基础不够。

我忘记了output的形式了...后面会补上

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页