JavaScript Export Excel Code

Source: Internet
Author: User

<meta http-equiv= "Content-type" content= "Text/html;charset=utf-8"/>
<title>web How to export a page to an Excel document </title>
<body>
<table id= "Tableexcel" width= "100%" border= "1" cellspacing= "0" cellpadding= "0" >
<tr>
&LT;TD colspan= "5" align= "Center" >web page Export to Excel document method </td>
</tr>
<tr>
<td> column Header 1</td>
<td> column Header 2</td>
<td> column Header 3</td>
<td> column Header 4</td>
<td> column Header 5</td>
</tr>
<tr>
<td>aaa</td>
<td>bbb</td>
<td>ccc</td>
<td>ddd</td>
<td>eee</td>
</tr>
<tr>
<td>AAA</td>
<td>BBB</td>
<td>CCC</td>
<td>DDD</td>
<td>EEE</td>
</tr>
<tr>
<td>FFF</td>
<td>GGG</td>
<td>HHH</td>
<td>III</td>
<td>JJJ</td>
</tr>
</table>
<input type= "button" onclick= "Javascript:method1 (' Tableexcel ');" Value= "First method import to Excel" >
<input type= "button" onclick= "Javascript:method2 (' Tableexcel ');" Value= "The second method imports into Excel" >
<input type= "button" onclick= "Javascript:getxlsfromtbl (' tableexcel ', null);" Value= "Third method import into Excel" >
<script language= "JavaScript" >

function Method1 (tableid) {//entire table copied to Excel
var curtbl = document.getelementbyidx_x_x (TableID);
var OXL = new ActiveXObject ("Excel.Application");
Create an Ax object Excel
var owb = OXL.Workbooks.Add ();
Get Workbook Object
var osheet = Owb.activesheet;
Activating the current sheet
var sel = Document.body.createTextRange ();
Sel.movetoelementtext (CURTBL);
Move the contents of the table into the TextRange
Sel.select ();
Select all the contents of TextRange
Sel.execcommand ("Copy");
Copy content in TextRange
Osheet.paste ();
Paste into active Excel
oXL.Visible = true;
Set Excel Visible Properties
}
function Method2 (tableid)//read each cell in the table into Excel
{
var curtbl = document.getelementbyidx_x_x (TableID);
var OXL = new ActiveXObject ("Excel.Application");
Create an Ax object Excel
var owb = OXL.Workbooks.Add ();
Get Workbook Object
var osheet = Owb.activesheet;
Activating the current sheet
var lenr = curTbl.rows.length;
Number of table rows obtained
for (i = 0; i < lenr; i++)
{
var Lenc = curtbl.rows (i). Cells.length;
Gets the number of columns per row
for (j = 0; J < Lenc; J + +)
{
Osheet.cells (i + 1, j + 1). Value =curtbl.rows (i). Cells (j). InnerText;
Assign value
}
}
oXL.Visible = true;
Set Excel Visible Properties
}
function Getxlsfromtbl (intblid, Inwindow) {
try {
var allstr = "";
var curstr = "";
Alert ("Getxlsfromtbl");
if (intblid! = NULL && Intblid! = "" && intblid! = "Null") {
Curstr = Gettbldata (Intblid, Inwindow);
}


if (curstr! = null) {
Allstr + = Curstr;
}

else {
Alert ("The table you want to export does not exist!") ");
Return
}
var fileName = Getexcelfilename ();
Dofileexport (FileName, ALLSTR);
}
catch (e) {
Alert ("Export exception occurred:" + e.name + "+" + e.description + "!");
}
}

