Struts2+bootstrap-fileinput+poi implement read Excel file to database

Source: Internet
Author: User

//JS Code
functionInitupload () {$ ("#uploadfile"). Fileinput ({language:' En ',//Set LanguageUploadurl: $ ("body"). attr ("Data-url") + "/permission/roleupload!upload.action",//Address to uploadAllowedfileextensions: [' xls ', ' xlsx '],//received file suffix //uploadextradata:{"id": 1, "fileName": ' 123.mp3 '},Uploadasync:true,//default Asynchronous UploadShowupload:true,//whether to display the upload buttonShowremove:true,//Show Remove buttonShowpreview:true,//whether to show previewShowcaption:false,//whether to show titleBrowseclass: "Btn btn-primary",//button StyleDropzoneenabled:false,//whether to display the drag area //minimagewidth:50,//minimum width of picture //minimageheight:50,//Minimum height of the picture //maximagewidth:1000,//Maximum width of a picture //maximum height of the maximageheight:1000,//picture //maxfilesize:0,//Unit is KB, if 0 means no limit to file size //minfilecount:0,Maxfilecount:10,//indicates the maximum number of files allowed to upload simultaneouslyEnctype: ' Multipart/form-data ', Validateinitialcount:true, Previewfileicon:"<i class= ' Glyphicon glyphicon-king ' ></i>", Msgfilestoomany:"The number of files selected for upload ({n}) exceeds the maximum allowable value {m}! ", });}

JSP code

<!--file Upload--

<label class= "Control-label" > Please select the Excel file to import:</label>
<input type= "File" Name= "Uploadfiles" id= "UploadFile" class= "file-loading"/>
<s:fielderror></s:fielderror>

Background Action Code

     Publicstring Upload () {string Savepath=servletactioncontext.getservletcontext (). Getrealpath ("/static/upload/"); File Uploaddir=NewFile (Savepath); if(!uploaddir.exists ())        {Uploaddir.mkdirs (); } SimpleDateFormat SDF=NewSimpleDateFormat ("YyyyMMdd"); String Ymd=sdf.format (NewDate ()); Savepath+ = "/" +ymd+ "/"; File Dirfile=NewFile (Savepath); if(!dirfile.exists ())        {Dirfile.mkdirs (); }        if( This. uploadfiles!=NULL){             for(intI=0;i<uploadfiles.size (); i++) {String Fileext=uploadfilesfilename.get (i). substring (Uploadfilesfilename.get (i). LastIndexOf (".") +1). Trim (). toLowerCase (); List<string>arr=arrays.aslist (Extmap.split (",")); if(!arr.contains (Fileext)) {                    Super. Addactionerror ( This. Uploadfilesfilename.get (i) + "Incorrect file type! Only the "+extmap+" format is allowed. "); Continue; } SimpleDateFormat sdfforfilename=NewSimpleDateFormat ("Yyyymmddhhmmss"); String NewName=sdfforfilename.format (NewDate ()) + "_" +NewRandom (). Nextint (1000) + "." +Fileext; File DestFile=NewFile (dirfile,newname); Try{fileutils.copyfile (Uploadfiles.get (i), destfile); List&LT;LIST&LT;STRING&GT;&GT;ROLES=EXCELUTIL.READXLSX (savepath+newName);  for(list<string>row:roles) {Role Role=NewRole (); Role.setrolename (Row.get (1));                    Rolebiz.insert (role); }                } Catch(Exception e) {Super. Addactionerror ( This. Uploadfilesfilename.get (i) + "Upload failed! "+e.getmessage ()); Continue; }}} System.out.println ("Save path:" +Savepath); returnSUCCESS; }

Background POI parsing Excel code

 Public classExcelutil { Public StaticList<list<string>>readxlsx (String path) {List<List<String>> result=NewArraylist<list<string>>(); Try{InputStream input=NewFileInputStream (path); Xssfworkbook Workbook=NewXssfworkbook (input);  for(Xssfsheet xssfsheet:workbook) {if(xssfsheet==NULL){                    Continue; }                 for(intRownum=1;rownum<=xssfsheet.getlastrownum (); rownum++) {Xssfrow row=Xssfsheet.getrow (RowNum); intmincellnum=Row.getfirstcellnum (); intmaxcellnum=Row.getlastcellnum (); List<string>rowlist=NewArraylist<string>();  for(inti=mincellnum;i<maxcellnum;i++) {Xssfcell cell=Row.getcell (i); if(cell==NULL){                            Continue;                    } rowlist.add (Cell.tostring ());                } result.add (Rowlist); }            }        } Catch(FileNotFoundException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }        returnresult; }         Public StaticList<list<string>>Readxls (String path) {List<List<String>> result=NewArraylist<list<string>>(); Try{InputStream input=NewFileInputStream (path); Hssfworkbook Workbook=NewHssfworkbook (input);  for(intNumsheet=0;numsheet<workbook.getnumberofsheets (); numsheet++) {Hssfsheet sheet=Workbook.getsheetat (Numsheet); if(sheet==NULL){                    Continue; }                 for(intRownum=1;rownum<=sheet.getlastrownum (); rownum++) {Hssfrow row=Sheet.getrow (RowNum); intmincellnum=Row.getfirstcellnum (); intmaxcellnum=Row.getlastcellnum (); List<String> rowlist=NewArraylist<string>();  for(inti=mincellnum;i<maxcellnum;i++) {Hssfcell cell=Row.getcell (i); if(cell==NULL){                            Continue;                    } rowlist.add (Getstringval (cell));                } result.add (Rowlist); }            }        } Catch(FileNotFoundException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }        returnresult; }    Private StaticString getstringval (Hssfcell cell) {Switch(Cell.getcelltype ()) { CaseCell.cell_type_boolean:returnCell.getbooleancellvalue ()? "TRUE": "FALSE";  CaseCell.cell_type_formula:returnCell.getcellformula ();  CaseCell.CELL_TYPE_NUMERIC:cell.setCellType (cell.cell_type_string); returnCell.getstringcellvalue ();  Casecell.cell_type_string:returnCell.getstringcellvalue (); default:            return NULL; }    }}

Struts2+bootstrap-fileinput+poi implement read Excel file to database

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.