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

一、说明

原文标题====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秒

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值