Java--POI技术处理Excel表 .xls ..xlsx两种格式的导入操作

举报
吾日三省贾斯汀 发表于 2021/09/10 00:48:44 2021/09/10
1.7k+ 0 0
【摘要】 一、说明 原文标题====SpringMvc+POI 处理Excel的导入操作功能==== 提到了ImportExcelUtil.java(Excel解析工具类)、UploadExcelControl.java (Spring控制器)、InfoVo.java(保存Excel数据对应的对象)、main.jsp(前端代码)以及配置文件we...

一、说明

原文标题====SpringMvc+POI 处理Excel的导入操作功能====

提到了ImportExcelUtil.java(Excel解析工具类)、UploadExcelControl.java (Spring控制器)、InfoVo.java(保存Excel数据对应的对象)、main.jsp(前端代码)以及配置文件web.xml、springmvc-servlet.xml(只做简单配置)、applicationContext-base.xml等。

本文只提Controller层、ImportExcelUtil工具类两部分,原文中这两部分导入功能可能会有一些小问题,具体可看原文网友评论。

我对原文导入部分代码进行略微修改后,导入功能已实际运用当中,没发现问题。

 

二、功能代码

首先先感谢下原文博主,然后上代码!!!!!
 

Controller层部分代码


         // 单号信息service
         @Autowired
         public OrderService orderService ;		//服务层改为自己的
     	/**
       * 一键上传Excel表信息
       *
       * @author Justin
       *
       */
     	@RequestMapping("order_add.action")
     	public @ResponseBody List<String> uploadadd(MultipartFile myFile, HttpServletResponse res) throws IOException {
      		List<String> errorList = new ArrayList<String>();
     		try {
      			ImportExcelUtil util = new ImportExcelUtil();
      			 InputStream input = null;
      			 List<List<Object>> lists = null;
     			 if(myFile.isEmpty()) {
      				 log.error("文件不存在!");
      			 }else {
     				if (errorList.size() == 0) {
      				 String fileName = myFile.getOriginalFilename();
      				 input = myFile.getInputStream();
      				 lists = util.getBankListByExcel(input, fileName);
      				 input.close();
     				 //循环将excel中的数据存入库
     				 for(int i=1; i<lists.size(); i++) {
      					 List<Object> list = lists.get(i);
      					 Order order= new Order();	//实体类,改为自己的
      					 order.setOrderNumber(util.getFormat(String.valueOf(list.get(0))));
      					 order.setAddress(util.getFormat(String.valueOf(list.get(1))));
      					 order.setPhone(util.getFormat(String.valueOf(list.get(2))));
      					 orderService.add(order);
      				 }
      			 }
      		}
      		} catch (Exception e) {
      			errorList.add("导入单号数据错误");
      			e.printStackTrace();
      			log.error("系统错误", e.fillInStackTrace());
      		}
     		return errorList;
      	}
  
 


