protected void ToExcel() { //新建一个Gridview,原因:避免当前窗口GridView外层没有直接跟form标签,从而避免“gridview1未包含在run='server'”的错误。 GridView gvOrders = new GridView(); System.IO.StringWriter sw = new System.IO.StringWriter(); //定义页面输出格式。 Response.Write("<meta http-equiv=Content-Type content="ms-excel; charset=utf-8">"); //定义文件名称 string fileName = System.Web.HttpUtility.UrlEncode(DateTime.Now.ToString("_yyyyMMddHHmmss"), Encoding.UTF8); //取得数据源 DataTable dt = (DataTable)Session["dt"];//在repeater数据绑定的时候,预先将dt赋值给Session //设置Excel网格(注意XML内容,定义Sheet工作簿名称和网格线) if (dt != null) { sw.WriteLine("<html xmlns:x="urn:schemas-microsoft-com:office:excel">"); sw.WriteLine("<head>"); sw.WriteLine("<!--[if gte mso 9]>"); sw.WriteLine("<xml>"); sw.WriteLine(" <x:ExcelWorkbook>"); sw.WriteLine(" <x:ExcelWorksheets>"); sw.WriteLine(" <x:ExcelWorksheet>"); sw.WriteLine(" <x:Name>" + fileName + "</x:Name>"); sw.WriteLine(" <x:WorksheetOptions>"); sw.WriteLine(" <x:Print>"); sw.WriteLine(" <x:ValidPrinterInfo />"); sw.WriteLine(" </x:Print>"); sw.WriteLine(" </x:WorksheetOptions>"); sw.WriteLine(" </x:ExcelWorksheet>"); sw.WriteLine(" </x:ExcelWorksheets>"); sw.WriteLine("</x:ExcelWorkbook>"); sw.WriteLine("</xml>"); sw.WriteLine("<![endif]-->"); sw.WriteLine("</head>"); sw.WriteLine("<body>"); sw.WriteLine("<table style=font-size:15px>"); sw.WriteLine(" <tr style=font-size:17px;font-weight:bold;font-family:Arial>"); //根据数据库表 生成列标题,注意这里根据需要的列名设置标题和获取数据 for (int i = 0; i < dt.Columns.Count; i++) { if (i == 5)sw.WriteLine(" <td>标题</td>"); if (i == 23) sw.WriteLine(" <td>发布人</td>"); if (i == 24) sw.WriteLine(" <td>添加时间</td>"); if (i == 28) sw.WriteLine(" <td>最新状态</td>"); } sw.WriteLine(" </tr>"); //根据数据库表 生成列数据 for (int i = 0; i < dt.Rows.Count; i++) { sw.WriteLine(" <tr>"); for (int j = 0; j < dt.Columns.Count; j++) { if (j == 5 || j == 23 || j == 24 || j == 28) //根据数据库表 根据需要的列获取数据 { if (j == 28) { if (dt.Rows[i][j].ToString().Trim() == "") sw.WriteLine(" <td>未签收</td>"); else sw.WriteLine(" <td style=color:red>已签收:" + dt.Rows[i][j] + "</td>"); } else sw.WriteLine(" <td>" + dt.Rows[i][j] + "</td>"); } } sw.WriteLine(" </tr>"); } sw.WriteLine("</table>"); sw.WriteLine("</body>"); sw.WriteLine("</html>"); Response.Clear(); //应用缓存 Response.Buffer = true; Response.Charset = "utf-8"; //设置 文件的名称 Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls"); //设置 内容格式。 Response.ContentType = "application/ms-excel"; //设置 输出编码 Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8"); this.EnableViewState = false; System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw); //不允许翻页 gvOrders.AllowPaging = false; //不允许排序 gvOrders.AllowSorting = false; //绑定数据源 gvOrders.DataSource = dt; gvOrders.DataBind(); //写入HtmlTextWriter gvOrders.RenderControl(hw); //Response.Write(sw.ToString());//换成下面这句可以解决乱码
Response.Write("<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=utf-8"/>" + sw.ToString());
Response.End(); } }
最终效果