GridView選擇性導(dǎo)出Excel解決方案

字號:


    這篇文章主要介紹了GridView選擇性導(dǎo)出Excel的解決方案,需要的朋友可以參考下
    一、需求分析
    首先根據(jù)用戶需求,可以進(jìn)行選擇性導(dǎo)出,之前已經(jīng)做了全部導(dǎo)出,這次新需求又來了,不過仔細(xì)想想也對,全部導(dǎo)出幾萬條數(shù)據(jù),意義并不大,而可選擇性的導(dǎo)出用戶需要的數(shù)據(jù)才是用戶需要的。有需求就有解決方法。
    任何問題的解決方法都不止一個,GridView的選擇性導(dǎo)出也一樣,首先GridView綁定的是數(shù)據(jù)庫的表數(shù)據(jù),選擇導(dǎo)出,我們也可以從數(shù)據(jù)中查詢需要的數(shù)據(jù),可以直接從前臺GridView表中取得數(shù)據(jù),問題來了,怎么判斷選中了,怎么后去選中的那條信息的主鍵(或者獲得整條信息)兩個方向,到底哪個效率哪個更優(yōu)?
    二、解決方法
    ONE
    1. 前臺獲取選中行的主鍵信息,通過JSON格式,傳送到后臺,后臺解析后,再從數(shù)據(jù)庫中取得數(shù)據(jù),通過DataTable導(dǎo)出到Excel
    ⑴. 導(dǎo)出所選操作
    代碼如下:
    <asp:Button ID="Export" runat="server" CssClass="btn-lit" Text="導(dǎo)出所選" OnClientClick="return getnumberExport()" OnClick="Export_Click"/>
    ⑵. 前臺JS,獲取選中行的那條信息的主鍵,也就是GridView要有一列是主鍵,獲取到所有的主鍵以JSON格式保存,然后傳到服務(wù)器
    代碼如下:
    <script type="text/javascript">
    function getnumberExport() {
    if (ExportCheck()) {
    //通過GridView ID獲取元素
    var gv = document.getElementById("ctl00_ContentPlaceHolder1_gridView");
    //獲取GridView的Input html
    var mycheck = gv.getElementsByTagName("input");
    //定義一個新數(shù)組
    var fam = new Array();
    var hg;
    var id;
    //循環(huán)檢測checkbox標(biāo)簽,獲取每條數(shù)據(jù)的主鍵信息
    for (var i = 0; i < mycheck.length; i++) {
    if (mycheck[i].type == 'checkbox')//hidden
    {
    //如果checkbox被選中
    if (mycheck[i].checked == true) {
    var numid = new Object();
    hg = gv.rows(i + 1).cells(20).innerHTML;
    //substring() 方法用于提取字符串中介于兩個指定下標(biāo)之間的字符。
    //LastIndexOf()倒取字符串,從后往前取到指定的字符
    hg = hg.substring(hg.lastIndexOf("=") + 1, hg.lastIndexOf("""));
    //獲取一條數(shù)據(jù)的主鍵
    id = gv.rows(i + 1).cells(1).innerHTML;
    numid.number = hg;
    numid.id = id;
    fam.push(numid);
    }
    }
    }
    //$.ajaxSetup({
    // async: false //設(shè)置為同步請求
    //});
    //將數(shù)組轉(zhuǎn)換成JSON類型
    var nid = JSON.stringify(fam);
    //post方式,向服務(wù)器傳送數(shù)據(jù)
    $.post("List.aspx", { Action: "action", numid: nid}, function (result) {
    });
    }
    else {
    return false;
    }
    }
    </script>
    ⑶. 后臺解析JSON,轉(zhuǎn)換成DataTable,導(dǎo)出到Excel
    代碼如下:
    protected void Page_Load(object sender, EventArgs e)
    {
    //判斷服務(wù)器是否正確接收數(shù)據(jù)
    if (Request.Params["Action"] !=null)
    {
    //獲取前臺的JSON
    string numid = Request.Params["numid"].ToString();
    Session["numid"] = numid;
    }
    }
    /// <summary>
    /// 選擇性導(dǎo)出EXCEL
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Export_Click(object sender, EventArgs e)
    {
    FamilyPlanningFacade familyPlanningFacade = new FamilyPlanningFacade(); //實例化計生外觀層
    DataSet dsAllFamily = new DataSet();
    DataSet dsOneFamily = new DataSet();
    dsAllFamily = familyPlanningFacade.GetAllList(); //獲得所有計生信息
    dsAllFamily.Tables[0].Rows.Clear();
    //解析JSON;需引入Newtonsoft.Json和Newtonsoft.Json.Linq庫
    JArray numidget = (JArray)JsonConvert.DeserializeObject(Session["numid"].ToString());
    //遍歷JSON中所需要的值,在通過這個值查詢數(shù)據(jù)庫獲取一條數(shù)據(jù),將數(shù)據(jù)加入新行
    for (int i = 0; i < numidget.Count; i++)
    {
    JObject numberget = (JObject)numidget[i];
    string num = numberget["number"].ToString();
    if (num.Equals(""))
    {
    //獲取id的鍵值
    string id = numberget["id"].ToString();
    //enBasic.ID = id;
    //通過id的值(唯一)查詢到一條數(shù)據(jù)
    dsExport = famfacade.SelectExport(id);
    //新建行
    DataRow row = newDataTable.NewRow();
    //向新建行中添加數(shù)據(jù)
    row.ItemArray = dsExport.Tables[0].Rows[0].ItemArray;
    //添加此行到DataTable中
    newDataTable.Rows.Add(row);
    }
    }
    DataTable dtfamilyplanning = new DataTable(); //創(chuàng)建計生信息數(shù)據(jù)表
    dtfamilyplanning = newDataTable.Tables[0];
    //設(shè)置表字段
    dtfamilyplanning = dtfamilyplanning.DefaultView.ToTable(false, new string[] { "ID", "name", "sex" });
    //修改表頭信息,為了使導(dǎo)出的Excel表頭為漢字
    dtfamilyplanning.Columns["ID"].ColumnName = "編號";
    dtfamilyplanning.Columns["name"].ColumnName = "姓名";
    dtfamilyplanning.Columns["sex"].ColumnName = "性別";
    //....表中其它信息不再細(xì)寫
    //新建DataTableToExcel類的對象
    DataTableToExcel dtToExcel = new DataTableToExcel();
    //導(dǎo)出數(shù)據(jù)到Excel
    dtToExcel.ToExcel(dtfamilyplanning);
    }
    ⑷. DataTable導(dǎo)出為Excel方法,很不錯的方法,站在巨人肩膀上為我所用。
    代碼如下:
    public void ToExcel(DataTable dt)
    {
    DataGrid dgExcel = new DataGrid();
    dgExcel.DataSource = dt;
    dgExcel.DataBind();
    HttpContext.Current.Response.Charset = "GB2312";
    string fileName = HttpUtility.UrlEncode(Guid.NewGuid().ToString(), System.Text.Encoding.UTF8);
    string str = "attachment;filename=" + fileName + ".xls";
    HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
    HttpContext.Current.Response.ContentType = "application/ms-excel";
    HttpContext.Current.Response.AppendHeader("content-disposition", str);
    StringWriter sw = new StringWriter();
    HtmlTextWriter htmTextWriter = new HtmlTextWriter(sw);
    dgExcel.RenderControl(htmTextWriter);
    HttpContext.Current.Response.Write("<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />");
    string style = "<style>td{mso-number-format:"@";}</style>";//防止導(dǎo)出excel時將以0開頭的全數(shù)字?jǐn)?shù)據(jù)的0去掉
    HttpContext.Current.Response.Write(style);
    HttpContext.Current.Response.Write("</head><body>");
    HttpContext.Current.Response.Write(sw);
    HttpContext.Current.Response.Write("</body></html>");
    HttpContext.Current.Response.End();
    }
    最后看一遍這個方法的整個實現(xiàn)過程:
    1 通過前臺獲取每個選中行的主鍵值,
    2 再將所有的鍵值保存到數(shù)組,數(shù)組轉(zhuǎn)化成JSON格式,
    3 在通過AJAX傳到后臺,
    4 后臺接收,解析JSON,取得JSON中的值,
    5 即可查詢數(shù)據(jù)庫獲得每條選中的數(shù)據(jù),將每行數(shù)據(jù)添加到DataTable中,
    6 最后導(dǎo)出為Excel。
    這個方法存在的問題:一.前臺獲取GridView選中行的主鍵值,通過innerHTML獲取主鍵的位置,也就是說如果HTML中主鍵位置變動,獲取主鍵代碼也要變,這個影響比較大,牽一發(fā)而動全身,這樣對系統(tǒng)的靈活性很有影響。
    再看第二個方法:
    TWO
    2. 后臺直接后去前臺GridView表的主鍵集合,獲取到后的實現(xiàn)和上一個方法類似。
    ⑴.導(dǎo)出所選操作
    代碼如下:
    <asp:Button ID="Export" runat="server" CssClass="btn-lit" Text="導(dǎo)出所選" OnClick="Export_Click"/>
    ⑵. 后臺button事件
    代碼如下:
    protected void Export_Click(object sender, EventArgs e)
    {
    DataSet dsAllFamily = new DataSet();
    DataSet dsOneFamily = new DataSet();
    FamilyPlanningFacade familyPlanningFacade = new FamilyPlanningFacade(); //實例化計生外觀
    dsAllFamily = familyPlanningFacade.GetAllList(); //獲得所有計生信息
    dsAllFamily.Tables[0].Rows.Clear();
    //循環(huán)gridView每行,查找CheckBox被選中的行
    foreach (GridViewRow msgRow in this.gridView.Rows)
    {
    //通過ID獲得所需要遍歷的CheckBox
    CheckBox chk = (CheckBox)msgRow.FindControl("DeleteThis");
    //判斷CheckBox是否被選中
    if (chk.Checked)
    {
    //獲取id的鍵值
    string id = msgRow.Cells[1].Text.ToString();
    dsOneFamily = familyPlanningFacade.GetList(id);
    //新建行
    DataRow row = dsAllFaamily.Tables[0].NewRow();
    //向新建行中添加數(shù)據(jù)
    row.ItemArray = dsOneFamily.Tables[0].Rows[0].ItemArray;
    //添加此行到DataTable中
    dsAllFamily.Tables[0].Rows.Add(row);
    }
    }
    if (dsAllFamily.Tables[0].Rows.Count == 0)
    {
    PersonalFiles.Web.MessageShow.MessageBox.Show(this, "請選擇需要導(dǎo)出的信息!");
    return;
    }
    DataTable dtfamilyplanning = new DataTable(); //創(chuàng)建計生信息數(shù)據(jù)表
    dtfamilyplanning = dsAllFamily.Tables[0];
    //設(shè)置表字段
    dtfamilyplanning = dtfamilyplanning.DefaultView.ToTable(false, new string[] { "ID", "name", "sex" });
    //修改表頭信息,為了使導(dǎo)出的Excel表頭為漢字
    dtfamilyplanning.Columns["ID"].ColumnName = "編號";
    dtfamilyplanning.Columns["name"].ColumnName = "姓名";
    dtfamilyplanning.Columns["sex"].ColumnName = "性別";
    //....表中其它信息不再細(xì)寫
    //新建DataTableToExcel類的對象
    DataTableToExcel dtToExcel = new DataTableToExcel();
    //導(dǎo)出數(shù)據(jù)到Excel
    dtToExcel.ToExcel(dtfamilyplanning);
    }
    這個方法的實現(xiàn)過程很簡單,直接在后臺獲取的是前臺GridView顯示的主鍵數(shù)據(jù),相比前臺傳JSON數(shù)據(jù)相對簡單了很多。
    Three
    3. 除了這兩種外還有更快速的方法,不需要重新查詢數(shù)據(jù)庫,而是直接從GridView中直接獲得顯示的數(shù)據(jù),不好的地方就是如果數(shù)據(jù)多人操作,而且更新頻繁,那直接從界面GridView獲取數(shù)據(jù)可能就不是最新的數(shù)據(jù)。
    復(fù)制代碼 代碼如下:
    protected void Export_Click(object sender, EventArgs e)
    {
    DataTable dsExport = new DataTable();
    //循環(huán)獲取gridView的每列,獲取表頭
    for(int i=0;i<this.gridView.Columns.Count-1;i++)
    {
    //將表頭信息添加到DataTable表頭
    dsExport.Columns.Add(this.gridView.Columns[i].HeaderText);
    }
    //循環(huán)gridView每行,查找CheckBox被選中的行
    foreach (GridViewRow msgRow in this.gridView.Rows)
    {
    //通過ID獲得所需要遍歷的CheckBox
    CheckBox chk = (CheckBox)msgRow.FindControl("DeleteThis");
    //判斷CheckBox是否被選中
    if (chk.Checked){
    //定義DataTable新行
    System.Data.DataRow dr = dsExport.NewRow();
    for (int i = 0; i < msgRow.Cells.Count-1; i++)
    {
    //獲取Cells數(shù)據(jù)
    dr[i] =msgRow.Cells[i].Text.ToString();
    }
    //添加新行到DataTable
    dsExport.Rows.Add(dr);
    }
    else
    {
    PersonalFiles.Web.MessageShow.MessageBox.Show(this, "請選擇需要導(dǎo)出的信息!");
    return;
    }
    }
    //移除DataTable中不需要的列
    dsExport.Columns.Remove("選擇");
    dsExport.Columns.Remove("詳細(xì)");
    dsExport.Columns.Remove("編輯");
    PersonalFiles.BLL.DataTableToExcel dtToExcel = new PersonalFiles.BLL.DataTableToExcel();
    //導(dǎo)出數(shù)據(jù)到Excel
    dtToExcel.ToExcel(dsExport);
    }
    三種方法上面寫的很清楚了,各有優(yōu)勢,根據(jù)實際項目的要求去選,學(xué)習(xí)過程必然是需要多接觸各種方法的實現(xiàn),之前寫過關(guān)于JSON的博客,就是沒用過,這次一個機(jī)會,學(xué)會了一個用法,感覺爽呀,反復(fù)學(xué)習(xí),不斷積累的過程,Heiheihei.