2013年4月10日 星期三

[ASP.NET][WebControl] GridView簡易匯出Excel

簡易方式匯出就是透過 GridView 控制項所輸出的 HTML,輸出的檔案存成*.xls然後就Excel可以去開啟檔案了,這個匯出方式比較簡易

我將匯出再調整為直接透過GridView 控制項所輸出的 HTML與按照GridView裡面資料自行調整HTML

 

直接透過GridView 控制項所輸出的 HTML,記得要將EnableEventValidation="false"和覆寫

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Data.aspx.cs" Inherits="Data" EnableEventValidation="false"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btn" runat="server" Text="ExportToExcel" onclick="btn_Click" />
</div>

<div>
<asp:GridView ID="GridView1" runat="server" PageSize="2" AllowPaging="True"
AutoGenerateColumns="False" onpageindexchanging="GridView1_PageIndexChanging">
<Columns>
<asp:BoundField DataField="EmployeeID" HeaderText="編號" SortExpression="EmployeeID" />
<asp:BoundField DataField="LastName" HeaderText="姓氏" SortExpression="LastName" />
<asp:BoundField DataField="FirstName" HeaderText="名" SortExpression="FirstName" />
<asp:BoundField DataField="Title" HeaderText="標題" SortExpression="Title" />
</Columns>
</asp:GridView>
</div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:DBConnection %>" ></asp:SqlDataSource>
</form>
</body>
</html>






protected void ExportExcelFile1()
    {
        string filename = "SampleExcelFile";
        string strfileext = ".xls";
        StringWriter tw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(tw);
        HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + strfileext);
        HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=text/html;charset=utf-8>");
        
        //先把分頁關掉
        GridView1.AllowPaging = false;
        bindgv();
 
        //Get the HTML for the control.
        GridView1.RenderControl(hw);
        HttpContext.Current.Response.Write(tw.ToString());
        HttpContext.Current.Response.End();
        
        GridView1.AllowPaging = true;
        bindgv();
    }
    //必須覆寫 Page.VerifyRenderingInServerForm 
    public override void VerifyRenderingInServerForm(Control control)
    {
    }

 


匯出結果


image


 


 


另一個方式還是透過GridView,不過自己編寫HTML



protected void ExportExcelFile2()
    {
        string filename = "SampleExcelFile";        
        string title = " Excel Title ";
 
        string html = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=big5\">"
                     + "<title>新增網頁1</title></head>" + title + "<br>";
        html += "<table border=\"1\">";
 
        //表頭
        html += "<tr>";
        for (int i = 0; i < GridView1.Columns.Count; i++)
        {
            if (!GridView1.Columns[i].Visible)
            {
                continue;
            }
            html += "<td bgcolor=\"#E4E4E4\">" + GridView1.HeaderRow.Cells[i].Text;
        }
 
        html += "</tr>";
 
        //先把分頁關掉
        GridView1.AllowPaging = false;
        bindgv();
        //內容
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            html += "<tr>";
            for (int c = 0; c < GridView1.Columns.Count; c++)
            {
                if (!GridView1.Columns[c].Visible)
                {
                    continue;
                }
                if (GridView1.Rows[i].Cells[c].Controls.Count > 0)
                {
                    //html += "<td>" + ((Label)gv.Rows[i].Cells[c].Controls[1]).Text + "</td>";
                    html += "<td>" + GridView1.Rows[i].Cells[c].Text + "</td>";
                }
                else
                {
                    html += "<td>" + GridView1.Rows[i].Cells[c].Text + "</td>";
                }
 
            }
            html += "</tr>";
        }
        html += "</table>";
 
        GridView1.AllowPaging = true;
        bindgv();
 
        string sContentDisposition = "";
        sContentDisposition += "attachment; "; // 強制存檔,未設定則依瀏覽器預設開啟或存檔
        sContentDisposition += "filename=" + HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8) + ".xls"; //設定檔名可為中文_#1
 
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader("Content-disposition", sContentDisposition);
        HttpContext.Current.Response.ContentType = "application/vnd.ms-excle";        
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
 
        //utt8 to ascii
        Byte[] bytes = System.Text.Encoding.Unicode.GetBytes(html);
        Byte[] outByte = System.Text.Encoding.Convert(System.Text.Encoding.Unicode, System.Text.Encoding.Default, bytes);
 
        HttpContext.Current.Response.BinaryWrite(outByte);
        HttpContext.Current.Response.End();
    }

