/** * */ package com.ssh.file.util.export; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; 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; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.multipart.MultipartFile; import com.ssh.framework.exception.ServiceException; /** * @author spring * */ public class ImportExcelUtil { private Logger logger = LoggerFactory.getLogger(ImportExcelUtil.class); public List<List<CellVo>> checkExcel(MultipartFile file, String columns[]) throws ServiceException { Workbook workbook = null; InputStream fis = null; String fileName = file.getOriginalFilename(); try { // 解决Excel 03版本后兼容性问题 fis = file.getInputStream(); if (fileName.endsWith("xls")) { workbook = new HSSFWorkbook(fis); } else { workbook = new XSSFWorkbook(fis); } logger.debug(this.getClass().getSimpleName() + ".ImportExcel()"); int sheetCount = workbook.getNumberOfSheets(); // 获得工作薄(Workbook)中工作表(Sheet)的个数 List<List<CellVo>> list = new ArrayList<List<CellVo>>(); for (int i = 0; i < sheetCount; i++) { Sheet sheet = workbook.getSheetAt(i); // 获取第i张sheet表 int rownum = sheet.getLastRowNum(); // 获得最后一行的行数 for (int j = 1; j <= rownum; j++) { Row row = sheet.getRow(j); // 获取第i行 Iterator<Cell> it = row.iterator(); List<CellVo> cells = new ArrayList<CellVo>(); int l = 0; while (it.hasNext()) { Cell cell = it.next(); CellVo cellData = new CellVo(); if (cell != null) { cell.setCellType(Cell.CELL_TYPE_STRING); cellData.setValue(cell.getStringCellValue().trim()); } else { cellData.setValue(""); } cellData.setItem(columns[l++]); // 设置字段名称 cells.add(cellData); } if (list != null) list.add(cells); } } return list; } catch (Exception ex) { throw new ServiceException("打开Excel文件异常!", ex); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { logger.warn("文件关闭异常!", e); } } } } }
导入excel
最新推荐文章于 2021-05-10 17:11:39 发布