javascript匯出excel檔案例子

來源:互聯網
上載者:User

方法一,測試過所有ie核心瀏覽器都可用

 代碼如下 複製代碼

// JavaScript Document
//調用方法
//   var test=new PageToExcel("data",0,255,"測試.xls");//table id , 第幾行開始,最後一行顏色 ,儲存的檔案名稱
//   test.CreateExcel(false);
//   test.Exec();
//   test.SaveAs();
//   test.CloseExcel();
//LastRowColor 0黑色 255紅色
//

function PageToExcel(TableID,FirstRow,LastRowColor,SaveAsName){
this.lastRowColor=LastRowColor==""?0:LastRowColor;
var today=new Date();
this.saveAsName=(SaveAsName==""?today.getYear()+"年"+(today.getMonth()+1)+"月"+today.getDate()+"日.xls":SaveAsName);
this.tableId=TableID;
this.table=document.getElementById(this.tableId);//匯出的table 對象
this.rows=this.table.rows.length;//匯出的table總行數
this.colSumCols=this.table.rows(0).cells.length;//第一行總列數
this.fromrow=FirstRow;
this.beginCol=0; //起始列數
this.cols=this.colSumCols;
this.oXL=null;
this.oWB=null;
this.oSheet=null;
this.rowSpans=1; //行合并
    this.colSpans=1; //列合并
    this.colsName={0:"A",1:"B", 2:"C", 3:"D", 4:"E", 5:"F", 6:"G", 7:"H", 8:"I",9:"J", 10:"K", 11:"L", 12:"M", 13:"N", 14:"O", 15:"P", 16:"Q", 16:"R" ,18:"S", 19:"T", 20:"U", 21:"V", 22:"W", 23:"X", 24:"Y", 25:"Z"};
}
PageToExcel.prototype.DeleteExcelCols=function(NotShowColList){//數組NotShowColList
    //this.notShowColList=NotShowColList;//不顯示列集合,1,2,3,1
    //刪除excel中的列
   var m=0;
   for(var i=0;i<NotShowColList.length;i++){
         if(i>0){
            m++;
         }
        var temp=NotShowColList[i]- m;
        var index=this.colsName[temp];
   this.oSheet.Columns(index).Delete;//刪除
   }
   m=0;
}


PageToExcel.prototype.CreateExcel=function(ExcelVisible)
{
   try{
   this.oXL = new ActiveXObject("Excel.Application"); //建立應該對象
   this.oXL.Visible = ExcelVisible;
   this.oWB = this.oXL .Workbooks.Add();//建立一個Excel活頁簿
    this.oSheet = this.oWB.ActiveSheet;//指定要寫入內容的工作表為使用中工作表
   //不顯示網格線
   this.oXL.ActiveWindow.DisplayGridlines=false;
   }catch(e){
    alert("請確認安裝了非綠色版本的excel!"+e.description);
    CloseExcel();
   }
}

PageToExcel.prototype.CloseExcel=function()
{
    this.oXL.DisplayAlerts = false;  
            this.oXL.Quit();  
            this.oXL = null;  
            this.oWB=null;  
            this.oSheet=null;
}

