import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Field; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang3.StringUtils; 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.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import com.weibo.api.admin.annotation.ExcelColumn; /** * Created by liuwen6 on 2017/3/7. */ public class ExcelUtils { /** * 将Excel的内容导出成Excel实体类 * * @param file * @param suffix * @param type * @param skip * @param <T> * @return * @throws IOException */ public static <T> List<T> parse(InputStream file, String suffix, Class<T> type, int skip) { LinkedList<T> ret = new LinkedList<>(); Map<Integer, Field> columnFieldMap = getColumnFieldMap(type); Workbook workbook = null; if (StringUtils.equalsIgnoreCase("xls", suffix)) { try { workbook = new HSSFWorkbook(file); } catch (IOException e) { throw new IllegalArgumentException("excel file not existed"); } } else if (StringUtils.equalsIgnoreCase("xlsx", suffix)) { try { workbook = new XSSFWorkbook(file); } catch (IOException e) { throw new IllegalArgumentException("excel file not existed"); } } if (workbook == null) { throw new IllegalArgumentException("excel suffix must be xls or xlsx"); } Sheet sheet = workbook.getSheetAt(0); int lastRow = sheet.getLastRowNum(); for (int i = skip; i <= lastRow; i++) { Row row = sheet.getRow(i); T t = null; try { t = type.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new IllegalArgumentException("type error"); } for (Map.Entry<Integer, Field> entry : columnFieldMap.entrySet()) { Integer index = entry.getKey(); Field field = entry.getValue(); Cell cell = row.getCell(index); Class<?> fieldType = field.getType(); if (fieldType.isAssignableFrom(Long.class) || fieldType.isAssignableFrom(Integer.class)) { double value = 0; try { value = cell.getNumericCellValue(); } catch (Exception e) { try { value = Double.valueOf(cell.getStringCellValue()); } catch (NumberFormatException e1) { throw new IllegalArgumentException("data format error"); } } if (fieldType.isAssignableFrom(Integer.class)) { try { field.set(t, Double.valueOf(value).intValue()); } catch (IllegalAccessException e) { throw new IllegalArgumentException("data format error"); } } if (fieldType.isAssignableFrom(Long.class)) { try { field.set(t, Double.valueOf(value).longValue()); } catch (IllegalAccessException e) { throw new IllegalArgumentException("data format error"); } } if (fieldType.isAssignableFrom(Double.class)) { try { field.set(t, value); } catch (IllegalAccessException e) { throw new IllegalArgumentException("data format error"); } } if (fieldType.isAssignableFrom(Float.class)) { try { field.set(t, (float) value); } catch (IllegalAccessException e) { throw new IllegalArgumentException("data format error"); } } } else if (fieldType.isAssignableFrom(String.class)) { String value = ""; try { value = cell.getStringCellValue(); } catch (Exception e) { try { value = "" + cell.getNumericCellValue(); } catch (Exception e1) { throw new IllegalArgumentException("cell content is not a string"); } } try { field.set(t, value); } catch (IllegalAccessException e) { throw new IllegalArgumentException("data format error"); } } } ret.add(t); } return ret; } /** * 根据Excel实体类导出Excel文件 * * @param file * @param data * @param type * @param <T> */ public static <T> void export(OutputStream file, List<T> data, Class<T> type) { Map<Integer, Field> columnFieldMap = getColumnFieldMap(type); Set<Map.Entry<Integer, Field>> entrySet = columnFieldMap.entrySet(); XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = workbook.createSheet("sheet 1"); XSSFRow header = sheet.createRow(0); for (Map.Entry<Integer, Field> entry : entrySet) { Field field = entry.getValue(); Integer index = entry.getKey(); ExcelColumn columnInfo = field.getAnnotation(ExcelColumn.class); XSSFCell cell = header.createCell(index); cell.setCellValue(columnInfo.name()); } int i = 1; for (T d : data) { XSSFRow row = sheet.createRow(i); for (Map.Entry<Integer, Field> entry : entrySet) { Field field = entry.getValue(); Integer index = entry.getKey(); XSSFCell cell = row.createCell(index); Class<?> fieldType = field.getType(); try { Object o = field.get(d); if (o != null) { if (fieldType.isAssignableFrom(Integer.class) || fieldType.isAssignableFrom(Long.class) || fieldType.isAssignableFrom(Double.class)) { cell.setCellValue(Double.parseDouble(o.toString())); } else { cell.setCellValue(o.toString()); } } } catch (IllegalAccessException e) { throw new IllegalArgumentException("data format error"); } } i++; } try { workbook.write(file); } catch (IOException e) { throw new IllegalArgumentException("file is not existed"); } } private static <T> Map<Integer, Field> getColumnFieldMap(Class<T> type) { Map<Integer, Field> columnFieldMap = new HashMap<>(); Field[] fields = type.getDeclaredFields(); for (Field field : fields) { ExcelColumn column = field.getAnnotation(ExcelColumn.class); int index = Math.max(column.index(), column.value()); if (index >= 0) { field.setAccessible(true); columnFieldMap.put(index, field); } } return columnFieldMap; } }
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Created by wencheng1 on 2017/3/7. */ @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface ExcelColumn { int index() default -1; int value() default -1; String name() default ""; }
import com.weibo.api.admin.annotation.ExcelColumn; /** * Created by liuwen6 on 2018/3/18. */ public class AbnormalRelationProtectInfo { @ExcelColumn(index = 0, name = "uid") private Long uid; @ExcelColumn(index = 1, name = "价值") private String reason; @ExcelColumn(index = 2, name = "处理类型") private Integer processType; public long getUid() { return uid; } public void setUid(long uid) { this.uid = uid; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } public int getProcessType() { return processType; } public void setProcessType(int processType) { this.processType = processType; } }
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.15</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.15</version> </dependency>