asp.net导出excel文件方法两则
方法一
public void Data2Excel(DataTable dtData) { System.Web.UI.WebControls.DataGrid 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.AppendHeader("Content-Disposition", "attachment;filename=ExportStudentInfo.xls"); 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 dgExport = new System.Web.UI.WebControls.DataGrid(); dgExport.ItemDataBound += new DataGridItemEventHandler(dgExport_ItemDataBound); dgExport.DataSource = dtData.DefaultView; dgExport.AllowPaging = false; dgExport.DataBind(); // 返回客户端 dgExport.RenderControl(htmlWriter); curContext.Response.Write(strWriter.ToString()); curContext.Response.End(); } } void dgExport_ItemDataBound(object sender, DataGridItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { e.Item.Cells[3].Attributes.Add("style", "vnd.ms-excel.numberformat:@"); e.Item.Cells[5].Attributes.Add("style", "vnd.ms-excel.numberformat:@"); } }
方法二:
private void Data2Excel(System.Data.DataTable dtData) { System.Web.HttpContext curContext = System.Web.HttpContext.Current; if (dtData != null) { // 设置编码和附件格式 if (curContext.Request.UserAgent.Contains("MSIE")) { curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("报考信息.xls", System.Text.Encoding.UTF8)); } else { curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=报考信息.xls"); } curContext.Response.ContentType = "application/vnd.ms-excel"; curContext.Response.ContentEncoding = System.Text.Encoding.UTF8; curContext.Response.Charset = ""; System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append("<table border='1'>"); sb.Append("<tr><th>序号</th><th>名称</th><th>编码</th><th>数量</th><th>场数量</th><th>xuesheng数量</th><th>轮次信息</th></tr>"); for (int i = 0; i < dtData.Rows.Count; i++) { string stuCount = dtData.Rows[i]["PersonCount"].ToString() == "" ? "0" : dtData.Rows[i]["PersonCount"].ToString(); sb.AppendFormat("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td><td>{5}</td><td >{6}</td></tr>", dtData.Rows[i]["NUM"], dtData.Rows[i]["SiteName"], dtData.Rows[i]["SiteCode"], dtData.Rows[i]["CenterCount"], dtData.Rows[i]["RoomCount"], stuCount, dtData.Rows[i]["SequenceName"]); } sb.Append("</table>"); curContext.Response.Write(sb.ToString()); curContext.Response.End(); } }