[ASP.NET]兩種匯出網頁到EXCEL的方法

來源:互聯網
上載者:User

第一種,將DataGrid作為參數傳入,將DataGrid轉成Excel

public bool ToExcel(System.Web.UI.Control ctl) 
  {
   try
   {
    HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=Excel.xls");
    HttpContext.Current.Response.Charset ="UTF-8";   
    HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default;
    HttpContext.Current.Response.ContentType ="application/ms-excel";//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword
    ctl.Page.EnableViewState =false;  
    System.IO.StringWriter  tw = new System.IO.StringWriter() ;
    System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);
    ctl.RenderControl(hw);
    HttpContext.Current.Response.Write(tw.ToString());
    HttpContext.Current.Response.End();
    return true;
   }
   catch(Exception e)
   {
    _errormsg = e.Message;
                return false;
   }
  }

第二種,直接將DataSet匯出成Excel

public void CreateExcel(DataSet ds,string typeid,string FileName)
  {
   HttpResponse resp;
   resp = Page.Response;
   resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
   resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);
   resp.Charset ="UTF-8";    
   
   string colHeaders= "", ls_item="";
   int i=0;

   //定義表對象與行對像,同時用DataSet對其值進行初始化
   DataTable dt=ds.Tables[0];
   DataRow[] myRow=dt.Select("");
   // typeid=="1"時匯出為EXCEL格式檔案;typeid=="2"時匯出為XML格式檔案
   if(typeid=="1")
   {

   resp.ContentType ="application/ms-excel";//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword
    //取得資料表各欄位標題,各標題之間以\t分割,最後一個欄位標題後加斷行符號符
    for(i=0;i<dt.Columns.Count-1;i++)
     colHeaders+=dt.Columns[i].Caption.ToString()+"\t";
    colHeaders +=dt.Columns[i].Caption.ToString() +"\n";  
    //向HTTP輸出資料流中寫入取得的資料資訊
    resp.Write(colHeaders);
    //逐行處理資料 
    foreach(DataRow row in myRow)
    {
     //在當前行中,逐列獲得資料,資料之間以\t分割,結束時加斷行符號符\n
     for(i=0;i<dt.Columns.Count-1;i++)
      ls_item +=row[i].ToString().Replace("\t","") + "\t";    
     ls_item += row[i].ToString().Replace("\t","") +"\n";
     //當前行資料寫入HTTP輸出資料流,並且置空ls_item以便下行資料   
     resp.Write(ls_item);
     ls_item="";
    }
   }
   else
   {
    if(typeid=="2")
    {
     //從DataSet中直接匯出XML資料並且寫到HTTP輸出資料流中
     resp.Write(ds.GetXml());
    }   
   }
   //寫緩衝區中的資料到HTTP標頭檔中
   resp.End();
  }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.