The import excel file controller receiving layer poi
Use extension xls or xlsx format excel.
1.pom introduced
<!-- poi 操作Excel --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency>
2.ExcelImportUtil tools created
import com.guard.biz.common.util.excel.ExcelIn; import org.apache.commons.beanutils.BeanUtilsBean; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.reflect.FieldUtils; import org.apache.poi.hssf.usermodel.HSSFDateUtil; 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.ss.usermodel.WorkbookFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; / ** * @author Wei * @time 2019/10/29 * @Description excel import tools */ public class ExcelImportUtil<T> { private static final Logger log = LoggerFactory.getLogger(ExcelImportUtil.class); private static BeanUtilsBean beanUtilsBean = new BeanUtilsBean(); static { beanUtilsBean.getConvertUtils().register(new org.apache.commons.beanutils.converters.DateConverter(null), java.util.Date.class); } /** * Where the header names and the corresponding index of the columns, according to the corresponding value taken title */ private final Map<String, Integer> title_to_index = new HashMap<>(); /** * All fields annotated with ExcelIn */ private final List<Field> fields = new ArrayList<>(); /** * Statistical tables of rows and number of columns used to traverse the table */ private int firstCellNum = 0; private int lastCellNum = 0; private int firstRowNum = 0; private int lastRowNum = 0; private String sheetName; private Sheet sheet; public List<T> read(InputStream in, Class clazz) throws Exception { gatherAnnotationFields(clazz); configSheet(in); configHeader(); List rList = null; try { rList = read content (Clazz); } catch (IllegalAccessException e) { throw new Exception(e); } catch (InstantiationException e) { throw new Exception(e); } catch (InvocationTargetException e) { throw new Exception(e); } return rList; } private List readContent(Class clazz) throws IllegalAccessException, InstantiationException, InvocationTargetException { Object o = null; Row row = null; List<Object> rsList = new ArrayList<>(); Object value = null; for (int i = (firstRowNum + 1); i <= lastRowNum; i++) { o = clazz.newInstance(); row = sheet.getRow(i); Cell the Cell = null ; for (Field, Field: Fields) { // The annotations in the title, to take the column in the table corresponding to the value of the Integer = title_to_index.get column (field.getAnnotation (ExcelIn. Class ) .title ( )); IF (column == null ) { Continue ; } cell = row.getCell(column); value = getCellValue(cell); if (null != value && StringUtils.isNotBlank(value.toString())) { beanUtilsBean.setProperty(o, field.getName(), value); } } rsList.add(o); } return rsList; } Private void configSheet (the InputStream in) throws Exception { // Create the appropriate Workbook object file type are the try (Workbook WB = WorkbookFactory.create (in)) { getSheetByName(wb); } catch (FileNotFoundException e) { throw new Exception(e); } catch (IOException e) { throw new Exception(e); } } /** * Get the value corresponding to the ranks based sheet, and the head corresponding to a column value map */ private void configHeader() { this.firstRowNum = sheet.getFirstRowNum(); this.lastRowNum = sheet.getLastRowNum(); //第一行为表头,拿到表头对应的列值 Row row = sheet.getRow(firstRowNum); this.firstCellNum = row.getFirstCellNum(); this.lastCellNum = row.getLastCellNum(); for (int i = firstCellNum; i < lastCellNum; i++) { title_to_index.put(row.getCell(i).getStringCellValue(), i); } } /** * Get sheet according to sheet name * * @param workbook * @return * @throws Exception */ private void getSheetByName(Workbook workbook) throws Exception { int sheetNumber = workbook.getNumberOfSheets(); for (int i = 0; i < sheetNumber; i++) { String name = workbook.getSheetName(i); if (StringUtils.equals(this.sheetName, name)) { this.sheet = workbook.getSheetAt(i); return; } } the throw new new Exception ( "Name not found to excel in" + the this .sheetName + "The Sheet" ); } /** * According to custom annotations, get the table you want to import the sheet names and field names to be imported * * @Param clazz * @throws Exception */ private void gatherAnnotationFields(Class clazz) throws Exception { if (!clazz.isAnnotationPresent(ExcelIn.class)) { throw new Exception(clazz.getName() + "类上没有ExcelIn注解"); } ExcelIn ExcelIn = (ExcelIn) clazz.getAnnotation (ExcelIn. Class ); the this .sheetName = excelIn.sheetName (); // get all the fields defined in Field, [] = allFields FieldUtils.getAllFields (clazz); // get all field and store in a list for (Field, Field: allFields) { IF (. field.isAnnotationPresent (ExcelIn class )) { fields.add(field); } } IF (fields.isEmpty ()) { the throw new new Exception (clazz.getName () + "No ExcelIn comment field" ); } } private Object getCellValue(Cell cell) { if (cell == null) { return ""; } Object obj = null; switch (cell.getCellTypeEnum()) { case BOOLEAN: obj = cell.getBooleanCellValue(); break; case ERROR: obj = cell.getErrorCellValue(); break; case FORMULA: try { obj = String.valueOf(cell.getStringCellValue()); } catch (IllegalStateException e) { obj = numericToBigDecimal(cell); } break; case NUMERIC: obj = getNumericValue(cell); break; case STRING: String value = String.valueOf(cell.getStringCellValue()); value = value.replace(" ", ""); value = value.replace("\n", ""); value = value.replace("\t", ""); obj = value; break; default: break; } return obj; } Private Object getNumericValue (the Cell Cell) { // transaction date or time format IF (HSSFDateUtil.isCellDateFormatted (Cell)) { return cell.getDateCellValue (); } The else IF (. Cell.getCellStyle () getDataFormat () == 58 ) { // handle custom Date format: m d May 1999 (determined by the format of the cell id solution, id value is 58) Double value = Cell .getNumericCellValue (); return org.apache.poi.ss.usermodel.DateUtil.getJavaDate (value); } else { return numericToBigDecimal(cell); } } private Object numericToBigDecimal(Cell cell) { String valueOf = String.valueOf(cell.getNumericCellValue()); BigDecimal bd = new BigDecimal(valueOf); return bd; } }
3.ExcelIn comment
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author Lei * @time 2019/10/29 * @Description */ @Retention(value = RetentionPolicy.RUNTIME) @Target(value = {ElementType.TYPE, ElementType.FIELD}) public @interface ExcelIn { /** * Import sheet name * * @return */ String sheetName() default ""; /** * Corresponding to the header field name * * @return */ String title() default ""; }
4. Create objects in excel
import lombok.Data; import lombok.ToString; import java.util.Date; /** * @author Lei * @time 2019/10/29 * @Description */ @ToString @Data @ExcelIn(sheetName = "用户") public class User { private String id; @ExcelIn(title = "姓名") private String name; @ExcelIn(title = "年龄") private Integer age; @ExcelIn (title = "Date of Birth" ) Private a Date birthDate; }
Receiving layer 5.controller
@PostMapping("/batch/excel") @ApiOperation(value = "根据excel文件批量导入") public ResponseVO batchAddDeviceByExcelImport(MultipartFile multipartFile) { return new ResponseVO(deviceService.addDeviceByExcelImport(multipartFile)); }
6.service processing (here to print only)
public boolean addDeviceByExcelImport(MultipartFile multipartFile) { File file = null; try { file = File.createTempFile("temp", null); } catch (IOException e) { e.printStackTrace (); } try { multipartFile.transferTo(file); } catch (IOException e) { e.printStackTrace (); } file.deleteOnExit(); InputStream inputStream = null; try { inputStream = new FileInputStream(file); } catch (FileNotFoundException e) { e.printStackTrace (); } ExcelImportUtil<User> reader = new ExcelImportUtil<>(); List<User> userList = null; try { userList = reader.read(inputStream, User.class); } catch (Exception e) { log.error(e.getMessage()); throw new CodeException("51302", e.getMessage()); } userList.stream().forEach(e -> log.info(e.toString())); return true; }
7. Test
(1) two types of files in excel
(2) excel in the following format, where the red arrow note corresponding user object and the field name sheet
(3) swagger test
(4) the success of print
Finally, welcome message exchange Tucao. . .