將資料導到Excel裡面去又一種方法

來源:互聯網
上載者:User
很久以前寫過一種方法,相關串連在:http://www.cnblogs.com/teracy/archive/2007/05/03/734962.html,網上也有很多這樣的方法,今天在公司看到使用這樣的方式,大同小異,拿出來也可以參考參考吧,可能這樣更容易理解點:方法代碼
 1//出口
 2public static void ToExcel(System.Web.UI.WebControls.DataGrid DataGrid2Excel, string FileName,string Title, string Head)
 3        {
 4            System.IO.StringWriter sw = new System.IO.StringWriter();
 5            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
 6
 7            FrontDecorator(hw);
 8            if (Title != "")
 9                hw.Write(Title + "<br>");
10            if (Head != "")
11                hw.Write(Head + "<br>");
12
13            DataGrid2Excel.EnableViewState = false;
14            DataGrid2Excel.RenderControl(hw);
15
16            RearDecorator(hw);
17
18            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
19            response.Clear();
20            response.Buffer = true;
21            response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-7");
22            response.ContentType = "application/vnd.ms-excel";
23            response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ".xls");
24            response.Charset = "gb2312";
25            response.Write(sw.ToString());
26            response.End();
27        }
28//入口
29        public static void ToExcel(DataTable dt, string FileName)
30        {
31            System.Web.UI.WebControls.DataGrid dgTemp = new System.Web.UI.WebControls.DataGrid();
32            dgTemp.DataSource = dt;
33            dgTemp.DataBind();
34            ToExcel(dgTemp, FileName, "", "");
35        }

FrontDecorator方法
1 private static void FrontDecorator(HtmlTextWriter writer)
2        {
3            writer.WriteFullBeginTag("HTML");
4            writer.WriteFullBeginTag("Head");
5          writer.WriteEndTag("Head");
6            writer.WriteFullBeginTag("Body");        }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.