java通过poi读取Excel

1、工具类

public class ExcelUtils {

public static final StringXLSX_FORMAT =".xlsx";

  public static final StringXLS_FORMAT =".xls";

  /**

    * Excel表头对应Entity属性 解析封装javabean

*

    * @param classzz    类

    * @param in        excel流

    * @param fileName  文件名

    * @param excelHeads excel表头与entity属性对应关系

    * @param         bean类型

    * @return 结果

    */

  public static ListreadExcelToEntity(Class classzz, InputStream in, String fileName, List excelHeads)throws Exception {

//是否EXCEL文件

      checkFile(fileName);

      //兼容新老版本

      Workbook workbook =getWorkBoot(in, fileName);

      //解析Excel并返回

      return readExcel(classzz, workbook, excelHeads);

  }

/**

    * 解析Excel转换为Entity

*

    * @param classzz  类

    * @param in      excel流

    * @param fileName 文件名

    * @param       bean类型

    * @return 结果

    */

  public static ListreadExcelToEntity(Class classzz, InputStream in, String fileName)throws Exception {

return readExcelToEntity(classzz, in, fileName, null);

  }

/**

    * 校验是否是Excel文件

    *

    * @param fileName 文件名称

    */

  private static void checkFile(String fileName) {

if (StringUtils.isBlank(fileName)) {

throw new CommonException("不是Excel文件!");

      }

if (!fileName.endsWith(XLSX_FORMAT) && !fileName.endsWith(XLS_FORMAT)) {

throw new CommonException("不是Excel文件!");

      }

}

/**

    * 兼容新老版Excel

*

    * @param in      输入流

    * @param fileName 文件名

    * @return workbook

*/

  private static WorkbookgetWorkBoot(InputStream in, String fileName)throws IOException {

if (fileName.endsWith(XLSX_FORMAT)) {

return new XSSFWorkbook(in);

      }else {

return new HSSFWorkbook(in);

      }

}

/**

    * 解析Excel

*

    * @param classzz    类

    * @param workbook  工作簿对象

    * @param excelHeads excel与entity对应关系实体

    * @param         类类型

    * @return 结果

    */

  private static ListreadExcel(Class classzz, Workbook workbook, List excelHeads)throws Exception {

List beans =new ArrayList<>();

      int sheetNum = workbook.getNumberOfSheets();

      for (int sheetIndex =0; sheetIndex < sheetNum; sheetIndex++) {

Sheet sheet = workbook.getSheetAt(sheetIndex);

        String sheetName = sheet.getSheetName();

        int firstRowNum = sheet.getFirstRowNum();

        int lastRowNum = sheet.getLastRowNum();

        Row head = sheet.getRow(firstRowNum);

        if (head ==null) {

continue;

        }

short firstCellNum = head.getFirstCellNum();

        short lastCellNum = head.getLastCellNum();

        Field[] fields = classzz.getDeclaredFields();

        a:

for (int rowIndex = firstRowNum +1; rowIndex <= lastRowNum; rowIndex++) {

Row dataRow = sheet.getRow(rowIndex);

            if (dataRow ==null) {

continue;

            }

T instance = classzz.newInstance();

            //非头部映射方式,默认不校验是否为空,提高效率

            if (CollectionUtils.isEmpty(excelHeads)) {

firstCellNum = dataRow.getFirstCellNum();

              lastCellNum = dataRow.getLastCellNum();

            }

for (int cellIndex = firstCellNum; cellIndex < lastCellNum; cellIndex++) {

Cell headCell = head.getCell(cellIndex);

              if (headCell ==null) {

continue;

              }

Cell cell = dataRow.getCell(cellIndex);

              // 每一行的第一列不能为空,否则不再读取下面剩下的列,转而读取下一行

              if (cell ==null || StringUtils.isBlank(cell.toString())) {

continue a;

              }

headCell.setCellType(CellType.STRING);

              String headName = headCell.getStringCellValue().trim();

              if (StringUtils.isEmpty(headName)) {

continue;

              }

ExcelHead eHead =null;

              if (!CollectionUtils.isEmpty(excelHeads)) {

for (ExcelHead excelHead : excelHeads) {

if (headName.equals(excelHead.getExcelName())) {

eHead = excelHead;

                        headName = eHead.getEntityName();

break;

                    }

}

}

for (Field field : fields) {

if (headName.equalsIgnoreCase(field.getName())) {

String methodName = MethodUtils.setMethodName(field.getName());

                    Method method = classzz.getMethod(methodName, field.getType());

                    if (isDateFiled(field)) {

Date date = cell.getDateCellValue();

                        if (date ==null) {

checkValueRequired(eHead, sheetName, rowIndex);

break;

                        }

method.invoke(instance, cell.getDateCellValue());

                    }else {

cell.setCellType(CellType.STRING);

                        String value = cell.getStringCellValue();

                        if (StringUtils.isEmpty(value)) {

checkValueRequired(eHead, sheetName, rowIndex);

break;

                        }

method.invoke(instance, convertType(field.getType(), value.trim()));

                    }

break;

                  }

}

}

beans.add(instance);

        }

}

return beans;

  }

/**

    * 是否日期字段

    *

    * @param field 属性列

    * @return 是否为日期格式

    */

