Java +EASYUI+SPRINGMVC Implementation excle Import and export (top)

Source: Internet
Author: User

Objective

    introduced the development environment of the project first, With java development language for development, foreground ui easyui frame, followed by springmvc EJB combined to develop, the entire project management using the maven management, server with jboss6.2.0 Enterprise Edition.

Body

Configuration

    for Span lang= "en-US" style= "Font-family:calibri" >excel To upload a file we first introduce the commons-fileupload .jar package due to our project adoption maven for project management, so for jar The introduction of the package is in pom.xml commons-fileupload .jar


<pre name= "code" class= "HTML" ><dependency><groupId>commons-fileupload</groupId>< Artifactid>commons-fileupload</artifactid><version>1.3.1</version></dependency>


because of the background codeExcelutilthe project where the tool class is located is no longer currentWebproject, and inItoo-exam-tooproject, so we need toExcelutilwhere the tool class residesItoo-exam-tooproject is introduced, which ismavenof thePom.xmlfiles are addedItoo-exam-toothe project depends on:

<dependency><groupId>com.tgb</groupId><artifactId>itoo-exam-tool</artifactId> <version>0.0.1-SNAPSHOT</version></dependency>



Next Springmvc configuration file also needs to be configured, so that the foreground file can be parsed and uploaded to the background:

<!--Springmvc Upload a file, you need to configure the Multipartresolver processor--><bean id= "Multipartresolver" class= " Org.springframework.web.multipart.commons.CommonsMultipartResolver "><property name=" defaultencoding "value = "UTF-8"/><!--specifies that the total size of the uploaded file cannot exceed 10485760000B. Note the limitations of the Maxuploadsize property are not for individual files, but for the sum of the capacity of all Files--><property name= "maxuploadsize" value= "10485760000" ></ Property><property name= "maxinmemorysize" value= "40960" ></property></bean>


Specific Implementation

Excel the import we can decompose, including three steps:

1. uploading Excel files

2. Read the data in the Excle file and convert the excle data into a list collection

3. storing The list collection in a database

First we start looking at our front desk Easyui Upload excle The code of the file, using a form Form , the form contains a single Easyui the control that uploads the file Easyui-filebox :

<form id= "Questiontypesmanage"  method= "post" enctype= "Multipart/form-data" >   Select File: <input id= " Uploadexcel "Name=" Uploadexcel "class=" Easyui-filebox "style=" width:200px "data-options=" prompt: ' Please select File ... ' >      <a href= "#" class= "Easyui-linkbutton" style= "width:122px" onclick= "Uploadexcel ()" > Import question Bank </a>    


The foreground code is relatively simple, we use isEasyuiof theFileboxfor file uploads, it's important to note thatformform'senctypeproperty must be""Multipart/form-data",Next we useJSCode onexcleformat for basic validation, and then submit the file to the backgroundController,

<pre name= "Code" class= "JavaScript" >//import Excel function Uploadexcel () {//Get the full path of the uploaded file Var filename= $ (' #uploadExc   El '). Filebox (' GetValue ');  Get the question question var id= $ (' #questionType '). ComboBox (' GetValue ');     var questiontypes=encodeuri (ID); if (questiontypes! = "") {//Perform basic check if (filename== "") {$.messager.alert (' hint ', ' Please select Upload file!  ', ' info '); }else{//Check the file format for Var d1=/\.[ ^\.]  +$/.exec (FileName);     if (d1== ". xls") {//Get questions about Var id= $ (' #questionType '). ComboBox (' GetValue ') var Questiontypes=encodeuri (ID);    Get the course var Coursetypeid =$ (' #courseTypeId '). ComboBox (' GetValue ') var Coursetype=encodeuri (Coursetypeid); Submit Form document.getElementById ("Questiontypesmanage"). action= "${pagecontext.request.contextpath}/  Leadtoquestiontypes/leadinexcelquestionbank?questiontype= "+questiontypes+" &coursetype= "+courseType;     document.getElementById ("Questiontypesmanage"). Submit (); $.messager.alert (' hint ', ' Operation succeeded!     ', ' info '); }else{$.messager.alert (' hint ', ' Please select the XLS format file!     ', ' info '); $ (' #uploadExcel '). Filebox (' SetValue ', '); }}}else{$.messager.alert (' hint ', ' Please select course types!   ', ' info '); }  }


          after the front code is finished, we'll look at the nextControllerthe code, it is important to note that the front deskEasyuiof theFileboxof thenameThe name of the tag is passed to the background as a parameter, and the background is received by the foreground in the form of a stream.exclefiles that we useexcleTool class willexcleconverted intoListcollection, and finally theListThe collection is saved to the database. Let's look at the code implementation in the background:

/** * Import Question Bank Excel * * @param uploadexcel uploaded Excel file * * @param request Requests * * @param resposne response * * @throws unsupportedencodingexception Code Exception */@RequestMapping ("/leadinexcelquestionbank") publi C String Leadinexcelquestionbank (@RequestParam ("Uploadexcel") Commonsmultipartfile uploadexcel,httpservletrequest Request, HttpServletResponse response) throws Unsupportedencodingexception {//Get the questions and lessons from the reception string questiontype = Request.getparameter ("Questiontype"). Trim (); String Coursetype = Request.getparameter ("Coursetype"). Trim (); String Questiontypenameid = new String (Questiontype.getbytes ("iso-8859-1"), "Utf-8"); String Coursetypeid = new String (Coursetype.getbytes ("iso-8859-1"), "Utf-8"), inputstream in;boolean flag = false;try {// Gets the input stream of the foreground exce in = Uploadexcel.getinputstream ();//Gets the SheetName name string sheetname = Leadtoinquestiontypesmanagebean.getsheetname (Questiontypenameid);//Excel header is corresponding to the text, get the Excel header linkedhashmap< String, string> map = leadtoInquestiontypesmanagebean.getmapleadinexcelquestionbank (Questiontypenameid);//Get a combination of excle header arrays to prevent repetitive string[] Uniquefields =leadtoinquestiontypesmanagebean.getuniquefields (Questiontypenameid);//Gets the specific table class that needs to be imported class1= Leadtoinquestiontypesmanagebean.getclassname (Questiontypenameid);//excel conversion to the list collection List List = Null;try {// Call Excle Common class, convert to Listlist=excelutil.exceltolist (in, SheetName, Class1, map, uniquefields);} catch (Excelexception e) {e.printstacktrace ();} Save Entity Collection flag= Leadtoinquestiontypesmanagebean.leadinexcelquestionbank (Questiontypenameid, courseTypeId, list);} catch (IOException E1) {e1.printstacktrace ();}    System.out.println ("Execution Result:" + flag);  return "/leadtoquestiontypebank"; }


to here about excle The import is complete, about excle the export, and Excelutil the writing of the class, we continue the next article, please look forward to.

Java +EASYUI+SPRINGMVC Implementation excle Import and export (top)

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.