function Gettbldata (INTBL, Inwindow) {
var rows = 0;
Alert ("Gettbldata is" + Inwindow);
var tbldocument = document;
if (!! Inwindow && Inwindow! = "") {
if (!document.all (Inwindow)) {
return null;
}
else {
Tbldocument = Eval_r (Inwindow). Document;
}
}


var curtbl = tbldocument.getelementbyidx_x_x (INTBL);
var outstr = "";
if (curtbl! = null) {
for (var j = 0; J < CurTbl.rows.length; J + +) {
Alert ("J is" + j);
for (var i = 0; i < curtbl.rows[j].cells.length;i++) {
Alert ("I am" + i);
if (i = = 0 && rows >0) {
Outstr + = "";
Rows-= 1;
}

Outstr + = Curtbl.rows[j].cells[i].innertext + "";
if (Curtbl.rows[j].cells[i].colspan > 1) {
for (var k = 0; k < curtbl.rows[j].cells[i].colspan-1; k++) {
Outstr + = "";
}
}

if (i = = 0) {
if (rows = = 0 &&curtbl.rows[j].cells[i].rowspan > 1) {
rows = curtbl.rows[j].cells[i].rowspan-1;
}
}
}
Outstr + = "";
}
}

else {
OUTSTR = null;

Alert (intbl + "does not exist!");

}

return outstr;

}

function Getexcelfilename () {

var d = new Date ();


var curyear = D.getyear ();

var curmonth = "" + (D.getmonth () + 1);

var curdate = "" + d.getdate ();

var curhour = "" + d.gethours ();
var Curminute = "" + d.getminutes ();
var Cursecond = "" + d.getseconds ();

if (curmonth.length = = 1) {
Curmonth = "0" + curmonth;
}

if (curdate.length = = 1) {
Curdate = "0" + curdate;
}

if (curhour.length = = 1) {
Curhour = "0" + curhour;
}

if (curminute.length = = 1) {
Curminute = "0" + curminute;
}

if (cursecond.length = = 1) {
Cursecond = "0" + cursecond;
}


var fileName = "Leo_zhang" + "_" + curyear + curmonth + curdate + "_"
+ curhour + curminute + cursecond + ". csv";
alert (fileName);
return fileName;
}


function Dofileexport (inname, inStr) {
var xlswin = null;
if (!! document.all ("Glbhidefrm")) {
Xlswin = glbhidefrm;
}

else {
var width = 6;
var height = 4;
var Openpara = "left=" + (WINDOW.SCREEN.WIDTH/2-WIDTH/2)
+ ", top=" + (WINDOW.SCREEN.HEIGHT/2-HEIGHT/2)
+ ", scrollbars=no,width=" + width + ", height=" + height;
Xlswin = window.open ("", "_blank", Openpara);

}
XlsWin.document.write (INSTR);

XlsWin.document.close ();

XlsWin.document.execCommand (' Saveas ', true, inname);

Xlswin.close ();

}
</SCRIPT>
</body>
---The following are the processing of Excel process shutdown issues----------------------

destructor problems in JavaScript (ActiveX object example)
//---------------------------------------------------------
<script>
var strsavelocation = ' File:///E:/1.xls '

function Createxls () {
var Excel = Newactivexobject ("Excel.Application");
var wk = Excel. Workbooks.Add ();
Wk. SaveAs (strsavelocation);
Wk. Saved = true;

Excel. Quit ();
}

function Writexls () {
var Excel = Newactivexobject ("Excel.Application");
var wk =excel. Workbooks.Open (strsavelocation);
var sheet = wk. Worksheets (1);
Sheet. Cells (1, 1). Value = ' Test string ';
Wk. SaveAs (strsavelocation);
Wk. Saved = true;

Excel. Quit ();
}
</script>

<body>
<buttononclick= "Createxls ()" > Create </button>
<buttononclick= "Writexls ()" > Rewrite </button>
</body>

In this example, the local file operation does not appear to be an exception. --up to just a few memory garbage
Rubbish only. However, if strsavelocation is a remote URL, then local will save a
File access credentials, and only one (remote) instance can open the Excel document concurrently
Storage. Then if you repeatedly click on the "Rewrite" button, there will be an exception.

Note that this is a simplified code for an instance of a shared file when operating in the SPS. Therefore, it is not
"Academic" boring discussion, and practical problems in engineering.

The solution to this problem is very complex. It involves two questions:
-Release of local credentials
-Release of an ActiveX object instance

Let's start with the "fail" issue of objects in JavaScript. To put it simply:
-An object is invalidated outside the context in which it is living.
-A global object is invalidated if it is not being used (referenced).

For example:
//---------------------------------------------------------
When JavaScript objects expire
//---------------------------------------------------------
function Testobject () {
var _obj1 = new Object ();
}

function TestObject2 () {
var _obj2 = new Object ();
return _obj2;
}

