JS
function getXlsFromTbl(inTblId) { try { inTblId = "demo"; var xml = new ActiveXObject("Microsoft.XMLDOM") xml.async = false xml.load(inTblId + ".xml") // Load XSL var xsl = new ActiveXObject("Microsoft.XMLDOM") xsl.async = false xsl.load( inTblId + ".xsl") var d = " " + xml.transformNode(xsl); //去掉 xml 头 var arr = d.split("?>"); //获得文件名 var fileName = getExcelFileName(inTblId); //导出 doFileExport(fileName, arr[1]); } catch (e) { alert("导出发生异常:" + e.name + "->" + e.description + "!"); } } //获得一个文件名 function getExcelFileName(inTblId) { 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 = inTblId + "_" + curYear + curMonth + curDate + "_" + curHour + curMinute + curSecond + ".csv"; //alert(fileName); return fileName; } //导出Excel 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(); }
html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title></title> <script src="ToExcel.js" type="text/javascript"></script> </head> <body> <input id="Button1" type="button" onclick="javascript:getXlsFromTbl('demo');" value="button" /> </body> </html>
Xsl
<?xml version="1.0" encoding="utf-16"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> Title	Artist	country	company	price	year	 <xsl:for-each select="catalog/cd"> <xsl:value-of select="title"/>	<xsl:value-of select="artist"/>	<xsl:value-of select="country"/>	<xsl:value-of select="company"/>	<xsl:value-of select="price"/>	<xsl:value-of select="year"/>	 </xsl:for-each> </xsl:template> </xsl:stylesheet>
XML
<?xml version="1.0" encoding="utf-8"?> <catalog> <cd> <title>Empire Burlesque</title> <artist>Bob Dylan</artist> <country>USA</country> <company>Columbia</company> <price>10.90</price> <year>1985</year> </cd> <cd> <title>Hide your heart</title> <artist>Bonnie Tyler</artist> <country>UK</country> <company>CBS Records</company> <price>9.90</price> <year>1988</year> </cd> </catalog>