首页 > 代码库 > 小功能集锦

小功能集锦

1. 导出功能

    public static void OutExcel(DataTable dt)
        {
            GridView gv1 = new GridView();

            gv1.DataSource = dt;
            gv1.DataBind();
            string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.Charset = "GB2312";
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.GetEncoding("GB2312")));
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            gv1.RenderControl(htw);
            HttpContext.Current.Response.Write("<html><head><meta http-equiv=Content-Type content=\"text/html; charset=gb2312\"></head><body>");
            HttpContext.Current.Response.Write(sw.ToString());
            HttpContext.Current.Response.Write("</body></html>");
            HttpContext.Current.Response.End();
        }

这样可以解决导出乱码的问题,以前的方式,乱码有时一条记录时出现,有时多条记录时出现,有时甚至导出了韩文。用这种方法,到目前为止还没有出现过乱码。