JS call page table export excel sample code

  • 2020-03-30 02:22:11
  • OfStack

There are major limitations to using JS methods to invoke page tables to export excel:
1. I have tried several browsers, but only IE supports it.
2, click tools -- security -- custom level --ActiveX related options enabled
Here's the HTML code
 
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 
<% 
String path = request.getContextPath(); 
String basePath = request.getScheme() + "://" 
+ request.getServerName() + ":" + request.getServerPort() 
+ path + "/"; 
%> 
<html> 
<head> 
<script language="javascript"> 
var idTmr = ""; 
//Function function: copy table to Excel
//Parameter: id of tableID table
function CellToTable(tableID) 
{ 
var tid=document.getElementById(tableID); 
//Load the ActiveX control and get the Excel handle
var exApp = new ActiveXObject("Excel.Application"); 

//Create an Excel file
var owb = exApp.WorkBooks.add(); 

//Gets the sheet1 handle CA
var exSheet = exApp.ActiveWorkBook.WorkSheets(1); 
//Set the name of sheet1
exSheet.name=" Demo copy table to Excel In the "; 
//Copy the specified form
var sel=document.body.createTextRange(); 
sel.moveToElementText(tid); 
sel.select(); 
sel.execCommand("Copy"); 

exSheet.Paste();//Paste it into the sheet

//exApp.save();//  Save dialog box, save Excel file  
exApp.Visible = false; 

var fname = exApp.Application.GetSaveAsFilename("save.xls", "Excel Spreadsheets (*.xls), *.xls"); 
owb.SaveAs(fname); 

exApp.Quit();//Exit the Excel instance
exApp = null; 
//Call Cleanup () for garbage collection
idTmr = window.setInterval("Cleanup();",10); 

} 
//Kill Excel process
function Cleanup() { 
window.clearInterval(idTmr); 
CollectGarbage(); 
} 
</script> 
</head> 
<body> 
<table width="307" border="1" cellspacing="0" cellpadding="0" id="tableToExcel" name="tableName"> 
<tr bgcolor="#99CCCC"> 
<td width="66" rowspan="4" bgcolor="#33FF99"> Changchun, jilin </td> 
<td width="67" rowspan="4" bgcolor="#33FF99"> Shenyang, liaoning </td> 
<td width="94" rowspan="4" bgcolor="#33FF99"> Harbin, heilongjiang </td> 
<td width="30" rowspan="4" bgcolor="#33FF99"> Beijing </td> 
<td width="38" bgcolor="#66CC99"> haidian </td> 
</tr> 
<tr bgcolor="#99CCCC"> 
<td bgcolor="#66CC99"> Ji Lin - changchun </td> 
</tr> 
<tr bgcolor="#99CCCC"> 
<td bgcolor="#66CC99"> liaoning - shenyang </td> 
</tr> 
<tr bgcolor="#99CCCC"> 
<td bgcolor="#66CC99"> heilongjiang - Harbin </td> 
</tr> 
<tr bgcolor="#99CCCC"> 
<td colspan="5"> demo javascr and pt On the table copy Processing process ( recommended ) </td> 
</tr> 
<tr bgcolor="#99CCCC"> 
<td colspan="5"><label> 
<div align="center"> 
<input name="textfield" type="text" value=" Single-line text box control " size="30"/> 
</div> 
</label></td> 
</tr> 
</table> 
<br> 
<input type="submit" name="Submit3" value=" Click copy table to Excel In the " onclick= "CellToTable('tableToExcel')" /> 
</body> 
</html> 

Related articles: