日期:2014-05-17 浏览次数:20381 次
public static void DataTable2Excel(System.Data.DataTable dtData, string name) { GridView dgExport = 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 = "UTF-8"; string fileurl = System.Web.HttpUtility.UrlEncode(name) + DateTime.Now.ToString("yyyyMMddHHmm") + ".xlsx"; curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileurl); // 导出excel文件 strWriter = new System.IO.StringWriter(); htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter); // 为了解决dgData中可能进行了分页的情况,需要重新定义一个无分页的DataGrid dgExport = new GridView(); dgExport.DataSource = dtData.DefaultView; dgExport.AllowPaging = false; dgExport.DataBind(); // 返回客户端 dgExport.RenderControl(htmlWriter); curContext.Response.Write(strWriter.ToString()); curContext.Response.End(); } }
<%@ Page Language="C#" EnableViewState="true" %> <%@ Import Namespace="System.Xml" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> public System.Data.DataTable CreateDataTable() { System.Data.DataTable dataTable1 = new System.Data.DataTable("BlogUser"); System.Data.DataRow dr; dataTable1.Columns.Add(new System.Data.DataColumn("Id", typeof(System.Int32))); dataTable1.Columns.Add(new System.Data.DataColumn("Title", typeof(System.String))); for (int i = 0; i < 8; i++) { dr = dataTable1.NewRow(); dr[0] = i; dr[1] = "xxxxxxxxxxxxxxxxxxxxx" + i.ToString(); dataTable1.Rows.Add(dr); } return dataTable1; } protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { } } public static void DataTable2Excel(System.Data.DataTable dtData, string name) { GridView dgExport = 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.ClearContent(); curContext.Response.ContentType = "application/vnd.ms-excel"; curContext.Response.ContentEncoding = System.Text.Encoding.UTF8; curContext.Response.Charset = "UTF-8"; string fileurl = System.Web.HttpUtility.UrlEncode(name) + DateTime.Now.ToString("yyyyMMddHHmm") + ".xlsx"; curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileurl); // 导出excel文件 strWriter = new System.IO.StringWriter(); htmlWriter = new Sy