将DataGrid中CheckBox被选择的行存储到EXcel文件中

#region 獲得要輸出的Excel表 ExcelTable
  private DataTable ExcelTable()
  {  
   DataTable newTable = new DataTable();
   newTable.Columns.Add(new DataColumn("編號",typeof(string)));
   newTable.Columns.Add(new DataColumn("詞目",typeof(string)));
   newTable.Columns.Add(new DataColumn("主類目",typeof(string)));
   newTable.Columns.Add(new DataColumn("次類目",typeof(string)));
   newTable.Columns.Add(new DataColumn("撰稿者",typeof(string)));
   newTable.Columns.Add(new DataColumn("附加檔案",typeof(string)));
   for(int i=0;i<this.DataGrid1.Items.Count;i++)
   {
    if(((CheckBox)this.DataGrid1.Items[i].FindControl("oncheck")).Checked)
    {
     DataRow Dr = newTable.NewRow();
     Dr["編號"] = this.DataGrid1.Items[i].Cells[1].Text;
     Dr["詞目"] =this.DataGrid1.Items[i].Cells[7].Text;
     Dr["主類目"] = this.DataGrid1.Items[i].Cells[3].Text;
     Dr["次類目"] = this.DataGrid1.Items[i].Cells[4].Text;
     Dr["撰稿者"] = this.DataGrid1.Items[i].Cells[5].Text;
     if(this.DataGrid1.Items[i].Cells[8].Text.Trim()!="")
      Dr["附加檔案"] = "有附件";
     newTable.Rows.Add(Dr);
    }
   }
   return newTable;
  }
  #endregion

  #region 輸出DataTable到Excel表 ToExcel
  private void ToExcel(DataTable outTable)
  {
   Response.Clear();
   Response.Buffer= true;
   Response.Charset="GB2312";   
   Response.AppendHeader("Content-Disposition","attachment;filename=FileName.xls");
   Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
   Response.ContentType = "application/ms-excel";
   this.EnableViewState = false;   
   System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("zh-tw",true);
   System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
   System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
   //this.DataGrid1.RenderControl(oHtmlTextWriter);
   DataGrid dg = new DataGrid();
   dg.DataSource = outTable;
   dg.DataBind();
   dg.RenderControl(oHtmlTextWriter);
   Response.Write(oStringWriter.ToString());
   Response.End();
  }
  #endregion

  #region 輸出指定的內容到Excel表
  private void OutputExal_Click(object sender, System.EventArgs e)
  {
   this.ToExcel(this.ExcelTable());
  }
  #endregion

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值