文件上传下载(三) 读取Excel

应用:

public List<Demo> importExcel(@RequestParam(value = "file",required = false)MultipartFile file){
    List<Demo> list = new ArrayList<Demo>();
    InputStream ins = null;
    XSSFWorkbook xssfWorkbook = null;
    //定义工作表
    XSSFSheet sheet;
    try {
        ins=file.getInputStream();
        //定义工作簿
        workbook = new XSSFWorkbook(ins);
        // 默认取第一个子表
        sheet = workbook.getSheetAt(0);
        //默认第一行为标题行,index = 0
        XSSFRow row = sheet.getRow(0);
    } catch (Exception e) {
        System.out.println("Excel data file cannot be found!");
    }

    // 验证表头是否一致
    String[] headNames={"表头一","表头二"};
    for(int i=0;i<headNames.length;i++){
        if(row.getCell(i)==null)
            throw new BusinessException("导入失败:请使用正确导入模板!");
        if(!headNames[i].equals(ExcelUtil.getCellValue(row.getCell(i)).trim())){
            String now="";
        if(StringUtil.isBlank(ExcelUtil.getCellValue(row.getCell(i)).trim())) {
            now="空";
        }else {
            now=ExcelUtil.getCellValue(row.getCell(i)).trim();
        }
            throw new BusinessException("导入失败:excel工作表中表头行与给定模板不符:第"+(i+1)+"列应为"+headNames[i]+",实际为"+now);
        }
    }

    for (int j = 1; j <= sheet.getLastRowNum(); j++) {
        row = sheet.getRow(j);
        if (row == null) {
            list.add(null);
            continue;
        }
        Demo demo = new Demo();
        if (row.getCell(0) != null) {
            demo.setA(ExcelUtil.getCellValue(row.getCell(0)).trim());
        }else{
            demo.setA("");
        }
        if (row.getCell(1) != null) {
            demo.setB(ExcelUtil.getCellValue(row.getCell(1)).trim());
        }else{
            demo.setB("");
        }
        list.add(demo);
    }
    return list;

}

ExcelUtil:

// 简单的查检列类型
public static String getCellValue(HSSFCell cell) {
    String value = null;

    switch (cell.getCellType()) {
        case HSSFCell.CELL_TYPE_STRING:// 字符串
            value = cell.getRichStringCellValue().getString();
            break;
        case HSSFCell.CELL_TYPE_NUMERIC:// 数字 处理 .0的问题
            double db=cell.getNumericCellValue();
            long dd=(long) db;
            value = db==dd?dd+"":String.valueOf(db);
            break;
        case HSSFCell.CELL_TYPE_BLANK:
            value = "";
            break;
        case HSSFCell.CELL_TYPE_FORMULA:
            value = String.valueOf(cell.getCellFormula());
            break;
        case HSSFCell.CELL_TYPE_BOOLEAN:// boolean型值
            value = String.valueOf(cell.getBooleanCellValue());
            break;
        case HSSFCell.CELL_TYPE_ERROR:
            value = String.valueOf(cell.getErrorCellValue());
            break;
        default:
            break;
    }
    return value;
}

 

posted @ 2019-12-31 08:44  DarGi  阅读(185)  评论(0编辑  收藏  举报