Upload excel from JSP and Insert excel into Database

  • 2021-07-18 08:44:14
  • OfStack

This article illustrates how JSP uploads excel and excel inserts into the database. Share it for your reference. The details are as follows:

This import excel is bound to pojo, (disadvantage) excle header must be the field value of pojo

1. html page:


<form id="myform" method="post" enctype="multipart/form-data">
<table>
 <tr>
  <td></td>
  <td>
   <input type="file" name="filepath" id="filepath"
    class="easyui-validatebox" required=true
    validType="equalLength[4]" missingMessage=" Documents !" value="" />
  </td>
 </tr>
 <tr align="center">
  <td colspan="2">
   <a id="btn1" class="easyui-linkbutton"
    data-options="iconCls:'icon-ok'" style="width: 60px"
    onclick="subForm();">OK</a>
   <a id="btn2" class="easyui-linkbutton"
    data-options="iconCls:'icon-cancel'" style="width: 60px"
    onclick="closeDig();">Cancel</a>
  </td>
 </tr>
</table>
</form>
<script type="text/javascript">
function subForm(){
 if($('#myform').form('validate')){
  /**
  var filepath = $("#filepath").val();
  alert(filepath);
  $.ajax({
   url: 'excleImport',
   typs: "post",
   data: {"filepath":filepath},
   async: false,
    error: function(request) {
    $('#dg').datagrid('reload');
    closeDig();
    $.messager.alert(" Operation tips ", " Operation successful! ","info");
    },
    success: function(data) {
     alert("success");
    }
  });
  **/
  var filepath = $("#filepath").val();
  var re = /(\\+)/g; 
  var filename = filepath.replace(re,"#"); 
  // Cut and intercept the path string  
  var one = filename.split("#"); 
  // Gets the last in the array 1 A, that is, the file name  
  var two = one[one.length-1]; 
  // Then intercept the file name to get the suffix name  
  var three = two.split("."); 
   // Gets the last of the intercepted 1 String, which is the suffix name  
  var last = three[three.length-1]; 
  // Add the suffix name type to be judged  
  var tp = "xls,xlsx"; 
  // Returns the position of the qualified suffix name in the string  
  var rs = tp.indexOf(last); 
  if(rs != -1){ 
   $("#myform").attr("action","excleImport");
   $("#myform").submit();
  }else{ 
   $.messager.alert(" Operation tips ", " The upload file you selected is not valid xls Or xlsx Files! ","error");
   return false; 
  } 
 } else {
  $.messager.alert(" Operation tips ", " Please select Upload File! ","error");
 }
}
</script>

2. java code:


