java工具类之excel文件上传解析工具类【版本1.0】

主要用于项目上传简单excel(如下图)的处理。
在这里插入图片描述

工具类:

import java.io.File;
import java.io.FileInputStream;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.formula.eval.ErrorEval;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.util.LocaleUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * excel文件上传解析工具类
 * 
 * @author zql
 * @version 1.0 on 2019-10-01
 * 该版本较为简单,只解析横向的第一个有标题行工作表的excel表格内容
 */
public class ExcelParseMapper {
	
	/**
	 * 解析方法
	 * 
	 * @param file excel文件对象
	 * @param type 用于横向读取或者纵向读取的判断,1为纵向,反之则为横向
	 * @param parseSheetCell 解析工作薄单元格内容的接口
	 */
	public void parseFirstSheet(File file, Integer type, ParseSheetCell parseSheetCell) {
		if (file != null) {
			if (file.getName().endsWith("xls")) {
				parseExcel2003(file, type, parseSheetCell);
			}
			if (file.getName().endsWith("xlsx")) {
				parseExcel2007(file, type, parseSheetCell);
			}
		}
	}
	
	/**
	 * 读取2003Excel
	 * 
	 * @param file excel文件对象
	 * @param type 用于横向读取或者纵向读取的判断,1为纵向,反之则为横向
	 * @param parseSheetCell 解析工作薄单元格内容的接口
	 */
	private void parseExcel2003(File file, Integer type, ParseSheetCell parseSheetCell) {
		try {
			FileInputStream fis = new FileInputStream(file);
			HSSFWorkbook wb = new HSSFWorkbook(fis);
			fis.close();

			HSSFSheet sheet = wb.getSheetAt(0);
			// 取得最后一行的行号
			int rowNum = sheet.getLastRowNum() + 1;

			HSSFRow rowTitle = sheet.getRow(0);
			int cellTitleNum = rowTitle.getLastCellNum();
			String[] title = new String[cellTitleNum];
			for (int i = 0; i < cellTitleNum; i++) {
				HSSFCell cell = rowTitle.getCell(Short.parseShort(i + ""));
				if (cell != null) {
					// 把类型先设置为字符串类型
					cell.setCellType(CellType.STRING);
					title[i] = cell.getStringCellValue();
				} else {
					title[i] = "";
				}
			}

			// 是否完成当前行的读取
			boolean isComplete;
			// 行循环开始
			for (int i = 1; i < rowNum; i++) {
				isComplete = false;
				// 得到Excel工作表的行
				HSSFRow row = sheet.getRow(i);
				for (int j = 0; j < cellTitleNum; j++) {
					// 得到Excel工作表指定行的单元格
					HSSFCell cell = row.getCell(j);
					if (j == (cellTitleNum - 1)) {
						isComplete = true;
					}
					parseSheetCell.setCurCell(title[j], i, isComplete, cell);
				}
			}

			wb.close();
		} catch (Exception e) {
			System.out.println("The error message:" + e.getMessage());
		}
	}
	
	/**
	 * 读取2007Excel
	 * 
	 * @param file excel文件对象
	 * @param type 用于横向读取或者纵向读取的判断,1为纵向,反之则为横向
	 * @param parseSheetCell 解析工作薄单元格内容的接口
	 */
	private void parseExcel2007(File file, Integer type, ParseSheetCell parseSheetCell) {
		try {
			FileInputStream fis = new FileInputStream(file);
			XSSFWorkbook wb = new XSSFWorkbook(fis);
			fis.close();

			XSSFSheet sheet = wb.getSheetAt(0);
			// 取得最后一行的行号
			int rowNum = sheet.getLastRowNum() + 1;

			XSSFRow rowTitle = sheet.getRow(0);
			int cellTitleNum = rowTitle.getLastCellNum();
			String[] title = new String[cellTitleNum];
			for (int i = 0; i < cellTitleNum; i++) {
				XSSFCell cell = rowTitle.getCell(Short.parseShort(i + ""));
				if (cell != null) {
					// 把类型先设置为字符串类型
					cell.setCellType(CellType.STRING);
					title[i] = cell.getStringCellValue();
				} else {
					title[i] = "";
				}
			}

			// 是否完成当前行的读取
			boolean isComplete;
			// 行循环开始
			for (int i = 1; i < rowNum; i++) {
				// 得到Excel工作表的行
				XSSFRow row = sheet.getRow(i);
				for (int j = 0; j < cellTitleNum; j++) {
					isComplete = false;
					// 得到Excel工作表指定行的单元格
					XSSFCell cell = row.getCell(j);
					if (j == (cellTitleNum - 1)) {
						isComplete = true;
					}
					parseSheetCell.setCurCell(title[j], i, isComplete, cell);
				}
			}

			wb.close();
		} catch (Exception e) {
			System.out.println("The error message:" + e.getMessage());
		}
	}

