/*
* 将DataGrid导出为Excel文件
*
* @par
am strT
ITle 文件标题
* @param dgData 待导出的DataGrid
* @param iStartCol 起始列序号
* @param iEndCol 结束列序号
*
* 创建人: calvin
* 创建日期: 2005-10-08
* 修改人:
* 修改日期:
**/
function DataGrid2Excel(strTitle, dgData, iStartCol, iEndCol)
{
// 定义Excel Applic
aiton Object
VAR ap
PExcel = null;
// 当前激活的工作簿
var
currentWork = null;
var currentSheet = null;
try
{
// 初始化application
appExcel = new ActiveXObject("Excel.Application");
appExcel.Visible = true;
}
catch(e)
{
window.alert("Please Install Excel
First");
return;
}
// 获取当前激活的工作部
currentWork = appExcel.Work
Books.Add();
currentSheet = currentWork.ActiveSheet;
// 填充excel内容
// 设置标题
currentSheet.Cells(1,1).Value = strTitle;
currentSheet.Cells(1,1).Value = dgData.innerText;
window.alert(dgData.innerHT
ML);
// 填充内容
for (var iRow = 0; iRow < dgData.rows.length - 1; iRow++)
{
// 显示指定列的内容
for (var iCol = iStartCol; iCol <= iEndCol; iCol++)
{
currentSheet.Cells(iRow + 2, iCol + 1).Value =
dgData.rows[iRow].cells[iCol].innerText;
}
}
}
DataGrid2Excel("使用javascript导出excel的例子", document.getElementsById("dgData"), 0, 3);
--------------------------------------------------------------------------------
/**//// <summary>
/// 把DataTable内容导出伟excel并返回客户端
/// </summary>
/// <param name="dgData">待导出的DataTable</param>
/// 创 建 人:陈文凯
/// 创建日期:2005年10月08日
/// 修 改 人:
/// 修改日期:
p
ublic
static void DataTable2Excel(
System.Data.DataTable dtData)
{
System.Web.UI.WebControls.DataGrid dg
export = null;
// 当前
对话 System.Web.HttpContext curContext = System.Web.HttpContext.Current;
// IO用于导出并返回excel文件
System.IO.StringWriter strWriter = null;
System.Web.UI.HtmlTextWriter htmlWriter = null;
if (dtData != null)
{
// 设置编码和附件格式
curContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.ContentEncoding =System.Text.Encoding.UTF8;
curContext.Response.Charset = "";
// 导出excel文件
strWriter = new System.IO.StringWriter();
htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);
// 为
了解决dgData中可能进行了分页的情况,需要重新定义一个无分页的DataGrid
dgE
xport = new System.Web.UI.WebControls.DataGrid();
dgExport.DataSource = dtData.DefaultView;
dgExport.AllowPa
ging = false;
dgExport.DataBind();
// 返回客户端
dgExport.RenderControl(htmlWriter);
curContext.Response.Write(strWriter.ToString());
curContext.Response.End();
}
}
客户要求的文字,就ok了。因为是从DataTable导出的,所以这种方法解决了分页数据的问题,堪称终极解决方案。