PageToExcel.prototype.ChangeElementToLabel=function (ElementObj){
   var GetText="";
   try{
   var childres=ElementObj.childNodes;

   }catch(e){ return GetText}
   if(childres.length<=0) return GetText;
   for(var i=0;i<childres.length;i++){
   try{if(childres[i].style.display=="none"||childres[i].type.toLowerCase()=="hidden"){continue;}}
   catch(e){}

     try{
      switch (childres[i].nodeName.toLowerCase()){
        case "#text" :
         GetText +=childres[i].nodeValue ;
         break;
        case "br" :
         GetText +="n";
         break;
        case "img" :
         GetText +="";
         break;
        case "select" :
         GetText +=childres[i].options[childres[i].selectedIndex].innerText ;
         break;
        case "input" :
         if(childres[i].type.toLowerCase()=="submit"||childres[i].type.toLowerCase()=="button"){
          GetText +="";
         }else if(childres[i].type.toLowerCase()=="textarea"){
          GetText +=childres[i].innerText;
         }else{
          GetText +=childres[i].value;
         }
         break;
        default :
         GetText += this.ChangeElementToLabel(childres[i]);
         break;
      }

     }catch(e){}
   }
   return GetText;
}
PageToExcel.prototype.SaveAs=function (){
   //儲存
   try{
    this.oXL.Visible =true;
    var fname = this.oXL.Application.GetSaveAsFilename(this.saveAsName, "Excel Spreadsheets (*.xls), *.xls");
    if(fname){
    this.oWB.SaveAs(fname);
     this.oXL.Visible =false;
    }
   }catch(e){};
}
PageToExcel.prototype.Exec=function()
{

   //尋找列數,考慮到第一行可能存在
   for (var i=0; i<this.colSumCols;i++) {
    var tmpcolspan = this.table.rows(0).cells(i).colSpan;
    if ( tmpcolspan>1 ) {
     this.cols += tmpcolspan-1;
    }
   }

   //定義2維容器資料,1:行;2:列;值(0 可以填充,1 已被填充)
   var container=new Array(this.rows);
   for (var i=0;i<this.rows;i++) {
    container[i]=new Array(this.cols);
    for (j=0;j<this.cols;j++) {
     container[i][j]=0;
    }
   }

   //將所有單元置為文本,避免非數字列被自動變成科學計數法和丟失首碼的0
   this.oSheet.Range(this.oSheet.Cells(this.fromrow+1,1), this.oSheet.Cells(this.fromrow+this.rows,this.cols)).NumberFormat = "@";
   // 迴圈行
   for (i=0;i<this.rows;i++){
    //迴圈列
    for (j=0;j<this.cols;j++){
     //尋找開始列
     for (k=j;k<this.cols;k++){
      if (container[i][k]==0) {
       this.beginCol=k;
       k=this.cols; //退出迴圈
      }
     }
//try{
      //賦值
      //此處相應跟改 根據 標籤的類型,替換相關參數
      this.oSheet.Cells(i+1+this.fromrow,this.beginCol+1).value = this.ChangeElementToLabel(this.table.rows(i).cells(j));


      //計算合并列
      try{
     this.colSpans = this.table.rows(i).cells(j).colSpan;
      }catch(e){
     this.colSpans=0  
     }
     if (this.colSpans>1) {
      //合并
      this.oSheet.Range(this.oSheet.Cells(i+1+this.fromrow,this.beginCol+1),this.oSheet.Cells(i+1+this.fromrow,this.beginCol+this.colSpans)).Merge();
     }
     //將當前table位置填寫到對應的容器中
     for (k=0; k<this.colSpans;k++) {
      container[i][this.beginCol+k]= 1;
     }
     // 計算合并行

     try{
      this.rowSpans = this.table.rows(i).cells(j).rowSpan;
       }catch(e){
       this.rowSpans = 0;
     }

     if (this.rowSpans>1) { //行合并
      this.oSheet.Range(this.oSheet.Cells(i+1+this.fromrow,this.beginCol+1),this.oSheet.Cells(i+this.rowSpans+this.fromrow,this.beginCol+this.colSpans)).Merge();
      //將當前table位置填寫到對應的容器中
      for (k=1; k<this.rowSpans;k++) { //由於第0行已經被colSpans對應的代碼填充了,故這裡從第1行開始
       for (l=0;l<this.colSpans;l++) {
        container[i+k][this.beginCol+l]=1;
       }
      }
     }
     //如果開始列+合并列已經等於列數了,故不需要再迴圈html table
     if (this.beginCol+this.colSpans>=this.cols) j=this.cols;

    }
    if(i==0)
    {
     //標題列
     this.oSheet.Range(this.oSheet.Cells(1,1), this.oSheet.Cells(1,1)).Font.Size=20;
     this.oSheet.Range(this.oSheet.Cells(1,1), this.oSheet.Cells(1,1)).Font.Bold = true;
     this.oSheet.Range(this.oSheet.Cells(1,1), this.oSheet.Cells(1,1)).HorizontalAlignment = -4108; //置中
     this.oSheet.Range(this.oSheet.Cells(1,1), this.oSheet.Cells(1,1)).Rows.RowHeight = 40;
    }
     //自動調整行高
   }


   //最後一行是否空色
   try{
    this.oSheet.Range(this.oSheet.Cells(this.rows,1), this.oSheet.Cells(this.rows,1)).Font.Color=this.lastRowColor;
   }catch(e){}
   this.oSheet.Range(this.oSheet.Cells(this.fromrow+2,1), this.oSheet.Cells(this.fromrow+this.rows,this.cols)).Rows.RowHeight=20;
   this.oSheet.Range(this.oSheet.Cells(this.fromrow+2,1), this.oSheet.Cells(this.fromrow+this.rows,this.cols)).Font.Size=10;
   //自動換行
   this.oSheet.Range(this.oSheet.Cells(this.fromrow+2,1), this.oSheet.Cells(this.fromrow+this.rows,this.cols)).WrapText = true;
   //自動調整列寬
   this.oSheet.Range(this.oSheet.Cells(this.fromrow+1,1), this.oSheet.Cells(this.fromrow+this.rows,this.cols)).Columns.AutoFit();
   //點虛線
   this.oSheet.Range(this.oSheet.Cells(this.fromrow+1,1), this.oSheet.Cells(this.fromrow+this.rows,this.cols)).Borders.LineStyle = -4118;


   return this.rows;
}

