导出表格EXCEL____备忘
1,首先复制下面的代码至要导出EXCEL页面.调用ExportToExcel('table的ID','要导出EXCEL的名称')即可.
代码
function ExportToExcel(tableid, filename) {
var table = document.getElementById(tableid);
if (!table) { return; }
var data = getTableData(table);
var objBody = document.getElementsByTagName("body").item(0);
var objExpTemp = document.getElementById('objExpTemp');
if (!objExpTemp) {
objExpTemp = document.createElement("iframe");
objExpTemp.setAttribute('id', 'objExpTemp');
objExpTemp.style.display = 'none';
objExpTemp.src = 'about:blank';
objBody.appendChild(objExpTemp);
}
var myForm = objExpTemp.contentWindow.document.forms['myForm'];
if (!myForm) {
objExpTemp.contentWindow.document.write('<div style="display:none"><form name="myForm"><input id="expContent" name="content" type="text" /><input id="expFileName" name="fileName" type="text" /></form></div>');
}
var myForm = objExpTemp.contentWindow.document.forms['myForm'];
var txtData = objExpTemp.contentWindow.document.getElementById('expContent');
txtData.value = data;
var txtFileName = objExpTemp.contentWindow.document.getElementById('expFileName');
txtFileName.value = filename;
myForm.action = 'ExcelTransfer.aspx';
myForm.method = 'POST';
myForm.submit();
return;
}
function getTableData(table) {
var tableData = "<table border=\"1\">" + table.innerHTML + "</table>";
return tableData;
}
2.然后再创建一个ExcelTransfer.aspx页面,aspx.cs代码如下
代码
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class ExcelTransfer : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string strContent = Request["content"];
if (string.IsNullOrEmpty(strContent))
return;
string strFileName = Request["fileName"];
if (string.IsNullOrEmpty(strFileName))
{
strFileName = "导出表格数据";
}
Response.Clear();
Response.Buffer = true;
Response.Charset = System.Text.Encoding.UTF8.WebName;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(strFileName) + ".xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
Response.ContentType = "application/ms-excel";
this.EnableViewState = false;
Response.Write("<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" /></head><body>" + strContent + "</body></html>");
//Response.Write(strContent);
Response.End();
}
}
Over....