Various attempts by Java to export Excel

Source: Internet
Author: User
Tags set cookie

One of the most recent projects has been busy and has not had time to come to the new blog. Come here today to share a little problem with this project: Export Excel, I believe that the export of Excel is particularly common, there are many ways. Well, not much to say, directly to say that they encounter the various pits, I use the background is the POI export.

First of all, to say the demand, want the result is: "In line with the export criteria, the normal export, and pop-up prompts to let the user select, do not meet the export criteria, prompting the user can not export, but also in the user export the Export button is disabled, when the export is successful, then the Export button release"

  (I'll start with the whole process of thinking and the problems and solutions I have encountered, the dry goods will be posted below)

1, because our entire framework is accustomed to the asynchronous request, so at first I use the AJAX asynchronous request to export Excel, the results found not exported, the background program ran out, the log is also recorded, that is no Excel, let alone the Prompt box, the online search a lot, All say because Ajax and background communication with a character stream, the browser will not recognize you let him download, so blocked. (There are also small partners that use Ajax synchronization, also tried, no.) And filled up a hole .... )

2, then ready to use form form submit submit export, try, found can ah, very happy, but the problem again, form form submitted after the page actually refreshed, if not meet the export conditions how can I prompt the user? Do you want to jump to a new page? Feel this is not appropriate, because the user worked hard to enter a half-day condition, and then waited for a half-day background check (involving large data volume), the result is to run to another page with you said can not export, if it is I I will collapse, and so on a half-day not to say, grandma a leg, I entered a half-day This can't be tolerated. Well, this method does not, and then try to write the script from the background to the JSP page, but also found that do not execute, it is also puzzled, finally, the network has a small partner said with an iframe hidden domain, if not meet the conditions, and then the flow of the way to write back the problem, The final problem is solved (the code will be pasted together below).

3, this feeling is perfect, but the problem has not been completely solved, there is a problem of disabling the button, this problem to think very simple, the user click on the Export button to disable, the export after the completion of a flag, and then the button release, but the question came, this sign how to wear back? At first, I took it for granted that the same ending plan as the wrong one, I found out. Because, I exported Excel already to use the response stream, I could not write the sign back in the way of stream. This will cause me not to open the export button, the boss will not agree, overtime to find ways. Finally, let me find a solution to the idea, with a cookie to do. The concrete idea is: the user clicks the export, disables the button, then JS writes a timer rotation to find the cookie, after the file stream writes out, I will put a cookie in the browser, then this time JS can find this cookie, after finding, first will the timer to kill, Then the cookie to kill (a little ladder feeling, haha), and then the Export button to release.

(Although the problem has been solved, but the cookie and timer rotation still a bit unreliable, I hope we have a better solution, please enlighten us, thank you!!! )

Front Code:

