GridView Selective export Excel Solution

Source: Internet
Author: User
Tags foreach fam httpcontext json

  This article mainly introduces the GridView Selective Export Excel solution, the need for friends can refer to the following

First, the needs of the analysis   in accordance with user needs, can be selected to export, has done all the export, this new demand again, but carefully think about it, all exported tens of thousands of data, the significance is not large, and the user needs to selectively export the data is the user needs. There is a need for solutions.   Any solution to any problem is more than one, the selective export of the GridView is the same, first the GridView binding is the database table data, select Export, we can also query the data needs, can be directly from the front of the GridView table to obtain data, the problem comes, How to determine the selected, how to select the main key of the information (or get the whole message) two direction, in the end which is more efficient which is more excellent?     II, solutions   one    1. The foreground gets the primary key information of the selected row, through JSON format, transmits to the backstage, after the background parsing, then obtains the data from the database, through the DataTable exports to excel   ⑴. Export the selected action   code as follows: <asp:button Id= "Export" runat= "cssclass=" Btn-lit "text=" to export the selected "onclientclick=" Return Getnumberexport () "onclick=" Export_ Click/>   ⑵. Foreground js, get the primary key of that information for the selected row, that is, the GridView has a column that is the primary key, gets all the primary keys to be saved in JSON format, and uploads to the server   code as follows: <script Type= "Text/javascript" >  function Getnumberexport () {  if (Exportcheck ()) { //Get element by GridView ID   var GV = document.getElementById ("Ctl00_contentplaceholder1_gridview"); //Get input html  of the GridView var MyCheck = gv.getelementsbytagname ("input"); //Defining a new array   var fam = The new Array ();  var hg;&nbSp var id; //Loop Detect CheckBox tab, get primary key information for each data   for (var i = 0; i < mycheck.length; i++) {  if (Mycheck[i].type = = ' checkbox ')//hidden  { //If checkbox is selected   if (mycheck[i].checked = = True) {  var numid = new Object () ;  HG = gv.rows (i + 1). Cells .innerhtml; //substring () method is used to extract characters between a string mediator and two specified subscripts.  //lastindexof () to fetch the string from the back to the specified character   HG = Hg.substring (Hg.lastindexof ("=") + 1, Hg.lastindexof ("")); / /Get the primary key   ID = gv.rows (i + 1) of a piece of data. Cells (1) .innerhtml;  Numid.number = hg;  numid.id = id;  Fam.push (numi d); } } } //$.ajaxsetup ({ //Async:false//Set to sync request  //}); //convert array to JSON type   var nid = Json.stringify (fam); //post Way to send data   $.post to the server ("List.aspx", {action: "Action", Numid:nid}, Functio N (Result) { }); }  else {  return false; } }  </script>   ⑶. Background resolution JSON, convert to DataTable, export to excel    code as follows: protectedvoid Page_Load (object sender, EventArgs e)   { //Determine if the server is receiving data correctly   if (request.params["Action"!=null)   { //Get foreground json  string numid = request.params["Numid"]. ToString ();  session["numid"] = numid; } } ///<summary> ///Selective export excel ///< /summary> ///<param name= "sender" ></param> ///<param name= "E" ></param>   protected void Export_click (object sender, EventArgs e)   {  Familyplanningfacade Familyplanningfacade = New Familyplanningfacade (); Instantiation of the IPPF appearance layer   DataSet dsallfamily = new DataSet ();  DataSet dsonefamily = new DataSet ();  dsallfamily = famil Yplanningfacade.getalllist (); Access to all family planning information   Dsallfamily.tables[0]. Rows.clear (); //parsing Json, introducing Newtonsoft.json and Newtonsoft.Json.Linq libraries   Jarray = (numidget) Jsonconvert.deserializeobject (session["Numid"). ToString ()); //traverse the desired value in JSON, retrieve a data by querying the database with this value, add the data to the new line   for (int i = 0; i < numIdget. Count; i++)   {  jobject numberget = (jobject) numidget[i];  string num = numberget["number"]. ToString ();  if (Num. Equals (""))   { //Get ID's key value   string id = numberget["id"]. ToString (); //enbasic.id = id; //Through the value of the ID (unique) query to a data   Dsexport = Famfacade. Selectexport (ID); //new row   DataRow row = Newdatatable.newrow (); //Add data   row to new row. ItemArray = Dsexport.tables[0]. Rows[0]. itemarray; //Add row to DataTable   NEWDATATABLE.ROWS.ADD (Row); } }  DataTable dtfamilyplanning = new DataTable (); Create a IPPF information datasheet   dtfamilyplanning = newdatatable.tables[0]; //Set table field   dtfamilyplanning = dtfamilyplanning. Defaultview.totable (False, new string[] {"ID", "name", "Sex"}); //Modify header information, in order for the exported Excel header to be kanji   Dtfamilyplanning. columns["ID"]. ColumnName = "number";  dtfamilyplanning. columns["Name"]. ColumnName = "name";  dtfamilyplanning. columns["Sex"]. ColumnName = "Gender"; //.... Other information in the table no longer writes  //new DatatObject of the Abletoexcel class   Datatabletoexcel dttoexcel = new Datatabletoexcel (); //Export data to excel  Dttoexcel.toexcel (dtfamilyplanning); }   ⑷. DataTable exported as an Excel method, a good way to stand on the shoulders of giants for me to use.     Code as follows: public void Toexcel (DataTable dt)   {  DataGrid dgexcel = new DataGrid ();  Dgexcel.dataso Urce = 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 ("&Lt;html>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.