  private static boolean isDateFiled(Field field) {

return (Date.class == field.getType());

  }

/**

    * 空值校验

    *

    * @param excelHead 表头

    */

  private static void checkValueRequired(ExcelHead excelHead, String sheetName, int rowIndex)throws Exception {

if (excelHead !=null && excelHead.isRequired()) {

throw new Exception("《" + sheetName +"》第" + (rowIndex +1) +"行:" + excelHead.getExcelName() +"不能为空!");

      }

}

/**

    * 类型转换

    *

    * @param classzz 类类型

    * @param value  值

    * @return 结果

    */

  private static ObjectconvertType(Class classzz, String value) {

if (Integer.class == classzz ||int.class == classzz) {

return Integer.valueOf(value);

      }

if (Short.class == classzz ||short.class == classzz) {

return Short.valueOf(value);

      }

if (Byte.class == classzz ||byte.class == classzz) {

return Byte.valueOf(value);

      }

if (Character.class == classzz ||char.class == classzz) {

return value.charAt(0);

      }

if (Long.class == classzz ||long.class == classzz) {

return Long.valueOf(value);

      }

if (Float.class == classzz ||float.class == classzz) {

return Float.valueOf(value);

      }

if (Double.class == classzz ||double.class == classzz) {

return Double.valueOf(value);

      }

if (Boolean.class == classzz ||boolean.class == classzz) {

return Boolean.valueOf(value.toLowerCase());

      }

if (BigDecimal.class == classzz) {

return new BigDecimal(value);

      }

return value;

  }

/**

    * 获取properties的set和get方法

    */

  static class MethodUtils {

private static final StringSET_PREFIX ="set";

      private static final StringGET_PREFIX ="get";

      private static Stringcapitalize(String name) {

if (name ==null || name.length() ==0) {

return name;

        }

return name.substring(0, 1).toUpperCase() + name.substring(1);

      }

public static StringsetMethodName(String propertyName) {

return SET_PREFIX +capitalize(propertyName);

      }

public static StringgetMethodName(String propertyName) {

return GET_PREFIX +capitalize(propertyName);

      }

}

/**

    * 生成Excel文件

    *

    * @param title  标题

    * @param headers 表头

    * @param column  数据集合

    * @param out    输出流

    */

  public static void generateExcel(String title, List headers, List> column, OutputStream out) {

if (headers ==null || column ==null) {

return;

      }

// 生成一个工作簿

      XSSFWorkbook workbook =new XSSFWorkbook();

      // 生成一个表格

      XSSFSheet sheet = workbook.createSheet(title);

      // 设置表格默认宽度为15字节

      sheet.setDefaultColumnWidth(15);

      // 产生表格标题行

      XSSFRow row = sheet.createRow(0);

      for (ExcelHead header : headers) {

XSSFCell cell = row.createCell(headers.indexOf(header));

        XSSFRichTextString text =new XSSFRichTextString(header.getExcelName());

        cell.setCellValue(text);

      }

// 填充数据

      int columnLength = column.size();

      for (int i =0; i < columnLength; i++) {

XSSFRow newRow = sheet.createRow(i +1);

        int length = column.get(i).size();

        for (int j =0; j < length; j++) {

XSSFCell cell = newRow.createCell(j);

            if (column.get(i).get(j) !=null) {

XSSFRichTextString columnName =new XSSFRichTextString(column.get(i).get(j));

              cell.setCellValue(columnName);

            }else {

XSSFRichTextString columnName =new XSSFRichTextString("");

              cell.setCellValue(columnName);

            }

}

}

try {

workbook.write(out);

      }catch (IOException e) {

throw new CommonException(e.getMessage());

      }

}

}

2、表头类

public class ExcelHead {

/**

    * Excel的表头名称

    */

  private StringexcelName;

  /**

    * 实体类属性名

    */

  private StringentityName;

  /**

    * 值必填

    */

  private boolean required =false;

  public ExcelHead(String excelName, String entityName, boolean required) {

this.excelName = excelName;

      this.entityName = entityName;

      this.required = required;

  }

public ExcelHead(String excelName, String entityName) {

this.excelName = excelName;

      this.entityName = entityName;

  }

public ExcelHead() {

}

你可能感兴趣的:(java通过poi读取Excel)