1. 程式人生 > >excel匯入到html和從html匯出檔案到excel

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:裡面很多程式碼是不需要的,大夥自己去刪掉吧