表格例子如下:
<table id="tableExcel" width="100%" border="1" cellspacing="0" cellpadding="0">
<tr>
<td colspan="5" align="center">html 表格导出道Exceltd>
tr>
<tr>
<td>列标题1td>
<td>列标题2td>
<td>类标题3td>
<td>列标题4td>
<td>列标题5td>
tr>
<tr>
<td>aaatd>
<td>bbbtd>
<td>ccctd>
<td>dddtd>
<td>eeetd>
tr>
<tr>
<td>AAAtd>
<td>BBBtd>
<td>CCCtd>
<td>DDDtd>
<td>EEEtd>
tr>
<tr>
<td>FFFtd>
<td>GGGtd>
<td>HHHtd>
<td>IIItd>
<td>JJJtd>
tr>
table>
1、js的方法
A、将整个表格拷贝到EXCEL中
function method1(tableid) {
var curTbl = document.getElementById(tableid);
var oXL = new ActiveXObject("Excel.Application");
var oWB = oXL.Workbooks.Add();
var oSheet = oWB.ActiveSheet;
var sel = document.body.createTextRange();
sel.moveToElementText(curTbl);
sel.select();
sel.execCommand("Copy");
oSheet.Paste();
oXL.Visible = true;
}
B、读取表格中每个单元到EXCEL中:
function method2(tableid)
{
var curTbl = document.getElementById(tableid);
var oXL = new ActiveXObject("Excel.Application");
var oWB = oXL.Workbooks.Add();
var oSheet = oWB.ActiveSheet;
var Lenr = curTbl.rows.length;
for (i = 0; i < Lenr; i++)
{
var Lenc = curTbl.rows(i).cells.length;
for (j = 0; j < Lenc; j++)
{
oSheet.Cells(i + 1, j + 1).value = curTbl.rows(i).cells(j).innerText;
}
}
oXL.Visible = true;
}
c、把表格输出到另一个页面,然后存成cvs格式
function getXlsFromTbl(inTblId, inWindow)
{
try {
var allStr = "";
var curStr = "";
if (inTblId != null && inTblId != "" && inTblId != "null") {
curStr = getTblData(inTblId, inWindow);
}
if (curStr != null) {
allStr += curStr;
}
else {
alert("你要导出的表不存在");
return;
}
var fileName = getExcelFileName();
doFileExport(fileName, allStr);
}
catch(e) {
alert("导出发生异常:" + e.name + "->" + e.description + "!");
}
}
function getTblData(inTbl, inWindow) {
var rows = 0;
var tblDocument = document;
if (!!inWindow && inWindow != "") {
if (!document.all(inWindow)) {
return null;
}
else {
tblDocument = eval(inWindow).document;
}
}
var curTbl = tblDocument.getElementById(inTbl);
var outStr = "";
if (curTbl != null) {
for (var j = 0; j < curTbl.rows.length; j++) {
for (var i = 0; i < curTbl.rows[j].cells.length; i++) {
if (i == 0 && rows > 0) {
outStr += " /t";
rows -= 1;
}
outStr += curTbl.rows[j].cells[i].innerText + "/t";
if (curTbl.rows[j].cells[i].colSpan > 1) {
for (var k = 0; k < curTbl.rows[j].cells[i].colSpan - 1; k++) {
outStr += " /t";
}
}
if (i == 0) {
if (rows == 0 && curTbl.rows[j].cells[i].rowSpan > 1) {
rows = curTbl.rows[j].cells[i].rowSpan - 1;
}
}
}
outStr += "/r/n";
}
}
else {
outStr = null;
alert(inTbl + "不存在 !");
}
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 = "table" + "_" + curYear + curMonth + curDate + "_"
+ curHour + curMinute + curSecond + ".csv";
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();
}
总结:比较上面3种方法,感觉第一种方法比较完美一些,因为这种方法比较完整的输出表格的格式。但,第一和第二种方法都用了ActiveX 对象,对客户端的安全有要求,而且最大的问题还有一个,就是excel 对象无法关闭。第3中方法虽然没有用ActiveX 对象,但是用了弹出窗口输出, 如果禁止了弹出窗口则无法使用。
对于execl 对象无法关闭的问题,下面的方法是一个权宜方法:
function Cleanup() {
window.clearInterval(idTmr);
CollectGarbage();
}
调用方法:
idTmr = window.setInterval("Cleanup();",1);
2、Asp.net WebForm中的方法
这种方法其实类似上面的js的第3中方法(也可以在其他的web脚本来实现,比如asp中vbscript,或者php),把表格用文件流的方式
输出为excel。实例代码如下:
public void OutPutExcel(string title)
{
Response.Clear();
Response.Buffer = true;
Response.Charset = "utf-8";
Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(title + ".xls"));
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
Response.ContentType = "application/ms-excel";
Page.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.Page.RenderControl(oHtmlTextWriter);
string temp = oStringWriter.ToString();
Response.Write(temp);
Response.End();
}
这种方法的从本质上说并非标准的excel格式,不过把html格式的文件另存为excel的格式,然后用excel打开罢了。
3、Asp.net MVC中的方法
1)使用FileContentResult
StringBuilder table = new StringBuilder();
table.Append("数据库中抓取需要的数据,组织成Html的<table></table>标签");
byte
[] b = System.Text.Encoding.Default.GetBytes(table);
//字串转byte阵列
return
File(b,
"application/vnd.ms-excel"
,
"这是Excel.xls"
);
//通过FileResult输出给Client端
3)使用FilePathResult
服务器上首先必须要有这个Excel文件,然会通过Server.MapPath获取路径返回.
public FileResult ExportExcel() 2 { 3 var sbHtml = new StringBuilder(); 4 sbHtml.Append("<table border='1' cellspacing='0' cellpadding='0'>"); 5 sbHtml.Append("<tr>"); 6 var lstTitle = new List<string> { "编号", "姓名", "年龄", "创建时间" }; 7 foreach (var item in lstTitle) 8 { 9 sbHtml.AppendFormat("<td style='font-size: 14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item); 10 } 11 sbHtml.Append("</tr>"); 12 13 for (int i = 0; i < 1000; i++) 14 { 15 sbHtml.Append("<tr>"); 16 sbHtml.AppendFormat("<td style='font-size: 12px;height:20px;'>{0}</td>", i); 17 sbHtml.AppendFormat("<td style='font-size: 12px;height:20px;'>屌丝{0}号</td>", i); 18 sbHtml.AppendFormat("<td style='font-size: 12px;height:20px;'>{0}</td>", new Random().Next(20, 30) + i); 19 sbHtml.AppendFormat("<td style='font-size: 12px;height:20px;'>{0}</td>", DateTime.Now); 20 sbHtml.Append("</tr>"); 21 } 22 sbHtml.Append("</table>"); 23 24 //第一种:使用FileContentResult 25 byte[] fileContents = Encoding.Default.GetBytes(sbHtml.ToString()); 26 return File(fileContents, "application/ms-excel", "fileContents.xls"); 27 28 //第二种:使用FileStreamResult 29 var fileStream = new MemoryStream(fileContents); 30 return File(fileStream, "application/ms-excel", "fileStream.xls"); 31 32 //第三种:使用FilePathResult 33 //服务器上首先必须要有这个Excel文件,然会通过Server.MapPath获取路径返回. 34 var fileName = Server.MapPath("~/Files/fileName.xls"); 35 return File(fileName, "application/ms-excel", "fileName.xls"); 36 }