c#大圣之路笔记——c# 从DataGrid中导出数据 Session

1 ///前端代码
2 <tr>
3             <td align="right">
4                 <asp:Button ID="btnExport" runat="server" Text="导出错误数据" CssClass="fieldButton" OnClick="btnExport_Click"   style="  height:24px; 100px"></asp:Button>
5             </td>
6         </tr>
 1 ///前端代码
 2  <tr>
 3             <td colspan="4"> 
 4              <asp:DataGrid ID="GridMain" runat="server" Width="100%" AutoGenerateColumns="False"
 5                  AllowPaging="True" PageSize="20" AllowSorting="True" DataMember="" OnPageIndexChanged="GridMain_PageIndexChanged"
 6                   AlternatingItemStyle-BackColor="#EBE9E9">
 7                   <AlternatingItemStyle CssClass="datagridAlternating" ></AlternatingItemStyle>
 8                   <HeaderStyle CssClass="tableHead" Height="22" ></HeaderStyle>
 9                   <Columns>
10                         <asp:BoundColumn DataField="errorMessage" HeaderText="错误原因">
11                             <ItemStyle HorizontalAlign="Center" Width="8%" ></ItemStyle>
12                         </asp:BoundColumn>
13                          <asp:BoundColumn DataField="GID" HeaderText="GID">
14                             <ItemStyle HorizontalAlign="Center" Width="4%" ></ItemStyle>
15                         </asp:BoundColumn>
16                          
17                   </Columns>
18                    <PagerStyle Position="Top" Mode="NumericPages"></PagerStyle>
19               </asp:DataGrid>
20           
21             </td>
22          </tr>
  1 //后台代码
  2    private DataTable Err_dt;
  3    private string tableName;
  4 
  5

    //通过把table中的值放在 Session中,绑定到datagrid中
    Session[tableName] = Err_dt;

  6 
  7 private void bindNextPage(int p)
  8         {
  9             tableName = ViewState["TableName"].ToString();
 10             Err_dt = (DataTable)Session[tableName];
 11             if (ViewState["Sort"].ToString() != "")
 12             {
 13                 DataView dv = new DataView(Err_dt);
 14                 dv.Sort = ViewState["Sort"].ToString();
 15                 GridMain.DataSource = dv;
 16             }
 17             else
 18             {
 19                 GridMain.DataSource = Err_dt;
 20             }
 21 
 22             GridMain.CurrentPageIndex = p;
 23             GridMain.DataBind();
 24             return;
 25         } 
 26 
 27     protected void btnExport_Click(object sender, EventArgs e)
 28         {
 29             GridMain.AllowPaging = false;
 30             GridMain.AllowSorting = false;
 31              
 32             bindNextPage(0);
 33 
 34             Export(GridMain, "ChannelStoreErrorList.xls", "ChannelStoreErrorList", "application/ms-excel");
 35 
 36             GridMain.AllowPaging = true;
 37             GridMain.AllowSorting = false;
 38         }
 39         protected void GridMain_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
 40         { 
 41             currentPageIndex = e.NewPageIndex;
 42             this.GridMain.CurrentPageIndex = currentPageIndex;
 43             //DataTable Err_dt = new DataTable();
 44             //Err_dt = BindERData();
 45             GridMain.DataSource = Err_dt;
 46             GridMain.DataBind();
 47         }
 48 
 49 
 50         #region  Export to the excel
 51 
 52 
 53         // Export to the excel
 54         private void Export(System.Web.UI.WebControls.DataGrid dg, string fileName, string fn, string typeName)
 55         {
 56             System.Web.HttpResponse httpResponse = Page.Response;
 57             httpResponse.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
 58             httpResponse.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
 59             httpResponse.ContentType = typeName;
 60             System.IO.StringWriter tw = new System.IO.StringWriter();
 61             System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
 62             dg.RenderControl(hw);
 63 
 64             //httpResponse.Write(tw.ToString());
 65             //httpResponse.End();
 66             string filePath = Server.MapPath("..") + fn + DateTime.Now.Ticks.ToString() + new Random().Next(100).ToString();
 67             System.IO.StreamWriter sw = System.IO.File.CreateText(filePath);
 68             sw.Write(tw.ToString());
 69             sw.Close();
 70             DownFile(httpResponse, fileName, filePath);
 71 
 72             httpResponse.End();
 73         }
 74 
 75         private bool DownFile(System.Web.HttpResponse Response, string fileName, string fullPath)
 76         {
 77             try
 78             {
 79                 Response.ContentType = "application/octet-stream";
 80 
 81                 Response.AppendHeader("Content-Disposition", "attachment;filename=" +
 82                 HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + ";charset=GB2312");
 83                 System.IO.FileStream fs = System.IO.File.OpenRead(fullPath);
 84                 long fLen = fs.Length;
 85                 int size = 102400;//每100K同时下载数据
 86                 byte[] readData = new byte[size];//指定缓冲区的大小
 87                 if (size > fLen) size = Convert.ToInt32(fLen);
 88                 long fPos = 0;
 89                 bool isEnd = false;
 90                 while (!isEnd)
 91                 {
 92                     if ((fPos + size) > fLen)
 93                     {
 94                         size = Convert.ToInt32(fLen - fPos);
 95                         readData = new byte[size];
 96                         isEnd = true;
 97                     }
 98                     fs.Read(readData, 0, size);//读入一个压缩块
 99                     Response.BinaryWrite(readData);
100                     fPos += size;
101                 }
102                 fs.Close();
103                 FileInfo FI = new FileInfo(fullPath);
104                 if (FI.Exists)
105                 {
106                     FI.Delete();
107                 }
108                 return true;
109             }
110             catch
111             {
112                 return false;
113             }
114         }
115 
116         #endregion
原文地址:https://www.cnblogs.com/allenzhang/p/5276509.html