<button class= "btn btn-sm btn-success" type= "Submit" id= "Detailep" onclick= "return Exportcheck (True);" Forbid= "yes" ><i class= "Icon-arrow-right bigger-110" ></i> export </button>
<script>$ (function () {var timer = "";}); /Click the Export button to disable the Export button $ ("#myForm"). Submit (function () {$ ("button[type=submit]", this). attr ("Disabled", "disabled");// After submitting the export time to check to see if there is a successful export timer = SetInterval (refrashpg,1000);}) The Export button's disable function Refrashpg () {if (GETCK () = "1") {clearinterval (timer); $ ("#detailEp") is released when the export is successful. REMOVEATTR ("Disabled ");} Delck ();} JS gets to Cookiefunction Getck () {Debuggervar CK = Document.cookie.split (";"); var ckname = ""; for (var i = 0;i<ck.length; i++) {var arr = ck[i].split ("="); if (arr[0] = = "Updtstatus") {ckname = Arr[1];break;}} return ckname;} JS Delete cookiefunction Delck () {var exp = new Date (); var name = "Updtstatus"; Exp.settime (Exp.gettime () -1000); var cval = ge TCk ();d Ocument.cookie = name + "=" + Cval + "; Expires= "+ exp.togmtstring ();}}
</script>

The background export code is the normal Java POI code:

1  Public voidBuildexceldocument (map<string, object>obj,string filename,string Type,2 httpservletrequest request, httpservletresponse response)3             throwsException {4Hssfworkbook Workbook =NewHssfworkbook (); 5         if("1". Equals (Type) {6list<map<string, object>> contentlist = (list<map<string, object>>) obj.get ("content"); 7Hssfsheet sheet = workbook.createsheet ("Sheet1");//the version of Excel created is 2003-2007 (xls) If it takes 2010, use Xssfsheet8Map<string,string> titlelist = (map<string, string>) obj.get ("title");9             //The key of the table header corresponds to the map key in the content ListmapTenList<string> Mkey =NewArraylist<string>(); One             //table Header's value header AList<string> Mvalue =NewArraylist<string>(); -Iterator<entry<string, string>> it =Titlelist.entryset (). iterator (); -              while(It.hasnext ()) { the@SuppressWarnings ("Rawtypes") -Java.util.Map.Entry Entry =(Java.util.Map.Entry) It.next (); - Mkey.add (String) Entry.getkey ()); - Mvalue.add (String) Entry.getvalue ()); +             } -Sheet.setdefaultcolumnwidth (( Short) 12);  +Hssfcell cell =NULL;  A              for(inti = 0;i<mvalue.size (); i++) { atCell = Getcell (sheet, 0, i); - SetText (cell, Mvalue.get (i)); -             } -              -              for( Shorti = 0; I < contentlist.size (); i++) {     -Hssfrow Sheetrow = Sheet.createrow (i+1);  inmap<string, object> entity =Contentlist.get (i);  -                  for(intj = 0;j< Mkey.size (); j + +) { to                         if(Entity.get (Mkey.get (j))instanceofString) { + Sheetrow.createcell (j). Setcellvalue ((String) Entity.get (Mkey.get (j))); -}Else if(Entity.get (Mkey.get (j))instanceofDouble) { the Sheetrow.createcell (j). Setcellvalue ((Double) Entity.get (Mkey.get (j))); *}Else if(Entity.get (Mkey.get (j))instanceofDate) { $String date =(Entity.get (Mkey.get (j))). ToString ();Panax NotoginsengSheetrow.createcell (j). Setcellvalue (date.substring (0, 10)); -}Else if(Entity.get (Mkey.get (j))instanceofBigDecimal) { the Sheetrow.createcell (j). Setcellvalue ((Entity.get (Mkey.get (j))). ToString ()); +                         } A                     } the                 } +             } -}Else if("2". Equals (Type) { $List<string[]> ContentList = (list<string[]>) obj.get ("content");  $Hssfsheet sheet = workbook.createsheet ("Sheet1");  -String[] Titlelist = (string[]) obj.get ("title"); -Hssfcell cell =NULL;  the              for(inti = 0;i<titlelist.length;i++) { -Cell = Getcell (sheet, 0, i);Wuyi SetText (cell, titlelist[i]); the             } -              for( Shorti = 0; I < contentlist.size (); i++) {     WuHssfrow Sheetrow = Sheet.createrow (i+1);  -string[] Detail =Contentlist.get (i); About                  for(intj = 0;j< detail.length;j++) { $ Sheetrow.createcell (j). Setcellvalue ((String) contentlist.get (i) [j]); -                 } -             } -         } A          +        //set the name of the client Excel when downloading theString filename = filename + ". xls";  -       //working with Chinese file names $filename =chineseutil.encodefilename (filename, request);  theResponse.setcontenttype ("Application/vnd.ms-excel;charset=utf-8");  theResponse.setheader ("Content-disposition", "attachment;filename=" +NewString (Filename.getbytes ("gb2312"), "Iso8859-1"));  theOutputStream Ouputstream =Response.getoutputstream (); the Workbook.write (Ouputstream);  -          in         //storing information in a cookie after exporting data theCookie status =NewCookie ("Updtstatus", "1"); theStatus.setmaxage (3600);//Set cookie Survival time 1 hours About Response.addcookie (status); the          the Ouputstream.flush ();  the Ouputstream.close ();  +}
View Code

Various attempts by Java to export Excel

Related Article

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.