2010-09-17 19 views
0

我需要將ASP.NET Datagrid或GridView轉換爲可以成爲目標excel一部分的分頁符。 將網格控件轉換爲excel的第一部分並不複雜且相當容易,但我的問題是如何在轉換過程中將分頁符插入到excel文件中。 感謝您的幫助。將Datagrid或Gridview轉換爲優秀的分頁符

回答

2

下面是完整的代碼GridView控件導出到Excel:

using System; 
using System.Data; 
using System.Configuration; 
using System.Collections; 
using System.Web; 
using System.Web.Security; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Web.UI.WebControls.WebParts; 
using System.Web.UI.HtmlControls; 
using System.Data.SqlClient; 

public partial class ExportGridView : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     if (!Page.IsPostBack) 
     { 
      GridView1.DataSource = BindData(); 
      GridView1.DataBind(); 
     } 
    } 



    private string ConnectionString 
    { 

     get { return @"Server=localhost;Database=Northwind; 
     Trusted_Connection=true"; } 

    } 



    private DataSet BindData() 
    { 
     // make the query 
     string query = "SELECT * FROM Categories"; 
     SqlConnection myConnection = new SqlConnection(ConnectionString); 
     SqlDataAdapter ad = new SqlDataAdapter(query, myConnection); 
     DataSet ds = new DataSet(); 
     ad.Fill(ds, "Categories"); 
     return ds; 

    } 




    protected void Button1_Click(object sender, EventArgs e) 
    { 
     Response.Clear(); 

     Response.AddHeader("content-disposition", "attachment; 
     filename=FileName.xls"); 

     Response.Charset = ""; 

     // If you want the option to open the Excel file without saving than 

     // comment out the line below 

     // Response.Cache.SetCacheability(HttpCacheability.NoCache); 

     Response.ContentType = "application/vnd.xls"; 

     System.IO.StringWriter stringWrite = new System.IO.StringWriter(); 

     System.Web.UI.HtmlTextWriter htmlWrite = 
     new HtmlTextWriter(stringWrite); 

     GridView1.RenderControl(htmlWrite); 

     Response.Write(stringWrite.ToString()); 

     Response.End(); 

    } 

    public override void VerifyRenderingInServerForm(Control control) 
    { 

     // Confirms that an HtmlForm control is rendered for the 
     specified ASP.NET server control at run time. 

    } 
} 
+0

縮進代碼4個空格字符內,否則格式化如代碼,而不是像純文本。 – Artemix 2012-11-20 13:04:11