把DataGrid导出成Excel或者Word文档

 1private void Export(System.Web.UI.WebControls.DataGrid dg,string fileName,string typeName)
 2{
 3
 4System.Web.HttpResponse httpResponse = Page.Response;
 5httpResponse.AppendHeader("Content-Disposition","attachment;filename="+HttpUtility.UrlEncode(fileName,System.Text.Encoding.UTF8)); 
 6httpResponse.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
 7httpResponse.ContentType = typeName;
 8System.IO.StringWriter  tw = new System.IO.StringWriter() ;
 9System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);
10dg.RenderControl(hw);
11string filePath = Server.MapPath("..")+fileName;
12System.IO.StreamWriter sw = System.IO.File.CreateText(filePath);
13sw.Write(tw.ToString());
14sw.Close();
15
16DownFile(httpResponse,fileName,filePath);
17httpResponse.End();
18}

19
20private  bool DownFile(System.Web.HttpResponse Response,string fileName,string fullPath)
21{
22try
23{
24Response.ContentType = "application/octet-stream";
25
26Response.AppendHeader("Content-Disposition","attachment;filename=" + 
27HttpUtility.UrlEncode(fileName,System.Text.Encoding.UTF8) + ";charset=GB2312");
28System.IO.FileStream fs= System.IO.File.OpenRead(fullPath);
29long fLen=fs.Length;
30int size=102400;//每100K同时下载数据 
31byte[] readData = new byte[size];//指定缓冲区的大小 
32if(size>fLen)size=Convert.ToInt32(fLen);
33long fPos=0;
34bool isEnd=false;
35while (!isEnd) 
36
37if((fPos+size)>fLen)
38{
39size=Convert.ToInt32(fLen-fPos);
40readData = new byte[size];
41isEnd=true;
42}

43fs.Read(readData, 0, size);//读入一个压缩块 
44Response.BinaryWrite(readData);
45fPos+=size;
46}
 
47fs.Close(); 
48System.IO.File.Delete(fullPath);
49return true;
50}

51catch
52{
53return false;
54}

55}

56
57
58private void btnWord_Click(object sender, System.EventArgs e)
59{
60Export(dataGrid,"FileName.doc","application/ms-word");
61
62}

63
64private void btnExcel_Click(object sender, System.EventArgs e)
65{
66Export(dataGrid,"FileName.xls","application/ms-excel");
67}

posted on 2006-03-31 15:44  aliketen  阅读(2163)  评论(0)    收藏  举报

(评论功能已被禁用)

导航

< 2025年6月 >
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 1 2 3 4 5
6 7 8 9 10 11 12
点击右上角即可分享
微信分享提示