冷风.NET

    ---默默無聞
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
#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