Example 1
Testobject ();

Example 2
TestObject2 ()

Example 3
var obj3 = TestObject2 ();
OBJ3 = null;

Example 4
var obj4 = TestObject2 ();
var arr = [Obj4];
OBJ3 = null;
arr = [];

In these four examples:
-"Example 1" constructs the _obj1 in function Testobject (), but when the function exits,
It has left the context of the function, so _obj1 has failed;
-In "Example 2", TestObject2 () also constructs an object _obj2 and outgoing, because
This object has a "out-of-function" context (and life cycle), however, because the function
The return value is not "held" by other variables, so the _obj2 is immediately invalidated;
-In "Example 3", the _obj2 of the TestObject2 () construct is used by the external variable obj3.
At this point, _OBJ2 will not be referenced until the "Obj3=null" code is in effect.
Disappear and fail.
-For the same reason as Example 3, the _obj2 in "Example 4" will be in the "arr=[" line of code
Before it expires.

However, the "invalidation" of an object does not wait for "release". Inside the JavaScript runtime environment, there is no
There is no way to tell the user exactly when the object will be released. This relies on javascript
Memory-recycling mechanism. -This strategy and. NET is similar to the recycling mechanism.

In the previous Excel Operation sample code, the object owner, that is, "Excel." EXE "This process
Occurs only after the release of an ActiveX object instance. And the lock of the file, and the operation
The system's permission credentials are process-dependent. So if the object is only "dead" instead of "released,"
Then other processes have problems processing files and referencing the operating system's permission credentials.

Some people say that this is a bug with JavaScript or COM mechanisms. Actually not, this is OS, ie
A complex relationship with JavaScript, rather than an independent problem.

Microsoft exposes a strategy to address this issue: proactively invoke the memory reclamation process.

A collectgarbage () process (usually referred to as a GC process) is provided in JScript (Microsoft).
The GC process is used to clean up "invalid object failures" in the current IE, which is called the destructor of the object.

The code for invoking the GC procedure in the example above is:
//---------------------------------------------------------
Standard invocation mode for GC procedures when handling ActiveX object
//---------------------------------------------------------
function Writexls () {
(Slightly ...)

Excel. Quit ();
Excel = null;
SetTimeout (CollectGarbage, 1);
}

The first line of code calls Excel. Quit () method to cause the Excel process to abort and exit, due to JavaScript
The environment has an Excel object instance, so the Excel process does not actually abort.

The second line of code causes Excel to be null to clear the object reference, which invalidates the object. However because
The object is still in the function context, so if you call the GC procedure directly, the object will still not be cleaned up.

The third line of code uses settimeout () to invoke the CollectGarbage function, with the interval set to ' 1 ', only
is to make the GC process happen after the Writexls () function finishes executing. This way, the Excel object satisfies the "can be
GC Cleanup "Two conditions: no reference and leave context.

The use of GC processes is effective in JS environments where ActiveX object is used. Some of the potential ActiveX
Object includes XML, VML, OWC (Office webcomponet), Flash, and even vbarray included in JS.
From this point of view, the AJAX architecture has adopted the XMLHTTP, and at the same time to meet the "do not switch page"
feature, so proactively invoking the GC process at the appropriate time will result in a better efficiency with the UI experience.

In fact, even with the GC process, the previously mentioned Excel problem will not be fully resolved. Because IE Also
Permission credentials are cached. The only way to make the page's permission credentials updated is to "switch to a new page",
So in fact, in the SPS project mentioned earlier, I'm not using a GC, but the following
Segment Code:
//---------------------------------------------------------
Page switch code used when working with ActiveX object
//---------------------------------------------------------
function Writexls () {
(Slightly ...)

Excel. Quit ();
Excel = null;

The following code is used to solve the method provided in an BUG,MSDN in IE call Excel:
SetTimeout (CollectGarbage, 1);
Because the trusted state of the Web page cannot be cleared (or synchronized), methods such as the SaveAs () will cause the
The next call is not valid.
Location.reload ();
}

Finally, a supplementary note about GC: IE will be invoked once when the IE form is minimized
The CollectGarbage () function. This allows the IE window to be minimized and memory usage significantly improved.

JavaScript Export Excel Code

Related Article

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.