匯出結果


image


 


這個簡易匯出方式,都是透過GridView,也可直接透過DataTable取得資料去進行匯出,反正都是簡易的匯出方式

2013年4月9日 星期二

[ASP.NET][WebControls] GridView取得總筆數

GirdView如果是用SqlDataSource連結來源的話

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewPage.aspx.cs" Inherits="GridViewPage" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    <div>
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
    </div>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:DBConnection %>"></asp:SqlDataSource>
    </form>
</body>
</html>





GridView看看有無分頁,沒有分頁的話,直接取GridView的RowsCount,不過這方式不太實用也不方便




using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class GridViewPage : System.Web.UI.Page
{
 
    protected void Page_Load(object sender, EventArgs e)
    {
        
        
        if (!IsPostBack)
        {
            bindgv();
        }
    }
 
    protected void bindgv()
    {
        string str = "select EmployeeID,LastName,FirstName,Title from Employees ";
        SqlDataSource1.SelectCommand = str;
        GridView1.DataSource = SqlDataSource1;
        GridView1.DataBind();
        Label1.Text = "總筆數:" + GridView1.Rows.Count;
    }
}


顯示結果


image


 


有分頁的話,直接用SqlDataSource去取,在onselected事件中取得




<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewPage.aspx.cs" Inherits="GridViewPage" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    <div>
        <asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="2">
        </asp:GridView>
    </div>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:DBConnection %>" 
        onselected="SqlDataSource1_Selected"></asp:SqlDataSource>
    </form>
</body>
</html>




using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class GridViewPage : System.Web.UI.Page
{
 
    protected void Page_Load(object sender, EventArgs e)
    {
        
        
        if (!IsPostBack)
        {
            bindgv();
        }
    }
 
    protected void bindgv()
    {
        string str = "select EmployeeID,LastName,FirstName,Title from Employees ";
        SqlDataSource1.SelectCommand = str;
        GridView1.DataSource = SqlDataSource1;
        GridView1.DataBind();
    }
    protected void SqlDataSource1_Selected(object sender, SqlDataSourceStatusEventArgs e)
    {
        Label1.Text = "總筆數:" + e.AffectedRows;
    }
}


其範例結果顯示


image











 


利用SqlDataSource取得資料筆數,範例用一button去取得資料數




<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewPage.aspx.cs" Inherits="GridViewPage" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    <asp:Button ID="btnShowGVCount"
        runat="server" Text="顯示總筆數" onclick="btnShowGVCount_Click" />
    <div>
        <asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="2">
        </asp:GridView>
    </div>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:DBConnection %>" 
        onselected="SqlDataSource1_Selected"></asp:SqlDataSource>
    </form>
</body>
</html>


這邊要注意的是這樣取得資料的方式,必須要讓SqlDataSource進行連結,也就是我在


Page_Load的時候都進行連結,這樣才會讀取到。



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
 
public partial class GridViewPage : System.Web.UI.Page
{
 
    protected void Page_Load(object sender, EventArgs e)
    {
 
        bindgv();
    }
 
    protected void bindgv()
    {
        string str = "select EmployeeID,LastName,FirstName,Title from Employees ";
        SqlDataSource1.SelectCommand = str;
        GridView1.DataSource = SqlDataSource1;
        GridView1.DataBind();
    }
    protected void SqlDataSource1_Selected(object sender, SqlDataSourceStatusEventArgs e)
    {
        //Label1.Text = "總筆數:" + e.AffectedRows;
    }
    protected void btnShowGVCount_Click(object sender, EventArgs e)
    {
        DataView view = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
        int count = view.Count; //(資料總筆數)
        Label1.Text = "總筆數:" + count;
        view.Dispose();
    }
}

顯示結果


image