JavaScript export Excel instance detailed _javascript tips

Source: Internet
Author: User

The example in this article describes how JavaScript exports Excel. Share to everyone for your reference. The implementation methods are as follows:

Copy Code code as follows:
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
How to export a <title>web 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 Headings 1</td>
<td> column Headings 2</td>
<td> column Headings 3</td>
<td> column Headings 4</td>
<td> column Headings 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 is imported to Excel >
<input type= "button" onclick= javascript:getxlsfromtbl (' tableexcel ', null); "Value=" The third method is imported to Excel >
<script language= "JavaScript" >
function Method1 (tableid) {//Full table Copy 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;
Activate current sheet
var sel = Document.body.createTextRange ();
Sel.movetoelementtext (CURTBL);
Move the contents of the table to TextRange
Sel.select ();
Full selection of TextRange contents
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 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;
Activate current sheet
var lenr = curTbl.rows.length;
Get the number of rows in the table
for (i = 0; i < lenr; i++)
{
var Lenc = curtbl.rows (i). Cells.length;
Get 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;
assigning values
}
}
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 is" + 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>

Here's how to handle Excel process shutdown issues

Copy Code code as follows:
The destructor problem in JavaScript (ActiveX object example)
//---------------------------------------------------------
<script>
var strsavelocation = ' File:///E:/1.xls '
function Createxls () {
var excel = new ActiveXObject ("Excel.Application");
var wk = Excel. Workbooks.Add ();
Wk. SaveAs (strsavelocation);
Wk. Saved = true;

Excel. Quit ();
}

function Writexls () {
var excel = new ActiveXObject ("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>
<button onclick= "Createxls ()" > Create </button>
<button onclick= "Writexls ()" > Rewrite </button>
</body>

In this example, the local file operation does not cause an exception. --at most, there is only memory garbage. However, if strsavelocation is a remote URL, a certificate of File access permission will be saved locally, and only one (remote) instance can be opened and stored. Then if you repeatedly click the "Rewrite" button, there will be an exception.

-Note that this is a simplified code for an instance of operating a shared file in an SPS. Therefore, it is not an "academic" boring discussion, but also a practical problem in engineering.

The way to solve this problem is very complicated. It involves two questions:
① the release of local credentials
②activex object instance's release

Let's start with the "fail" problem of the object 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:

Copy Code code as follows:
//---------------------------------------------------------
When JavaScript objects fail
//---------------------------------------------------------
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 the function Testobject (), but when the function exits, it has left the context of the function, so the _obj1 is invalid;
-in Example 2, an object is also constructed in TestObject2 () and is _obj2, so that the object has a context (and a lifetime) outside of the function, but the _OBJ2 is immediately invalidated because the return value of the function is not "held" by another variable;
-In "Example 3", the _obj2 of the TestObject2 () construct is held by an external variable obj3, and _obj2 will not expire because the reference relationship disappears until the "obj3=null" line of code takes effect.
-For the same reason as Example 3, the _obj2 in "Example 4" will not expire until after the "arr=[" line of code.

However, the "expiration" of an object is not "released". Within the JavaScript runtime environment, there is no way to tell the user exactly when the object will be released. This relies on JavaScript's memory recycle mechanism. --This strategy and. NET, the recycling mechanism is similar.

In the previous Excel action sample code, the owner of the object, which is "Excel." EXE "This process will only occur after" release of an ActiveX object instance ". The lock on the file, and the permission credentials of the operating system, are related to the process. So if the object is only "fail" instead of "release", then the other process will have problems processing the file and referencing the permissions credentials of the operating system.

Some people say this is a bug in JavaScript or COM mechanics. Not really, this is the result of a complex relationship between OS, ie and JavaScript, rather than a stand-alone issue.

Microsoft exposes a strategy to address this problem by actively invoking the memory recycle process.

In JScript (Microsoft), a collectgarbage (usually referred to as a GC process) is provided, and the GC process is used to clean up "failed object loss cases" in current IE, which is the destructor of the calling object.

The code that invokes the GC procedure in the previous example is:

Copy Code code as follows:
//---------------------------------------------------------
Standard invocation method for GC process 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 because the JavaScript environment holds an instance of the Excel object, so the Excel process is not actually aborted.

The second line of code makes Excel null to clear the object reference, causing the object to "fail". However, because the object is still in the function context, the object will not be cleaned up if the GC procedure is called directly.

The third line of code uses settimeout () to invoke the CollectGarbage function, with the interval set to ' 1 ', just to make the GC process happen after the Writexls () function has been executed. This allows the Excel object to meet the two criteria for GC cleanup: No referencing and leaving the context.

The use of GC processes is effective in JS environments that use ActiveX object. Some of the potential ActiveX object includes XML, VML, OWC (Office Web componet), Flash, and even vbarray included in JS.

From this point of view, Ajax architecture because of the adoption of XMLHTTP, and at the same time to meet the "do not switch the page" feature, so the appropriate time to actively invoke the GC process, will be better efficiency with the UI experience.

In fact, even with the GC process, the Excel problem mentioned earlier will not be completely resolved. Because IE also caches the permission credentials. The only way to make the page's permission credentials updated is to "switch to a new page", so in fact, the method I used in the SPS project mentioned earlier is not a GC, but the following code:

Copy Code code as follows:
//---------------------------------------------------------
Page switch code used when handling ActiveX object
//---------------------------------------------------------
function Writexls () {
(Slightly ...)

Excel. Quit ();
Excel = null;

The following code resolves a bug in IE call Excel, which is provided in MSDN:
SetTimeout (CollectGarbage, 1);
Because the trusted state of the Web page cannot be purged (or synchronized), it will cause methods such as SaveAs () to
The next call is invalid.
Location.reload ();
}

Finally, a supplementary note about GC: When IE forms are minimized, IE will actively call once
CollectGarbage () function. This allows the IE window to be minimized, memory footprint will be significantly improved.

I hope this article will help you with your JavaScript based Web programming.

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.