ImportExcelUtil工具类


      package com.sale.util;
      import java.io.InputStream;
      import java.text.DecimalFormat;
      import java.text.SimpleDateFormat;
      import java.util.ArrayList;
      import java.util.Date;
      import java.util.List;
      import org.apache.poi.hssf.usermodel.HSSFDateUtil;
      import org.apache.poi.hssf.usermodel.HSSFWorkbook;
      import org.apache.poi.ss.usermodel.Cell;
      import org.apache.poi.ss.usermodel.Row;
      import org.apache.poi.ss.usermodel.Sheet;
      import org.apache.poi.ss.usermodel.Workbook;
      import org.apache.poi.xssf.usermodel.XSSFWorkbook;
      /**
       * excel文件上传Util
       *
      * @author Justin
      *
      */
      public class ImportExcelUtil {
     	private final static String Excel_2003 = ".xls"; //2003 版本的excel
     	private final static String Excel_2007 = ".xlsx"; //2007 版本的excel
     	/**
       * @param in
       * @param fileName
       * @param columNum 自定义列数
       * @return
       * */
     	public List<List<Object>> getBankListByExcel(InputStream in,String fileName) throws Exception{
      		List<List<Object>> list = null;
     		//创建Excel工作簿
      		Workbook work = this.getWorkbook(in, fileName);
     		if(work == null) {
     			throw new Exception("创建Excel工作簿为空!");
      		}
      		Sheet sheet = null;
      		Row row = null;
      		Cell cell = null;
      		list = new ArrayList<List<Object>>();
     		//遍历Excel中的所有sheet
     		for(int i = 0; i<work.getNumberOfSheets(); i++) {
      			sheet = work.getSheetAt(i);
     			if(sheet == null) {continue;}
     			//遍历当前sheet中的所有行
     			//int totalRow = sheet.getPhysicalNumberOfRows();//如果excel有格式,这种方式取值不准确
     			int totalRow = sheet.getPhysicalNumberOfRows();
     			for(int j = sheet.getFirstRowNum(); j<totalRow; j++) {
      				row = sheet.getRow(j);
     				if(row != null && !"".equals(row)) {
     					//获取第一个单元格的数据是否存在
      					Cell fristCell=row.getCell(0);
     					if(fristCell!=null){
     						//遍历所有的列
      						List<Object> li = new ArrayList<Object>();
     						//int totalColum = row.getLastCellNum();
     						for(int y = row.getFirstCellNum(); y<row.getLastCellNum(); y++) {
      							cell = row.getCell(y);
      							String callCal = this.getCellValue(cell)+"";
      							li.add(callCal);
      						}
      						list.add(li);
      					}
      				}
      			}
      		}
      		in.close();
     		return list;
      	}
     	/**
       * 描述:根据文件后缀,自动适应上传文件的版本
       * @param inStr,fileName
       * @return
       * @throws Exception
       * */
     	public Workbook getWorkbook(InputStream inStr,String fileName) throws Exception {
      		Workbook work = null;
      		String fileType = fileName.substring(fileName.lastIndexOf("."));
     		if(Excel_2003.equals(fileType)){
      			work=new HSSFWorkbook(inStr);//2003 版本的excel
      		}else if(Excel_2007.equals(fileType)) {
      			work=new XSSFWorkbook(inStr);//2007 版本的excel
      		}else {
     			throw new Exception("解析文件格式有误!");
      		}
     		return work;
      	}
     	/**
       * 描述:对表格中数值进行格式化
       * @param cell
       * @return
       * */
     	public Object getCellValue(Cell cell) {
      		Object value = null;
      		DecimalFormat df1 = new DecimalFormat("0");//格式化number,string字符
      		SimpleDateFormat sdf = new  SimpleDateFormat("yyy-MM-dd");//日期格式化
      		DecimalFormat df2 = new DecimalFormat("0.00");//格式化数字
     		if(cell !=null && !"".equals(cell)) {
     			switch (cell.getCellType()) {
     			case Cell.CELL_TYPE_STRING:
      				value = cell.getRichStringCellValue().getString();
     				break;
     			case Cell.CELL_TYPE_NUMERIC:
     				if("General".equals(cell.getCellStyle().getDataFormatString())) {
      					value = df1.format(cell.getNumericCellValue());
      				}else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())) {
      					value = sdf.format(cell.getDateCellValue());
      				}else if(HSSFDateUtil.isCellDateFormatted(cell)){
      					Date date = cell.getDateCellValue();
      					value = sdf.format(date);
      				}
     				else {
      					value = df2.format(cell.getNumericCellValue());
      				}
     				break;
     			case Cell.CELL_TYPE_BOOLEAN:
      				value = cell.getBooleanCellValue();
     				break;
     			case Cell.CELL_TYPE_BLANK:
      				value = "";
     				break;
     			default:
     				break;
      			}
      		}
     		return value;
      	}
     	public String getFormat(String str) {
     		if(str.equals("null")) {
      			str="";
     			return str;
      		}else{
     			return str;
      		}
      	}
     	public Integer getFormats(Integer str) {
     		if(str==null) {
      			str=0;
     			return str;
      		}else{
     			return str;
      		}
      	}
      }
  
 




附:

导入耗时测试代码(可忽略,根据需要往代码copy测试)


      //方法第一行代码
      long startTime = System.currentTimeMillis();
      //方法最后一行代码
      long endTime = System.currentTimeMillis();
      //long类型时间差,单位毫秒
      long timeLong = endTime - startTime;
      //long类型时间差转为double类型时间差,单位毫秒
      double timeDouble= Double.parseDouble(Long.toString(timeLong));
      System.out.println("该方法执行时间为" + timeDouble+ "毫秒,即" + timeDouble/(double)1000 + "秒");
  
 


我的1、2、3、4次测试结果分别为如下:
该POI技术导入excel表数据量为16880条到数据库耗时为11569.0毫秒,即11.569秒
该POI技术导入excel表数据量为16880条到数据库耗时为7451.0毫秒,即7.451秒
该POI技术导入excel表数据量为16880条到数据库耗时为7258.0毫秒,即7.258秒
该POI技术导入excel表数据量为16880条到数据库耗时为7478.0毫秒,即7.478秒

文章来源: blog.csdn.net,作者:吾日三省贾斯汀,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/JustinQin/article/details/78769789

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

作者其他文章

评论(0

抱歉,系统识别当前为高风险访问,暂不支持该操作

    全部回复

    上滑加载中

    设置昵称

    在此一键设置昵称,即可参与社区互动!

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。