主页 > 编程资料 > JSP(JAVA) >
发布时间:2016-01-01 作者:网络 阅读:213次

本文实例讲述了JSP上传excel及excel插入至数据库的方法。分享给大家供大家参考。具体如下:

此导入excel是与pojo绑定的,(缺点)excle表头必须是pojo的字段值

1. html页面:

OK Cancel

2. java代码:

@RequestMapping("/excleImport")
 public void excleImport(HttpServletRequest request) throws IOException, Exception {
  request.setCharacterEncoding("utf-8"); //设置编码 
  //获得磁盘文件条目工厂 
  DiskFileItemFactory factory = new DiskFileItemFactory(); 
  //获取文件需要上传到的路径 
  String path = request.getRealPath("/upload/kaku"); 
  File uploadDir = new File(path);
  if (!uploadDir.exists()) {
   uploadDir.mkdirs();
  }
  factory.setRepository(uploadDir); 
  //设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室 
  factory.setSizeThreshold(1024*1024) ; 
  //高水平的API文件上传处理 
  ServletFileUpload upload = new ServletFileUpload(factory); 
  //可以上传多个文件 
  List list = (List)upload.parseRequest(request); 
  for(FileItem item : list) 
  { 
   //获取表单的属性名字 
   String name = item.getFieldName(); 
   //如果获取的 表单信息是普通的 文本 信息 
   if(item.isFormField()) 
   {      
    //获取用户具体输入的字符串 ,名字起得挺好,因为表单提交过来的是 字符串类型的 
    String value = item.getString() ; 
    request.setAttribute(name, value); 
   } 
   //对传入的非 简单的字符串进行处理 ,比如说二进制的 图片,电影这些 
   else 
   { 
    /** 
     * 以下三步,主要获取 上传文件的名字 
     */ 
    //获取路径名 
    String value = item.getName() ; 
    //索引到最后一个反斜杠 
    int start = value.lastIndexOf("\\"); 
    //截取 上传文件的 字符串名字,加1是 去掉反斜杠, 
    String filename = value.substring(start+1); 
    //文件后缀名
    String prefix = filename.substring(filename.lastIndexOf(".") + 1);
    CardCenter cardCenter = new CardCenter();
    request.setAttribute(name, filename); 
    //真正写到磁盘上 
    //它抛出的异常 用exception 捕捉 
    //item.write( new File(path,filename) );//第三方提供的 
    //手动写的 
    //OutputStream out = new FileOutputStream(new File(path,filename)); 
    InputStream in = item.getInputStream() ; 
    List listFromExcel = (List)ExelUtil.exportListFromExcel(in, prefix, cardCenter);
    this.cardCenterService.excleImport(listFromExcel);
    /*int length = 0 ; 
    byte [] buf = new byte[1024] ; 
    System.out.println("获取上传文件的总共的容量:"+item.getSize()); 
    // in.read(buf) 每次读到的数据存放在 buf 数组中 
    while( (length = in.read(buf) ) != -1) 
    { 
     //在 buf 数组中 取出数据 写到 (输出流)磁盘上 
     out.write(buf, 0, length); 
    } */
    in.close(); 
    //out.close(); 
   } 
  } 
}

3. java代码:

public class ExelUtil { 
 //第一列开始
 private static int start = 0;
 //最后一列序号
 private static int end =0;
 public static String getSubString(String str){
  return str.substring(0,str.lastIndexOf("."));
 }
 /** 
  * 方法描述:由Excel文件的Sheet导出至List
  * @param file
  * @param sheetNum
  * @return
  * @throws IOException
  * @author 
  * @date 2013-3-25 下午10:44:26
  * @comment
  */
 public static List exportListFromExcel(File file, String fileFormat,Object dtoobj) 
   throws IOException { 
  return exportListFromExcel(new FileInputStream(file), fileFormat,dtoobj); 
 } 
 /** 
  * 方法描述:由Excel流的Sheet导出至List 
  * @param is
  * @param extensionName
  * @param sheetNum
  * @return
  * @throws IOException
  * @author 
  * @date 2013-3-25 下午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); 
 } 
 /**
  * 方法描述:由指定的Sheet导出至List
  * @param workbook
  * @param sheetNum
  * @return
  * @author 
  * @date 2013-3-25 下午10:43:46
  * @comment
  */
 private static List exportListFromExcel(Workbook workbook ,Object dtoobj) {
  List list = new ArrayList();
  String[] model = null;
  Sheet sheet = workbook.getSheetAt(0); 
  // 解析公式结果 
  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; 
    } 
    // 经过公式解析,最后只存在Boolean、Numeric和String三种数据类型,此外就是Error了 
    // 其余数据类型,根据官方文档,完全可以忽略 
    switch (cellValue.getCellType()) { 
    case Cell.CELL_TYPE_BOOLEAN: 
     sb.append(BizConstant.SEPARATOR + cellValue.getBooleanValue()); 
     break; 
    case Cell.CELL_TYPE_NUMERIC: 
     // 这里的日期类型会被转换为数字类型,需要判别后区分处理 
     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(",");
    //字段映射
    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; 
 } 
 /**
  * 方法描述:字段映射赋值
  * @param objOne
  * @param listName
  * @param listVales
  * @return
  * @author 
  * @date 2013-3-25 下午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;
 }
}



希望本文所述对大家的JSP程序设计有所帮助。

关键字词: