导出Excel

直接代码:

        public static void ExportExcel(GridView gv, HttpContext context)
        {
            gv.HeaderStyle.BackColor = System.Drawing.Color.FromArgb(2552550); //rgb(243, 243, 243)
            for (int i = 0; i < gv.Rows.Count; i++)
            {
                for (int j = 0; j < gv.Rows[i].Cells.Count; j++)
                {
                    gv.Rows[i].Cells[j].Attributes.Add("style""vnd.ms-excel.numberformat:@");
                }
            }
            HttpResponse resp = context.Response;
            resp.Charset = "GB2312";
            resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            string fileName = "ExportData.xls";
            if (string.IsNullOrEmpty(gv.ToolTip) == false) fileName = gv.ToolTip+".xls";
            resp.AppendHeader("Content-Disposition""attachment;filename=" +
                HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8).ToString());
            resp.ContentType = "application/ms-excel";
            StringWriter tw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(tw);
            gv.RenderControl(hw); //输出结构
            string content = "<html><head><meta http-equiv=Content-Type content=\"text/html; charset=gb2312\">";
            content += tw.ToString();
            content += "</body></html>";
            resp.Output.Write(content);
            resp.Flush();
            resp.End();
        } 

 

posted @ 2012-08-27 15:04  IT-民工  阅读(110)  评论(0编辑  收藏  举报