电竞比分网-中国电竞赛事及体育赛事平台

分享

gridview導(dǎo)出到Excel問題

 實(shí)力決定地位 2012-06-09

首先要把GridView控件放到panel中
  
     AutoGenerateColumns="False" AllowPaging="True" AllowSorting="True" OnRowDeleting="gridview1_RowDeleting"
  OnRowEditing="gridview1_RowEditing" DataKeyNames="sno" OnDataBound="gridview1_DataBound"
  Font-Size="14px">
  
     DataNavigateUrlFormatString="StudentInfo.aspx?id={0}" />
  
   
  再添加一個按鈕,用于觸發(fā)導(dǎo)出事件:
  
  以上為aspx頁面代碼,后臺代碼則是:
  protected void lbtnexcel_Click(object sender, EventArgs e)
  {
  gridview1.BottomPagerRow.Visible = false;//導(dǎo)出Excel表后,隱藏分頁部分
  gridview1.Columns[9].Visible = false;//隱藏“編輯”
  gridview1.Columns[10].Visible = false;//隱藏“刪除”
  DateTime dt = DateTime.Now;//給導(dǎo)出后的Excel表命名,結(jié)合表的用途以及系統(tǒng)時間來命名
  string filename = dt.Year.ToString() + dt.Month.ToString() + dt.Day.ToString() + dt.Hour.ToString() + dt.Minute.ToString() + dt.Second.ToString();
  /*如導(dǎo)出的表中有某些為編號、身份證號之類的純數(shù)字字符串,如不進(jìn)行處理,則導(dǎo)出的數(shù)據(jù)會默認(rèn)為數(shù)字,例如原字符串"0010"則會變?yōu)?B style="BACKGROUND-COLOR: #ff66ff; COLOR: black">數(shù)字10,字符串"1245787888"則會變?yōu)榭茖W(xué)計(jì)數(shù)法1.236+E9,這樣便達(dá)不到我們想要的結(jié)果,所以需要在導(dǎo)出前對相應(yīng)添加格式化的數(shù)據(jù)類型,以下為格式化為字符串型*/
  foreach (GridViewRow dg in this.gridview1.Rows)
  {
  dg.Cells[0].Attributes.Add("style", "vnd.ms-excel.numberformat: @;");
  dg.Cells[5].Attributes.Add("style", "vnd.ms-excel.numberformat: @;");
  dg.Cells[6].Attributes.Add("style", "vnd.ms-excel.numberformat: @;");
  dg.Cells[8].Attributes.Add("style", "vnd.ms-excel.numberformat: @;");
  }
  Response.Clear();
  Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode("學(xué)生表" + filename, System.Text.Encoding.UTF8) + ".xls");//導(dǎo)出文件命名
  Response.ContentEncoding = System.Text.Encoding.UTF7;//如果設(shè)置為"GB2312"則中文字符可能會亂碼
  Response.ContentType = "applicationshlnd.xls";
  System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
  System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
  Panel1.RenderControl(oHtmlTextWriter);//Add the Panel into the output Stream.
  Response.Write(oStringWriter.ToString());//Output the stream.
  Response.Flush();
  Response.End();
  }
  //重載VerifyRenderingInServerForm方法,否則運(yùn)行的時候會出現(xiàn)如下錯誤提示:“類型“GridView”的控件“GridView1”必須放在具有 runat=server 的窗體標(biāo)記內(nèi)”
  public override void VerifyRenderingInServerForm(Control control)
  {
  //override VerifyRenderingInServerForm.
  }

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點(diǎn)擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多