2013-04-11 59 views
1

出口數據網格視圖到Excel代碼運行時,所有的數據導出到Excel工作表中,但我想在excel表格中只選列了如何解決這個問題出口數據網格視圖到Excel中的ASP點網

protected void btnexcel_Click1(object sender, EventArgs e) 
    { 

    Response.Clear(); 
    Response.Buffer = true; 

    Response.AddHeader("content-disposition", 
    "attachment;filename=ActualsAndBudgets.xls"); 
    Response.Charset = ""; 
    Response.ContentType = "application/ms-excel"; 
    Response.Cache.SetCacheability(HttpCacheability.NoCache); 
    StringWriter sw = new StringWriter(); 
    HtmlTextWriter htw = new HtmlTextWriter(sw); 
    gvdetails.AllowPaging = false; 
    fillgrid(); 
    gvdetails.RenderControl(htw); 
    Response.Write(sw.ToString()); 
    Response.End(); 
    gvdetails.AllowPaging = true; 
    fillgrid(); 

    } 
    public override void VerifyRenderingInServerForm(Control control) 
    { 

    } 
+0

請記住將包含您的數據的數據表傳遞給excel_Click() – 2013-04-11 10:46:37

+0

您準備做什麼? – 2013-04-11 10:51:37

回答

0
using System; 
    using System.Data; 
    using System.IO; 
    using System.Web; 
     using System.Web.UI; 
     using System.Web.UI.WebControls; 

     namespace Whatever 
     { 
     /// 

     /// This class provides a method to write a dataset to the HttpResponse as 
      /// an excel file. 
     /// 

      public class ExcelExport 
     { 
      public static void ExportDataSetToExcel(DataSet ds, string filename) 
     { 
     HttpResponse response = HttpContext.Current.Response; 

    // first let's clean up the response.object 
     response.Clear(); 
     response.Charset = ""; 

     // set the response mime type for excel 
      response.ContentType = "application/vnd.ms-excel"; 
     response.AddHeader("Content-Disposition", "attachment; 
      filename=\"" + filename  + "\""); 

     // create a string writer 
     using (StringWriter sw = new StringWriter()) 
     { 
     using (HtmlTextWriter htw = new HtmlTextWriter(sw)) 
     { 
     // instantiate a datagrid 
     DataGrid dg = new DataGrid(); 
     dg.DataSource = ds.Tables[0]; 
     dg.DataBind(); 
     dg.RenderControl(htw); 
     response.Write(sw.ToString()); 
     response.End(); 
    } 
    } 
    } 
    } 
    }