	/**
	 * 对单元格进行格式化
	 * 
	 * @param cell
	 * @return
	 */
	public Object getFormartType(Cell cell) {
		Object value;
		if (cell == null) {
			return "";
		}
		switch (cell.getCellType()) {
		case NUMERIC:
			if (DateUtil.isCellDateFormatted(cell)) {
				DateFormat sdf = new SimpleDateFormat("yyyy-MMM-dd", LocaleUtil.getUserLocale());
				sdf.setTimeZone(LocaleUtil.getUserTimeZone());
				value = sdf.format(cell.getDateCellValue());
			} else if ("@".equals(cell.getCellStyle().getDataFormatString())) {
				// 大数值读取时,会读到科学计数法形式,即后面带一个E,所以需要用new DecimalFormat("#")格式化
				// #号表示前缀或后缀出现不必要的0时,将其忽略,因此,要想读到几位,就在点号后加几个#号,本例中,#.########将可读到1至8位小数
				value = new DecimalFormat("#.########").format(cell.getNumericCellValue());
			} else if ("0.00".equals(cell.getCellStyle().getDataFormatString())) {
				value = new DecimalFormat("#.########").format(cell.getNumericCellValue());
			} else if ("General".equals(cell.getCellStyle().getDataFormatString())) {
				value = new DecimalFormat("#.########").format(cell.getNumericCellValue());
			} else {
				value = Double.toString(cell.getNumericCellValue());
			}
			break;
		case STRING:
			value = cell.getRichStringCellValue().toString();
			break;
		case FORMULA:
			// try catch为了防止取到计算公式,而取到计算结果
			try {
				value = String.valueOf(cell.getNumericCellValue());
			} catch (IllegalStateException e) {
				value = String.valueOf(cell.getCellFormula());
			}
			break;
		case BLANK:
			value = "";
			break;
		case BOOLEAN:
			value = cell.getBooleanCellValue() ? true : false;
			break;
		case ERROR:
			value = ErrorEval.getText(cell.getErrorCellValue());
			break;
		default:
			value = cell.toString();
		}
		return value;
	}
	
	/**
	 * 定义一个解析工作薄单元格内容的接口
	 */
	public interface ParseSheetCell {
		
		/**当前单元格的设置
		 * @param title 当前单元格所在列的标题
		 * @param curRowNum 当前单元格所在的行数
		 * @param isComplete 是否完成当前行的读取
		 * @param cell 当前单元格对象
		 */
		void setCurCell(String title, int curRowNum, boolean isComplete, Cell cell);
	}
	
}

测试类:

import java.io.File;

import org.apache.poi.ss.usermodel.Cell;

/**
 * @author zql
 * @version 1.0 on 2019-10-01
 *
 */
public class ExcelParseMapperTest {

	public static void main(String[] args) {
		File file = new File("d:\\excel\\测试数据.xlsx");
		File file2 = new File("d:\\excel\\测试数据.xls");
		ExcelParseMapper epm = new ExcelParseMapper();
		
		epm.parseFirstSheet(file, 0, new ParseSheetCell(){

			@Override
			public void setCurCell(String title, int curRowNum, boolean isComplete, Cell cell) {
				// 如果不使用工具类的getFormartType方法,就自行调用cell的方法,例如,cell.getStringCellValue()
				System.out.println(title + "--" + curRowNum + "--" + epm.getFormartType(cell) + "--" + isComplete);
			}
			
		});
		
		epm.parseFirstSheet(file2, 0, new ParseSheetCell(){

			@Override
			public void setCurCell(String title, int curRowNum, boolean isComplete, Cell cell) {
				//如果不使用工具类的getFormartType方法,就自行调用cell的方法,例如,cell.getStringCellValue()
				System.out.println(title + "--" + curRowNum + "--" + epm.getFormartType(cell) + "--" + isComplete);
			}
			
		});
	}
}

普通项目需要引入的包
poi-4.0.1.jar
poi-ooxml-4.0.1.jar
poi-ooxml-schemas-4.0.1.jar
commons-codec-1.11.jar
commons-collections4-4.3.jar
commons-math3-3.6.1.jar
xmlbeans-3.0.2.jar
commons-compress-1.18.jar
curvesapi-1.06.jar

maven项目依赖

<!-- poi -->
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi</artifactId>
	<version>4.0.1</version>
</dependency>
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi-ooxml</artifactId>
	<version>4.0.1</version>
</dependency>
发布了55 篇原创文章 · 获赞 25 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/mr_zql/article/details/100127510