POI parsing excel file
1. Uploading files to the server2. Parse the Excel file and return the data collection3. Saving data to the server Frame ======spring+ (annotation-based)Springmvc and mybatis===== The first step:Front Desk:The JSP file uses the Uploadify
<div id= "Filequeue" ></div><input type= "file" id= "Brandfile" >
JS:
<script type= "Text/javascript" >//When the DOM (Document Object model) is loaded ready to be queried and manipulated, bind a function to execute. $ (document). Ready (function () {$ ("#brandFile"). Uploadify ({////foreground request background URL non-negligible parameter gets session ID ' Uploader ': ' <%=request.getcontextpath ()%>/brand/analyzexml.jhtml; ',//plugin with non-negligible parameters ' swf ': ' <%=request.getcontextpath ()%>/js/uploadify/uploadify.swf ',//Undo button's Picture path ' cancelimg ': ' <%=request.getcontextpath ()%>/js/uploadify/uploadify-cancel.png ',//If True is automatically uploaded after the file is False then it We have to manually click the Upload button ' auto ': true,//You can select multiple files at the same time by default to true cannot ignore ' multi ': false,//set upload The ID of the queue container DOM element, or false to automatically generate a queue container. ' Queueid ': false, ' Queueid ': ' Filequeue ',//Filetypedesc: ' *.xls;*.xlsx ',//file suffix description//fil Etypeexts: ' **.xls;*.xlsx ',//file suffix limit//To the Upload button set text ' ButtonText ': ' POI parsing ',//After uploading the queue disappears ' RemovecompletEd ': true,//After uploading the file disappears after the interval ' removetimeout ': 1,/* The size limit of uploaded files allows the maximum size of uploaded files. This value can be a number or a string. If it is a string, it accepts a unit (B, KB, MB, or GB). The default unit is KB you can set this value to 0, there is no limit, a single file does not allow more than the set value if more than Onselecterror time is triggered */' filesizelimit ': ' 100KB ', The name of the uploaded object is quite the name attribute in the file tag; ' Fileobjname ': ' Brandfile ',//number of uploaded files ' Uploadlimi T ': 1,//Returns an error when selecting file to trigger ' Onselecterror ': function (file, ErrorCode, errormsg) {SWITC H (errorCode) {Case-100:alert ("the number of uploaded files has exceeded the system limit" +$ (' # Brandfile '). Uploadify (' Settings ', ' queuesizelimit ') + "Files! "); Break Case-110:alert ("File [" +file.name+ "] size exceeds the system limit of" +$ (' #brandFile '). Uploadify ( ' Settings ', ' filesizelimit ') + "size! "); Break Case-120:alert ("File [" +file.name+ "] size is abnormal! "); Break Case-130:alert ("File [" +file.name+ "] type is incorrect! "); Break }},//upload to the server, the server returns the appropriate information to the ' onuploadsuccess ': function (file, data, response) { Alert ("Upload success"); alert (data); },//Trigger ' onuploaderror ' when outgoing on a single file: function (file, ErrorCode, ErrorMsg, errorstring) { Alert ("Upload failed"); } }); });</script>
Background: mybatis file upload with uploadify
@RequestMapping ("/analyzexml") public void Analyzexml (@RequestParam multipartfile brandfile,httpservletrequest Request,httpservletresponse response) { //upload XML file inputstream inputs; try { inputs = Brandfile.getinputstream (); String fileName = Brandfile.getoriginalfilename (); String Path = Getrealpath ("/uploadfile", request); SYSTEM.OUT.PRINTLN (path); String uploadfilename = fileutil.uploadfile (inputs, fileName, path); Parse XML file list<brand> brandlist = Analyzepoibrand.analyze_poi_brand (Getrealpath ("/uploadfile/" + Uploadfilename, request)); Import Database Brandservice.addbrandlistpoi (brandlist); Response Client outjoin ("{\" success\ ": True}", response), } catch (IOException e) { e.printstacktrace (); } }
Get upload file name: Fileutil UploadFile () method in the Package class
/*** * <pre>uploadfile (springmvc file Upload inputstream) * Modified NOTE: * @param inputs * @param fileName * @param folderp Ath * @return </pre> */public static string UploadFile (InputStream inputs, string fileName, String folderpath) {//upload Physical file to server hard disk Bufferedinputstream bis = null; FileOutputStream fos = null; Bufferedoutputstream BOS = NULL; String Uploadfilename = null;try {//build input buffer to increase the speed at which the file is read bis = new Bufferedinputstream (inputs);//Automatically create folder file = new Fi Le (FolderPath); if (!folder.exists ()) {folder.mkdirs ();} In order to ensure the uniqueness of the upload file, can be resolved through the UUID//in order to avoid Chinese garbled problem, the newly generated file name is composed of uuid+ the original filename suffix uploadfilename = uuid.randomuuid (). toString () + Getsuffix (fileName);//build the stream that writes the file is the output stream fos = new FileOutputStream (New File (folderpath+ "/" +uploadfilename));//build output buffer, Improve performance of write files Bos = new Bufferedoutputstream (FOS);//read data via input stream and write data to hard disk folder via output stream byte[] buffer = new byte[4096];//build 4k buffer int s = 0;while ((s=bis.read (buffer))! =-1) {bos.write (buffer, 0, s); Bos.flush ();}} catch (FileNotFoundException e) {//TODO auto-generatedCatch Blocke.printstacktrace ();} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();} finally {if (BOS! = null) {try {bos.close () ; bos = NULL;} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}} if (FOS = null) {try {fos.close (); fos = null;} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}} if (bis = null) {try {bis.close (); bis = null;} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}} if (inputs! = NULL) {try {inputs.close (); inputs = null;} catch (IOException e) {//TODO auto-generated catch blocke.prints Tacktrace ();}}} return uploadfilename;}
The original suffix name gets Getsuffix ()
private static string Getsuffix (string fileName) {int index = Filename.lastindexof ("."); String suffix = filename.substring (index); return suffix;}
Encapsulated Excel Q-key conversion to javabeanlist data
public class Analyzepoibrand {public static list<brand> Analyze_poi_brand (String brandpath) {list<brand> Brandmodellist = new arraylist<brand> (); try {//Gets the file to parse by path InputStream InputStream = new FileInputStream ( Brandpath);//Parse the file (convert the retrieved file to sheet table) Xssfworkbook WorkBook = new Xssfworkbook (inputstream);// Gets sheet starting from line 0th xssfsheet hssfsheet = workbook.getsheetat (0);//Get total number of rows int lastrownum = Hssfsheet.getlastrownum ();//must use "= Because of the number from the following table. Only then will a small number of data for (int i = 0; I <= lastrownum; i++) {Brand brand = new Brand (); Xssfrow hrow = Hssfsheet.getrow (i); String brandname = Hrow.getcell (0). Getstringcellvalue (); Brand.setbrandname (brandname); Brandmodellist.add (brand);}} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();} return brandmodellist;}}
The above is the use of my re-project
Combine projects (spring+ (annotation-based) Springmvc and mybatis+uploadify file uploads)--poi parse Excel files