@RequestMapping("/excleImport")
 public void excleImport(HttpServletRequest request) throws IOException, Exception {
  request.setCharacterEncoding("utf-8"); // Set code  
  // Get Disk File Entry Factory  
  DiskFileItemFactory factory = new DiskFileItemFactory(); 
  // Get the path to which the file needs to be uploaded  
  String path = request.getRealPath("/upload/kaku"); 
  File uploadDir = new File(path);
  if (!uploadDir.exists()) {
   uploadDir.mkdirs();
  }
  factory.setRepository(uploadDir); 
  // Settings   The size of the cache. When the capacity of the uploaded file exceeds the cache, it is directly put into the   Temporary storage room  
  factory.setSizeThreshold(1024*1024) ; 
  // High level API File upload processing  
  ServletFileUpload upload = new ServletFileUpload(factory); 
  // You can upload multiple files  
  List<FileItem> list = (List<FileItem>)upload.parseRequest(request); 
  for(FileItem item : list) 
  { 
   // Gets the property name of the form  
   String name = item.getFieldName(); 
   // If the retrieved   Form information is generic   Text   Information  
   if(item.isFormField()) 
   {      
    // Gets the string entered by the user   The name is very good, because the form submitted is   String type  
    String value = item.getString() ; 
    request.setAttribute(name, value); 
   } 
   // For incoming non-   Simple string processing   For example 2 Binary   Pictures, movies, these  
   else 
   { 
    /** 
     *  The following 3 Step, which mainly obtains   The name of the uploaded file  
     */ 
    // Get the pathname  
    String value = item.getName() ; 
    // Index to last 1 Backslash  
    int start = value.lastIndexOf("\\"); 
    // Interception   Upload the file   String name, plus 1 Yes   Remove the backslash,  
    String filename = value.substring(start+1); 
    // File suffix name 
    String prefix = filename.substring(filename.lastIndexOf(".") + 1);
    CardCenter cardCenter = new CardCenter();
    request.setAttribute(name, filename); 
    // Really write to disk  
    // The exception it throws   Use exception  Capture  
    //item.write( new File(path,filename) );// No. 1 3 Provided by the party  
    // Written manually  
    //OutputStream out = new FileOutputStream(new File(path,filename)); 
    InputStream in = item.getInputStream() ; 
    List<CardCenter> listFromExcel = (List<CardCenter>)ExelUtil.exportListFromExcel(in, prefix, cardCenter);
    this.cardCenterService.excleImport(listFromExcel);
    /*int length = 0 ; 
    byte [] buf = new byte[1024] ; 
    System.out.println(" Gets the total capacity of the uploaded file: "+item.getSize()); 
    // in.read(buf)  The data read each time is stored in  buf  Array  
    while( (length = in.read(buf) ) != -1) 
    { 
     // In  buf  Array   Fetch data   Write to   (Output stream) on disk  
     out.write(buf, 0, length); 
    } */
    in.close(); 
    //out.close(); 
   } 
  } 
}

3. java code:


public class ExelUtil { 
 // No. 1 1 Column start 
 private static int start = 0;
 // Finally 1 Column serial number 
 private static int end =0;
 public static String getSubString(String str){
  return str.substring(0,str.lastIndexOf("."));
 }
 /** 
  *  Method description: By Excel Documentary Sheet Export to List
  * @param file
  * @param sheetNum
  * @return
  * @throws IOException
  * @author 
  * @date 2013-3-25  Afternoon 10:44:26
  * @comment
  */
 public static List<?> exportListFromExcel(File file, String fileFormat,Object dtoobj) 
   throws IOException { 
  return exportListFromExcel(new FileInputStream(file), fileFormat,dtoobj); 
 } 
 /** 
  *  Method description: By Excel Streamy Sheet Export to List 
  * @param is
  * @param extensionName
  * @param sheetNum
  * @return
  * @throws IOException
  * @author 
  * @date 2013-3-25  Afternoon 10:44:03
  * @comment
  */
 public static List<?> exportListFromExcel(InputStream is,String fileFormat,Object dtoobj) throws IOException { 
  Workbook workbook = null; 
  if (fileFormat.equals(BizConstant.XLS)) { 
   workbook = new HSSFWorkbook(is); 
  } else if (fileFormat.equals(BizConstant.XLSX)) { 
   workbook = new XSSFWorkbook(is); 
  } 
  return exportListFromExcel(workbook,dtoobj); 
 } 
 /**
  *  Method description: By the specified Sheet Export to List
  * @param workbook
  * @param sheetNum
  * @return
  * @author 
  * @date 2013-3-25  Afternoon 10:43:46
  * @comment
  */
 private static List<Object> exportListFromExcel(Workbook workbook ,Object dtoobj) {
  List<Object> list = new ArrayList<Object>();
  String[] model = null;
  Sheet sheet = workbook.getSheetAt(0); 
  //  Analytic formula result  
  FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); 
  int minRowIx = sheet.getFirstRowNum(); 
  int maxRowIx = sheet.getLastRowNum(); 
  for (int rowIx = minRowIx; rowIx <= maxRowIx; rowIx++) { 
   Object obj = null;
   if(rowIx==minRowIx){
    start = sheet.getRow(rowIx).getFirstCellNum();
    end = sheet.getRow(rowIx).getLastCellNum();
   }
   Row row = sheet.getRow(rowIx); 
   StringBuilder sb = new StringBuilder();  
   for (int i = start; i < end; i++) { 
    Cell cell = row.getCell(new Integer(i)); 
    CellValue cellValue = evaluator.evaluate(cell); 
    if (cellValue == null) { 
     sb.append(BizConstant.SEPARATOR+null);
     continue; 
    } 
    //  After formula analysis, it only exists in the end Boolean , Numeric And String3 Data types, in addition to the Error It's over  
    //  The remaining data types, according to official documents, can be completely ignored  
    switch (cellValue.getCellType()) { 
    case Cell.CELL_TYPE_BOOLEAN: 
     sb.append(BizConstant.SEPARATOR + cellValue.getBooleanValue()); 
     break; 
    case Cell.CELL_TYPE_NUMERIC: 
     //  The date type here will be converted into a number type, which needs to be distinguished after discrimination  
     if (DateUtil.isCellDateFormatted(cell)) { 
      sb.append(BizConstant.SEPARATOR + cell.getDateCellValue()); 
     } else { 
      sb.append(BizConstant.SEPARATOR + cellValue.getNumberValue()); 
     } 
     break; 
    case Cell.CELL_TYPE_STRING: 
     sb.append(BizConstant.SEPARATOR + cellValue.getStringValue()); 
     break; 
    case Cell.CELL_TYPE_FORMULA: 
     break; 
    case Cell.CELL_TYPE_BLANK: 
     break; 
    case Cell.CELL_TYPE_ERROR: 
     break; 
    default: 
     break; 
    } 
   } 
   if(rowIx==minRowIx){
    String index = String.valueOf(sb);
    String realmodel =index.substring(1, index.length());
    model =realmodel.split(",");
   }else{
    String index = String.valueOf(sb);
    String realvalue =index.substring(1, index.length());
    String[] value =realvalue.split(",");
    // Field mapping 
    try {
     dtoobj =dtoobj.getClass().newInstance();
    } catch (InstantiationException e) {
     e.printStackTrace();
    } catch (IllegalAccessException e) {
     e.printStackTrace();
    }
    obj = reflectUtil(dtoobj,model,value);
    list.add(obj);
   }
  } 
  return list; 
 } 
 /**
  *  Method description: Field mapping assignment 
  * @param objOne
  * @param listName
  * @param listVales
  * @return
  * @author 
  * @date 2013-3-25  Afternoon 10:53:43
  * @comment
  */
 @SuppressWarnings("deprecation")
 private static Object reflectUtil(Object objOne, String[] listName,
   String[] listVales) {
  Field[] fields = objOne.getClass().getDeclaredFields();
  for (int i = 0; i < fields.length; i++) {
   fields[i].setAccessible(true);
   for (int j = 0; j < listName.length; j++) {
    if (listName[j].equals(fields[i].getName())) {
     try {
      if (fields[i].getType().getName().equals(java.lang.String.class.getName())) { 
       // String type
       if(listVales[j]!=null){
        fields[i].set(objOne, listVales[j]);
       }else{
        fields[i].set(objOne, "");
       }
      } else if (fields[i].getType().getName().equals(java.lang.Integer.class.getName())
        || fields[i].getType().getName().equals("int")) { 
       // Integer type 
       if(listVales[j]!=null){
        fields[i].set(objOne, (int)Double.parseDouble(listVales[j])); 
       }else{
        fields[i].set(objOne, -1); 
       }
      }else if(fields[i].getType().getName().equals("Date")){
       //date type
       if(listVales[j]!=null){
        fields[i].set(objOne, Date.parse(listVales[j]));
       } 
      }else if(fields[i].getType().getName().equals("Double")
        ||fields[i].getType().getName().equals("float")){
       //double
       if(listVales[j]!=null){
        fields[i].set(objOne, Double.parseDouble(listVales[j])); 
       }else{
        fields[i].set(objOne, 0.0); 
       }
      }
     } catch (IllegalArgumentException e) {
      e.printStackTrace();
     } catch (IllegalAccessException e) {
      e.printStackTrace();
     }
     break;
    }
   }
  }
  return objOne;
 }
}

I hope this article is helpful to everyone's JSP programming.


Related articles: