JavaScript Export Excel File example

Source: Internet
Author: User

Method One, tested all IE kernel browsers are available

The code is as follows Copy Code

JavaScript Document
Call method
var test=new pagetoexcel ("Data", 0,255, "test. xls");//table ID, line start, last line color, saved file name
Test. Createexcel (FALSE);
Test. Exec ();
Test. SaveAs ();
Test. Closeexcel ();
Lastrowcolor 0 Black 255 Red
//

function Pagetoexcel (tableid,firstrow,lastrowcolor,saveasname) {
this.lastrowcolor=lastrowcolor== ""? 0:lastrowcolor;
var today=new Date ();
This.saveasname= (saveasname== "" "" Today.getyear () + "year" + (Today.getmonth () +1) + "month" +today.getdate () + "day. xls": Saveasname);
This.tableid=tableid;
This.table=document.getelementbyid (This.tableid);//Exported Table object
this.rows=this.table.rows.length;//the number of table rows exported
This.colsumcols=this.table.rows (0). cells.length;//The total number of columns in the first row
This.fromrow=firstrow;
this.begincol=0; Number of starting columns
This.cols=this.colsumcols;
This.oxl=null;
This.owb=null;
This.osheet=null;
This.rowspans=1; Row merge
This.colspans=1; Column Merge
This.colsname={0: "A", 1: "B", 2: "C", 3: "D", 4: "E", 5: "F", 6: "G", 7: "H", 8: "I", 9: "J", "K", One: "L", One: "M", "N", "O", "P": "Q", "" R "," S "," T "," U "," V "," W "," X "," Y "," "Z"}; "
}
Pagetoexcel.prototype.deleteexcelcols=function (notshowcollist) {//array notshowcollist
this.notshowcollist=notshowcollist;//does not display the column collection, 1,2,3,1
Delete a column in 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;//Delete
}
m=0;
}


Pagetoexcel.prototype.createexcel=function (excelvisible)
{
try{
THIS.OXL = new ActiveXObject ("Excel.Application"); Create a should object
this.oXL.Visible = excelvisible;
THIS.OWB = This.oxl. Workbooks.Add ()//Create a new Excel workbook
This.osheet = this.owb.activesheet;//Specifies that the worksheet to be written to the content is the active worksheet
Do not show grid lines
This.oxl.activewindow.displaygridlines=false;
}catch (e) {
Alert ("Verify that the non-green version of the excel! is installed "+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 () {
Save
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 ()
{

Look for the number of columns, considering that the first row may exist
for (var i=0; i<this.colsumcols;i++) {
var tmpcolspan = this.table.rows (0). Cells (i). ColSpan;
if (tmpcolspan>1) {
This.cols + = tmpcolspan-1;
}
}

Defines 2-D container data, 1: Rows, 2: Columns, values (0 can be populated, 1 are filled)
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;
}
}

  //Convert all cells to text to avoid non-numeric columns being automatically turned into scientific notation and missing prefixes of 0
   This.oSheet.Range (This.oSheet.Cells ( this.fromrow+1,1), This.oSheet.Cells (This.fromrow+this.rows,this.cols)). NumberFormat = "@";
  //looping rows
   for (i=0;i<this.rows;i++) {
   //Looping columns
  & nbsp for (j=0;j<this.cols;j++) {
    //Find start column
     for (k=j;k< this.cols;k++) {
      if (container[i][k]==0) {
        This.begincol=k;
       k=this.cols;//Exit Loops
     }
     }
//try{
     //Assignment
     //Here corresponding to the type of label , replace the related parameter
      this.oSheet.Cells (i+1+this.fromrow,this.begincol+1). Value = this. Changeelementtolabel (This.table.rows (i). Cells (j));


     //Calculate merge Columns
      try{
     This.colspans = This.table.rows (i). Cells (j). ColSpan;
     }catch (e) {
     this.colspans=0  
     }
     if (this.colspans>1) {
     //merge
      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 ();
    }
    //fill in the current table position in the corresponding container
     for (k=0; k<this.colspans;k++) {
      container[i][this.begincol+k]= 1;
    }
    /Calculate merge rows

     try{
      This.rowspans = this.table.rows (i). Cells (j). RowSpan;
      }catch (e) {
       This.rowspans = 0;
    }

     if (this.rowspans>1) {//row merge
      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 ();
     //fill in the current table position in the corresponding container
      for (k=1 k< this.rowspans;k++) {//Since line No. 0 is already populated by the Colspans corresponding code, this is done from line 1th
       for (l=0;l< this.colspans;l++) {
        container[i+k][this.begincol+l]=1;
       }
     }
    }
     //If the Start column + merge column is already equal to the number of columns, there is no need to recycle the HTML table
     if (this.begincol+ This.colspans>=this.cols) J=this.cols;

}
if (i==0)
{
Title bar
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; Center
This.oSheet.Range (This.oSheet.Cells (1,1), This.oSheet.Cells (1,1)). Rows.rowheight = 40;
}
Auto Adjust Row height
}


Whether the last line is empty
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;
Wrap Line
This.oSheet.Range (This.oSheet.Cells (this.fromrow+2,1), This.oSheet.Cells (This.fromrow+this.rows,this.cols)). WrapText = true;
Automatically adjust column widths
This.oSheet.Range (This.oSheet.Cells (this.fromrow+1,1), This.oSheet.Cells (This.fromrow+this.rows,this.cols)). Columns.AutoFit ();
Dot Dash
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;
}

Method Two, also supports all IE kernel browsers

Create a new exportprint.html page with the code shown below to enable you to export to Excel and print your Web pages.

The code is as follows Copy Code

<title>ie Browser uses JS technology to export to Excel and print </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>
<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>
&LT;TD id= "title" align= "Center" nowrap= "nowrap" class= "Td_stat" colspan= "2" >
User Information
</td>
</tr>
<tr>
&LT;TD id= "title" align= "Center" nowrap= "nowrap" class= "Td_stat" colspan= "1" >
Name
</td>
&LT;TD id= "title" align= "Center" nowrap= "nowrap" class= "Td_stat" colspan= "1" >
Tom
</td>
</tr>

<tr>
&LT;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>

<script type= "Text/javascript" >
Export to 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 ("Wrong!") Maybe the browser or the amount of data is too big! ");
Return
}
Appexcel = null;
Orangeref = null;
}
}

Print
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 ("Wrong!") Maybe the browser or the amount of data is too big! ");
Return
}
Export.style.display = "";
Print.style.display = "";
}
}
</script>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.