很久以前写过一种方法,相关连接在:http://www.cnblogs.com/teracy/archive/2007/05/03/734962.html,网上也有很多这样的方法,今天在公司看到使用这样的方式,大同小异,拿出来也可以参考参考吧,可能这样更容易理解点:

方法代码
1
//出口
2
public 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"); }
1
//出口2
public 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
}1
private static void FrontDecorator(HtmlTextWriter writer)2

{3
writer.WriteFullBeginTag("HTML");4
writer.WriteFullBeginTag("Head");5
writer.WriteEndTag("Head");6
writer.WriteFullBeginTag("Body"); }
浙公网安备 33010602011771号