前阵子,项目中的一小模块,需要加上数据导入的功能。由于项目有好几个地方需要用到excel的数据导入。因此,当时就想了将excel导入封装成一公共组件,由于不同的excel数据导入,具体入库操作不同。因此,此组件提供对导入的数据的读取。具体不同的入库操作,在具体实现类中进行!
于是得出了 excel数据导入的抽象类
直接上代码:
读取excel方法
public List<List<Object>> readFormExcel(File file, int startRow, int startColumn) throws Exception { List<List<Object>> list = new ArrayList<List<Object>>(); Workbook workbook = null; if (file.getName().toUpperCase().endsWith(".XLS")) { workbook = createWorkBook(file); } else { workbook = createWorkbook2007(file); } Sheet sheet = workbook.getSheetAt(0); if (sheet == null) { throw new IllegalArgumentException("导入的数据必须是放要第一个工作表"); } int rowNumbers = sheet.getLastRowNum(); if (startRow > rowNumbers) { throw new IllegalArgumentException("起始行数大于导入的数据最大行数"); } int headColumnCount = sheet.getRow(0).getLastCellNum(); for (int i = startRow; i <= rowNumbers; i++) { Row row = sheet.getRow(i); if (row == null) { continue; } int columnNumber = row.getLastCellNum(); if (columnNumber < headColumnCount) { columnNumber = headColumnCount; // ,如果有表头有3列,另一行有2列,则读到2列时,最后列为2列.而不是3列.为数据完整性..方便做循环,将之改为与表头相同列 } List<Object> cellList = new ArrayList<Object>(); for (int j = startColumn; j < columnNumber; j++) { Cell cell = row.getCell(j); if (cell == null) { cellList.add(""); continue; } Object value = null; switch (cell.getCellType()) { case Cell.CELL_TYPE_BLANK: { value = ""; cellList.add(value); break; } case Cell.CELL_TYPE_FORMULA: { value = cell.getCellFormula(); cellList.add(value); break; } case Cell.CELL_TYPE_NUMERIC: { if (workbook instanceof HSSFWorkbook) { if (HSSFDateUtil.isCellDateFormatted(cell)) { value = cell.getDateCellValue(); cellList.add(value); } else { value = cell.getNumericCellValue(); cellList.add(value); } } else { if (DateUtil.isCellDateFormatted(cell)) { value = cell.getDateCellValue(); cellList.add(value); } else { value = cell.getNumericCellValue(); cellList.add(value); } } break; } case Cell.CELL_TYPE_STRING: { value = cell.getRichStringCellValue().getString(); cellList.add(value); break; } case Cell.CELL_TYPE_BOOLEAN: { value = cell.getBooleanCellValue(); cellList.add(value); break; } default: { value = cell.getRichStringCellValue().getString(); cellList.add(value); break; } } } list.add(cellList); } return list; }
客户端调用方法
/** * * @param file * execute文件 * @param startRow * 起始行 * @param startColumn * 起始列 * @param requestData * 客户端请求的数据 * @return 返回导入的行数 * @throws Exception */ public int executeDataImport(File file, int startRow, int startColumn, Map<String, Object> requestData) throws Exception { String text = file.getName(); List<List<Object>> importDatas = readFormExcel(file, startRow, startColumn); if (importDatas == null || importDatas.size() == 0) { return 0; } int resultCount = processBatchData(importDatas, requestData); return resultCount; }
实际入库抽象方法
/** * * @param importDatas * excel数据 * @param requestData * 客户端请求数据 * @return */ public abstract int processBatchData(List<List<Object>> importDatas, Map<String, Object> requestData);