java 文件上传Excel解析(表头不固定顺序,多sheet页)并插入数据库

文件上传返回存贮路径

/**
* 前端上传文件  返回存储路径
*
*/
   public static String fileUpload(HttpServletRequest request, HttpServletResponse response) throws FileUploadException, IOException{
		//文件路径
		String filepath = null;
		//文件名称
		String filename = null;
		
       response.setContentType("text/html;charset=utf-8");
       //创建DiskFileItemFactory工厂对象
       DiskFileItemFactory factory=new DiskFileItemFactory();
       
       //设置文件缓存目录,如果该文件夹不存在则创建一个
       File f=new File("E:\\TempFolder");
       if (!f.exists()){
           f.mkdirs();
       }
       factory.setRepository(f);
       //创建ServletFileUpload对象
       ServletFileUpload fileUpload=new ServletFileUpload(factory);
       //设置字符编码
       fileUpload.setHeaderEncoding("utf-8");
       // 解析request,将form表单的各个字段封装为FileItem对象
       List<FileItem> fileItems = fileUpload.parseRequest(request);
       //遍历List集合
       for (FileItem fileItem:fileItems) {
       	//判断是否为普通字段
           if (fileItem.isFormField()){
    		
           } else {
               //获取上传的文件名
               filename=fileItem.getName();
               //处理上传文件
               if(filename!=null&&filename!=""){
                   //保持文件名唯一
                   filename= UUID.randomUUID().toString()+"_"+filename;
                   String webpath="/upload/";
                   //创建文件路径
                   //String filepath=getServletContext().getRealPath(webpath+filename);
                   filepath = "E:/TempFolder"+webpath+filename;
                   //创建File对象
                   File file=new File(filepath);
                   //创建文件夹
                   file.getParentFile().mkdirs();
                   //创建文件
                   file.createNewFile();
                   //获取上传文件流
                   InputStream in=fileItem.getInputStream();
                   //使用 FileOutputStream打开服务器端的上传文件
                   FileOutputStream out=new FileOutputStream(file);
                   //流
                   byte[] bytes=new byte[1024];//每次读取一个字节
                   int len;
                   //开始读取上传文件的字节,并将其输出到服务器端的上传文件输出流中
                   while ((len=in.read(bytes))>0) {
                       out.write(bytes, 0, len);
                   }
                   in.close();
                   out.close();
                   fileItem.delete();
               }
           }
       }
	return filepath;
		
   }

解析表头不固定Excel 返回List集合

	因业务需求  每次上传表头顺序无法确定 ,没想到更好的方法     
采用表头名称固定  遍历后  添加到集合中  和数据库字段对应  得到固定的顺序
	 public static List<Map<String,String>> analysisExcel(String filepath) throws IOException{
	      List<Map<String,String>> list = new ArrayList<Map<String,String>>();

	      //String encoding = "GBK";
	      File excel = new File(filepath);
	      if (excel.isFile() && excel.exists()) {   //判断文件是否存在

	          String[] split = excel.getName().split("\\.");  //.是特殊字符,需要转义!!!!!
	          Workbook wb=null;
	          //根据文件后缀(xls/xlsx)进行判断
	          if ( "xls".equals(split[1])){
	              FileInputStream fis = new FileInputStream(excel);   //文件流对象
	              wb = new HSSFWorkbook(fis);
	          }else if ("xlsx".equals(split[1])){
	        	  FileInputStream fis = new FileInputStream(excel);  
	        	  wb = new XSSFWorkbook(fis);
	          }else {
	              return null;
	          }

	          //开始解析
	          Sheet sheet = wb.getSheetAt(0);     //读取sheet 0
	          
	          List<String> listBt = new ArrayList<String>();
	          //获得表头 此处只遍历表头
	          Row bt = sheet.getRow(0);
	          if (bt != null) {
	        	  int firstIndex = bt.getFirstCellNum();
                  int lastIndex = bt.getLastCellNum();  
                  for (int cellIndex = firstIndex; cellIndex < lastIndex; cellIndex++) {   			         
                       //遍历列
                	   String cell = bt.getCell(cellIndex).toString();
                	   //将表头遍历出  对应数据库中插入时对应的ID 得到对应的集合
                	   if(cell.equals("序号")){ listBt.add("ID");}
    
                	   
                  }
	          }
	          
	          int firstRowIndex = sheet.getFirstRowNum()+1;   //第一行是列名,所以不读
	          int lastRowIndex = sheet.getLastRowNum();
	          for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) {   //遍历行
	              Row row = sheet.getRow(rIndex);
	              if (row != null) {
	                  int firstCellIndex = row.getFirstCellNum();
	                  int lastCellIndex = row.getLastCellNum();
	                  Map<String,String> map = new HashMap<String, String>();
	                  for (int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex++) {   	  
	                  //遍历列
	                      Cell cell = row.getCell(cIndex);
	                      String key = listBt.get(cIndex);
	                      map.put(key, cell.toString());
	                  }
	                  list.add(map);                
	              }
	          }
	      } else {
	          //找不到指定文件
	      }
	     
		return list;

	  }

多sheet页解析

上传excel  用sheet页名称做数据库某一关键字段 ,将sheet页名称拼如集合中返回:
/**
 * 
 * @param filepath Excel地址
 * @param field excel表头对应数据库字段 插入sheet页名称专用
 * @return
 * @throws IOException
 */
 public static List<Map<String,String>> analysisExcel(String filepath,String[] field) throws IOException{
      List<Map<String,String>> list = new ArrayList<Map<String,String>>();

      //String encoding = "GBK";
      File excel = new File(filepath);
      if (excel.isFile() && excel.exists()) {   //判断文件是否存在

          String[] split = excel.getName().split("\\.");  //.是特殊字符,需要转义!!!!!
          Workbook wb=null;
          //根据文件后缀(xls/xlsx)进行判断
          if ( "xls".equals(split[1])){
              FileInputStream fis = new FileInputStream(excel);   //文件流对象
              wb = new HSSFWorkbook(fis);
          }else if ("xlsx".equals(split[1])){
        	  FileInputStream fis = new FileInputStream(excel);  
        	  wb = new XSSFWorkbook(fis);
          }else {
              return null;
          }
          int sheetCount = wb.getNumberOfSheets();
          
          for(int i = 0;i<sheetCount;i++){
        	  //开始解析
	          Sheet sheet = wb.getSheetAt(i);     //读取sheet 0
	          
	          String sheetName = sheet.getSheetName();//sheet页名称
	        
	          int firstRowIndex = sheet.getFirstRowNum()+1;   //第一行是列名,所以不读
	          int lastRowIndex = sheet.getLastRowNum();
	          for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) {   //遍历行
	              Row row = sheet.getRow(rIndex);
	              if (row != null) {
	                  int firstCellIndex = row.getFirstCellNum();
	                  int lastCellIndex = row.getLastCellNum();
	                  Map<String,String> map = new HashMap<String, String>();
	                  for (int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex++) {   	  
	                  //遍历列
	                      Cell cell = row.getCell(cIndex);
	                      map.put(field[cIndex], cell.toString());
	                  }
	                  map.put(field[lastCellIndex], sheetName);
	                  list.add(map);                
	              }
	          }
          	}
	      } else {
	          //找不到指定文件
	      }
     
	return list;

  }
  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值