excel导入到html和从html导出文件到excel

公司最近需求。所以做了一个。下面是一些可运行的代码

html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>WYExcel</title>
<link rel="shortcut icon"href="images/biao.ico">
<link rel="stylesheet" type="text/css" href="css/mycss.css"/>
<script src="http://oss.sheetjs.com/js-xlsx/xlsx.full.min.js"></script>
<script src="js/jquery-3.1.1.min.js"></script>
<script src="js/myIndex_1.js"></script>
<style>
#mybody{background-size:cover;width:100%; overflow:hidden}
</style>
</head>
<body id="mybody">
<div id="All">
<div id="redDiv"></div>


<!-- 中间主体-->
<div id="Icontent">
   <!--左侧栏-->
  <div id="iconleft">
   <div id="MyselsecButtom">
<br/><br/>


<span  style="width:5%; margin-top:80px;position:absolute;color:red" class="dog"><img style="width:100%;height:90%" src="images/dog.png" /><h3>&nbsp;旺年大旺</h3></span>
   </div>
  </div>
  
<!--右侧栏表-->
<div id="ExcelDiv" style="width:95%;float:left;">
  <br/>
   <!-- 文件上传栏-->
  <div style="background-color:#BEE7EA;border-radius:10px; width:100%;height:40px">
 
      <!-- 文件上传-->
    <div id="flieButtondiv" style="display:none; margin-left:10px"><span class="mybutton" style="margin-top:0px">导入其他</span></div>
  </div>
  
 
  
 
   <!-- 表头-->
   <div id="demoHead"></div>
   <div class="clearBoth"></div>
   <!--表身-->
   <div id="demo"></div>
   <input  id="DaoChuAll" type="button"  name="导出文件" value="导出整个文件" style="margin-left:5px; z-index:999"/><br/>
 
   </div>
</div>




<br />
<!--提示兰和文件上传-->
<div id="flieButtondiv1"><input type="file" onchange="importExcel(this)" class="fileButton1" /></div>
<div id="shousuo"><img   style="width:100%;height:100%"src="images/anniu.png" /></div>






</div>


</body>

</html>



js:// JavaScript Document


$(document).ready(function(e) {
 
var a;var myTishi=document.getElementById("myTishi");
var TiScr=function(){
a=myTishi.scrollLeft++
   if(a==myTishi.scrollLeft){
myTishi.scrollLeft=0;
}
}
setInterval(TiScr,40);
    $("#myTishi").mouseenter(function(){
$("#tishiLan").fadeIn();

})
$("#myTishi").mouseleave(function(){
$("#tishiLan").fadeOut();

})

$(".mysousuo").focus(function(){
 
 $(".mysousuo").val("");
})
    $(".mybutton").mouseenter(function(){
 $(this).css("background-color","#888")

})
$(".mybutton").mouseleave(function(){
 $(this).css("background-color","#999")

})
$(".mybutton").mousedown(function(){
 $(this).css({"width":"76px","height":"37px","background-color":"#F00"})

})
    $(".mybutton").mouseup(function(){
 $(this).css({"width":"80px","height":"40px","background-color":"#888"})

})

var mydate = new Date();
var mydatestr="当前时间:"+mydate.toLocaleDateString()
$("#ritou").html(mydatestr);




});


//文件操作:


{//大括号


var wb;var rABS = false;var excelnote;   
//导入//该方法是已定义的方法
function importExcel(obj) {
 
      if(!obj.files) {
            return;
        }

       const IMPORTFILE_MAXSIZE = 2*1024;//这里可以自定义控制导入文件大小
       var suffix = obj.files[0].name.split(".")[1]
  
      if(suffix != 'xls' && suffix !='xlsx'){
            alert('导入的文件格式不正确!')
            return
        }
      if(obj.files[0].size/1024 > IMPORTFILE_MAXSIZE){
            alert('导入的表格文件不能大于2M')
            return
        }

        var f = obj.files[0];
        var reader = new FileReader();
      reader.onload = function(e) {
            var data = e.target.result;
            if(rABS) {
                wb = XLSX.read(btoa(fixdata(data)), {//手动转化
                    type: 'base64'
                });
            } else {
                wb = XLSX.read(data, {
                    type: 'binary'
                });
            }
   excelnote=JSON.stringify( XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]) );

myaction();
 
          };// reader.onload闭合
        if(rABS) {
            reader.readAsArrayBuffer(f);
        } else {
            reader.readAsBinaryString(f);
        }
 }//importExcel闭合 文件加载完毕




//操作Ecxel中文件。
var myneed;
var arra=[];
var lie;var hang;
var myneedstr;
var arrh;
var needReTurnArrb;
var myaction=function(){
      XianAndYin();
  myneed=excelnote; //初始json数据
  
  myneedstr=getMyNeedStr(myneed);//获取去掉#并合成号码的json格式字符串
 
  lie=getLie(myneedstr);//列
  hang=getHang(myneedstr);//行 
 
  arra=getArra(myneedstr);//获取"  "  "的角标 
  
  loadHead(lie);//设置表头格数
  
  arrh=setDivhtmlHead(myneedstr,arra); //将数据写入表头
  
  loadExcelBody(lie,hang);//设置表身的列数和行数。
 
  arrb=getArrb(arra,myneedstr);//获取表身内容 并转成字符数组;

  setDivHtml(arrb);//回写表身数据到表身中


  //导出全部:
  daoChuAll(myneedstr);
  
  //筛选部分 
 needReTurnArrb=Shaixuanbufen(hang,arrb);
    //收缩栏
 shousuo();

 
 
}//action
var getMyNeedStr=function(myneed){
var myneedstr=myneed;
   /*
for(var i=0;i<myneedstr.length;i++) {
         myneedstr= myneedstr.replace("\",\"编号ID\":\"N.","");
myneedstr= myneedstr.replace("#.","1");
myneedstr= myneedstr.replace("#","手机号码");
}
*/

 myneedstr= myneedstr.replace(/\",\"编号ID\":\"N./g,"");//替换全部
 
 myneedstr= myneedstr.replace(/#./g,"1");//好像不识别  .
 
 myneedstr= myneedstr.replace(/1:/g,"手机号码\":");//接下继续转

return myneedstr;
}




//获取arra;并返回  
var getArra=function(myneedstr){//遍历字符串
//此数组收集的是"出现的角标
var count=0;
for(var i=0;i<myneedstr.length;i++)
{    if(myneedstr.charAt(i)=="\""){
arra[count]=i;
count++;
}
 
}
 
return arra;
}
//获取myneedstr中{}之间的","来判断列数。一个","表示两列,所以初始给出1列。
var getLie=function(myneedstr){
var lie=1;var a;var b;
for(var i=0;i<myneedstr.length;i++){
  a=myneedstr.indexOf("{");
  b=myneedstr.indexOf("}")
break;
}
for(var i=a;i<=b;i++){
  if(myneedstr[i]==","){lie++;}
 
}

return lie;
}
//获取行数;
var getHang=function(myneedstr){
var Hang=0;
for(var i=0;i<myneedstr.length;i++){
  if(myneedstr[i]=="{"){
    Hang++;
  }

}
return Hang;
}






//获取arrb
var getArrb=function(arra,myneedstr){
 var arrb=[];//we need
 var count1=0;
         
 for(var i=0;i<arra.length;i++){

    if((i-2)%4==0)


      arrb[count1]=myneedstr.substring(parseInt(arra[i])+1,parseInt(arra[i+1]));
  count1++;
}
 }
 

    return arrb;  
}
//重写行数和列数的div


var loadHead=function(lie){
var Htmldemohead="";
for(var i=1;i<=lie;i++){
Htmldemohead=Htmldemohead+"<div class='HeadTit Head'"+i+"></div>";
}
$("#demoHead").html(Htmldemohead);
$(".HeadTit").css("width", (parseInt($("#demo").css("width"))-(2*lie+9))/lie);
}
//写入exceldiv
var loadExcelBody=function(lie,hang){

var Htmldemo=""
var HtmlexcContent="";
for(var i=1;i<=lie;i++){
 Htmldemo=Htmldemo+"<div class='ContentExc one'"+i+"></div>";
}
for(var i=1;i<=hang;i++){
   HtmlexcContent=HtmlexcContent+Htmldemo;
 
}
 
$("#demo").html(HtmlexcContent);
$(".ContentExc").css("width", (parseInt($("#demo").css("width"))-(2*lie+9))/lie);

}








//回写数据到表头
 var setDivhtmlHead=function(myneedstr,arra){
 var arrh=[];
 var counth=0;
 for(var i=0;i<=4*(lie-1);i++)//$*9=36;但是角标从0开始所以是4*8=32
    {
   if(i%4==0)
   {
arrh[counth]=myneedstr.substring(parseInt(arra[i])+1,parseInt(arra[i+1]));
counth++;

 if(counth==lie){break;}
}  
 }

for(var i=0;i<lie;i++)
{
document.getElementsByClassName("HeadTit").item(i).innerHTML=arrh[i];
    }
return arrh; 
}


//回写数据到表中
var setDivHtml=function(arrb){


 for(var i=0;i<arrb.length;i++){
  
document.getElementsByClassName("ContentExc").item(i).innerHTML=arrb[i];

   }
}




//导入文件后隐藏欢迎字段和显示统计
var XianAndYin=function(){
  
  $(".mystatistics").fadeIn(2000);
  $("#Icontent").fadeIn();
 
  $("#flieButtondiv").fadeIn();
  $("#flieButtondiv1").fadeOut();
  $("#redDiv").fadeIn();
  $("#shousuo").fadeIn();
}




     


//导出所有
var daoChuAll=function(myneedstr){
var data=myneedstr;
$("#DaoChuAll").click(function(){
alert()
           if(data == '')
              return;
           JSONToCSVConvertor(data,true);  
})
 
   
}


//导出的函数
var  JSONToCSVConvertor=function(JSONData, ShowLabel){
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData; 
    var CSV = '';    
    if (ShowLabel) {
        var row = "";
        for (var index in arrData[0]) {
            row += index + ',';
        }


        row = row.slice(0, -1);
        CSV += row + '\r\n';
    }
    for (var i = 0; i < arrData.length; i++) {
        var row = "";
        for (var index in arrData[i]) {
            row += '"' + arrData[i][index] + '",';
        }


        row.slice(0, row.length - 1);
        CSV += row + '\r\n';
    }


    if (CSV == '') {        
        alert("Invalid data");
        return;
    }   
    var fileName = "MyReport_";
    fileName += "G"
    var uri = 'data:text/csv;charset=utf-8,' + encodeURI(CSV);//编码
    var link = document.createElement("a");    
    link.href = uri;
    link.style = "visibility:hidden";
    link.download = fileName + ".csv";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

}




}//大括号



