标签:
程序如下:
程序描述:该程序能够实现有大型的标题,以及表头等功能
调用方法:ToExcel(newDt, FileName);
protected void ToExcel(DataTable dt, string FileName) { StringBuilder sb = new StringBuilder(); sb.Append("<style type=\"text/css\">"); sb.Append("<!--"); sb.Append(".text"); sb.Append("{mso-style-parent:style0;"); sb.Append("font-size:10.0pt;"); sb.Append("font-family:\"Arial Unicode MS\", sans-serif;"); sb.Append("mso-font-charset:0;"); sb.Append(@"mso-number-format:\@;"); sb.Append("text-align:center;"); sb.Append("border:.5pt solid black;"); sb.Append("white-space:normal;}"); sb.Append("-->"); sb.Append("</style>"); sb.Append("<table cellspacing=\"0\" rules=\"all\" border=\"1\" style=\"border-collapse:collapse;\">"); DataRow[] myRow = dt.Select(); int i = 0; int cl = dt.Columns.Count; //定义标题 sb.Append("<tr align=\"Center\" style=\"font-weight:bold;\">"); sb.Append("<td colspan=\"" + cl + "\" style =\" height : 25px; font-size: 20pt;\">"+ DropEnterprise.SelectedItem + "</td>"); sb.Append("</tr>"); //定义中间标题 sb.Append("<tr align=\"Center\" style=\"font-weight:bold;\">"); sb.Append("<td >" + txtStart.Text + "</td>"); for (i = 0; i < cl - 2; i++) { sb.Append("<td ></td>"); } sb.Append("<td >" + DropEnterprise.SelectedItem + "</td>"); sb.Append("</tr>"); //定义字段名 sb.Append("<tr align=\"Center\" style=\"font-weight:bold;\">"); for (i = 0; i < cl; i++) { if (i == (cl - 1)) { sb.Append("<td>" + dt.Columns[i].ColumnName.ToString() + "</td></tr>"); } else { //ls_item += dt.Columns[i].ColumnName.ToString() + "\t"; sb.Append("<td>" + dt.Columns[i].ColumnName.ToString() + "</td>"); } } //定义数据 foreach (DataRow row in myRow) { sb.Append("<tr align=\"Center\">"); for (i = 0; i < cl; i++) { if (i == (cl - 1)) { sb.Append("<td>" + row[i].ToString() + "</td></tr>"); } else { //ls_item += dt.Columns[i].ColumnName.ToString() + "\t"; sb.Append("<td>" + row[i].ToString() + "</td>"); } } } sb.Append("</table>"); System.Web.HttpContext.Current.Response.Clear(); System.Web.HttpContext.Current.Response.Charset = "GB2312"; // System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8; // 添加头信息,为"文件下载/另存为"对话框指定默认文件名 System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls"); // 添加头信息,指定文件大小,让浏览器能够显示下载进度 // System.Web.HttpContext.Current.Response.AddHeader("Content-Length",sb.ToString()); // 指定返回的是一个不能被客户端读取的流,必须被下载 System.Web.HttpContext.Current.Response.ContentType = "application/ms-excel"; // 把文件流发送到客户端 System.Web.HttpContext.Current.Response.Write(sb.ToString()); // 停止页面的执行 System.Web.HttpContext.Current.Response.End(); }
asp.net后台导出excel的方法:使用System.Web.HttpContext.Current.Response导出excel
标签:
原文地址:http://www.cnblogs.com/sizhizhiyue/p/4825589.html