方法二,同樣支援所有ie核心瀏覽器

 建立一個exportPrint.html頁面,裡面的代碼如下所示,就可以實現匯出到Excel和列印網頁。

 代碼如下 複製代碼

<html>
 <head>
  <title>IE瀏覽器使用JS技術匯出到Excel和列印</title>
  <style>
   .table_stat {
    border-right:0px;
    border-bottom:0px;
    border-left:1px solid #819BD8;
    border-top:1px solid #819BD8;
   }
   .td_stat {
    border-right:1px solid #819BD8;
    border-bottom:1px solid #819BD8;
   }
  </style>
 </head>
 <body>
  <object classid="CLSID:8856F961-340A-11DO-A96B-00C04FD705A2" height="0" id="WebBrowser" width="0"></object>
  <table width="100%" align="center" border="0" cellpadding="0" cellspacing="0" style="text-align: center;" class="table_stat">
   <tr>
    <td id="title" align="center" nowrap="nowrap" class="td_stat" colspan="2">
     使用者資訊
    </td>
   </tr>
   <tr>
    <td id="title" align="center" nowrap="nowrap" class="td_stat" colspan="1">
     姓名
    </td>
    <td id="title" align="center" nowrap="nowrap" class="td_stat" colspan="1">
     張三
    </td>
   </tr>
   
   <tr>
    <td id="title" align="center" nowrap="nowrap" class="td_stat" colspan="2">
     <input type="button" id="export" value="匯出" onclick="javascript:exportToExcel();" >
     <input type="button" id="print" value="列印" onclick="javascript:print();" >
    </td>
   </tr>
  </table>
 </body>
</html>

<script type="text/javaScript">
 //匯出到Excel
 function exportToExcel() {
  if(document.getElementById("title")) {
   try {
    var oRangeRef = document.body.createTextRange();
    oRangeRef.execCommand("Copy");
    var appExcel = new ActiveXObject("Excel.Application");
    appExcel.visible = true;
    appExcel.Workbooks.Add().WorkSheets.Item(1).Paste();
   } catch(e) {
    alert("出錯啦!可能是瀏覽器或者是資料量太大咯哦!");
    return;
   }
   appExcel = null;
   oRangeRef = null;
  }
 }
 
 //列印
 function print() {
  if(document.getElementById("title")) {
   var export = document.getElementById("export");
   var print = document.getElementById("print");
   try {
    export.style.display = "none";
    print.style.display = "none";
    document.all.WebBrowser.ExecWB(6,1);
   } catch(e) {
    alert("出錯啦!可能是瀏覽器或者是資料量太大咯哦!");
    return;
   }
   export.style.display = "";
   print.style.display = "";
  }
 }
</script>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.