css:

@charset "utf-8";
/* CSS Document */
#mainHead{height:80px;width:100%; background-color:#79C3E3;box-shadow: 2px 2px 30px #bbb;border-radius:10px;}
#demoHead{ margin-left:2.5%;width:95%;height:50px;}
 .HeadTit{height:60px;float:left;background-color:#EDEDED; border-width:1px; border-style:solid; text-align:center; font-size:24px; line-height:68px}
 .clearBoth{clear:both}
#demo{ margin-left:2.5%;width:95%;height:500px;overflow:auto;}
 .ContentExc{height:50px;float:left;background-color:#FFF; border-width:1px; border-style:solid; text-align:center;}  
::-webkit-scrollbar   
{     width: 9px;   
     background-color: #F5F5F5;   
}  
::-webkit-scrollbar-thumb   
{   
    border-radius:9px;   
    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3);   
    background-color:#666;   
}    
  #myTishi{width:300px;white-space:nowrap;overflow:hidden;}
 #myTishispan{text-align:center}
 #mystaspan1{ border-width:1px;box-shadow: 2px 2px 30px #bbb; background-color:#CCC}
 #mywelcome{position:fixed;text-align:center;width:1500px;color:#FC6;font-size:50px; top:600px}
 #otherExcelLie{display:none; background-color:#CCC;border-radius:10px; width:104px; border-width:1px; border-style:solid;position:relative;margin-top:-20px}
.mybutton{ background-color:#999;width:80px;height:40px; position:absolute;font-size:18px; text-align:center; line-height:40px; margin-top:20px;margin-left:6px; border-radius:10px}


#flieButtondiv1{
display: inline-block;
position:absolute;
top:660px;
left:810px;
padding: 3px 5px;
overflow: hidden;
color:#FFF;
background-color:#CCC;
}
#fileButton1{
position: absolute;
width: 100%;
height: 100%;
top: 0;
    left:450px;
    outline: none;
    background-color: transparent;
    filter:alpha(opacity=0);
-moz-opacity:0;
-khtml-opacity: 0;
opacity: 0;
}
#RiLi{width:400px;height:170px; background-color:#CCC; border-width:10px; border-color:#FC9;position:fixed;left:1300px;top:620px; border-radius:10px; display:none;}
#ritou{ margin-top:20px;font-size:16px;}
#redDiv{width:100%;height:20px; background-color:red; display:none}
#Icontent{position:absolute;width:100%;display:none}
#iconleft{width:5%;float:left;height:900px; background-color:#79C3E3}
#shousuo{height:200px;width:20px; position:absolute;top:450px;left:5%; display:none}


ps:里面很多代码是不需要的,大伙自己去删掉吧

猜你喜欢

转载自blog.csdn.net/Chou_Junn/article/details/80169513