1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
| package com.demo.util;
import java.io.IOException; import java.io.InputStream; import java.io.PushbackInputStream; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Map;
import org.apache.poi.POIXMLDocument; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.DateUtil; 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.XSSFWorkbook; import org.slf4j.LoggerFactory; import ch.qos.logback.classic.Logger;
public class ExcelToEntityList {
private Logger log = (Logger) LoggerFactory.getLogger(this.getClass()); private BeanStorage storage = new BeanStorage(); private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); private StringBuffer error = new StringBuffer(0);
public <T> ArrayList<T> transform(Class<?> entity,InputStream excel,Map<String,String> titleToAttr) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvalidFormatException{ ArrayList<T> result = new ArrayList<T>();
Workbook book = create(excel); Sheet sheet = book.getSheetAt(0); int rowCount = sheet.getLastRowNum(); if(rowCount < 1){ return result; } Map<Integer, String> headTitle = loadHeadTitle(sheet); for(int i=1;i<=rowCount;i++){ Row row = sheet.getRow(i); if(row==null){ continue; } int cellCount = row.getLastCellNum(); @SuppressWarnings("unchecked") T instance = (T) entity.newInstance(); int col = 0; try { for(;col<cellCount;col++){ String cellValue = getCellValue(row.getCell(col)); if(null!=cellValue){ this.setEntity(entity, instance,titleToAttr.get(headTitle.get(col)), cellValue); } } result.add(instance); } catch (Exception e) { e.printStackTrace(); this.error.append("第"+ (i+1) +"行,"+ headTitle.get(col)+"字段,数据错误,跳过!").append("<br>"); log.error("第"+ (i+1) +"行,"+ headTitle.get(col)+"字段,数据错误,跳过!"); } } excel.close(); return result; }
private Map<Integer,String> loadHeadTitle(Sheet sheet){ Map<Integer,String> map = new HashMap<Integer, String>(); Row row = sheet.getRow(0); int cellCount= row.getLastCellNum(); for(int i = 0; i < cellCount; i++){ String value = row.getCell(i).getStringCellValue(); if(null == value){ throw new RuntimeException("Excel导入:标题栏不能为空!"); } map.put(i, value); } return map; }
private String getCellValue(Cell cell){ if(null==cell){return "";} String value = null; switch (cell.getCellType()){ case XSSFCell.CELL_TYPE_BOOLEAN: value = String.valueOf(cell.getBooleanCellValue()); break; case XSSFCell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)){ value = dateFormat.format(cell.getDateCellValue()); }else{ value = String.valueOf((long) cell.getNumericCellValue()); } break; case XSSFCell.CELL_TYPE_STRING: value = cell.getStringCellValue(); break; case XSSFCell.CELL_TYPE_FORMULA: log.debug("不支持函数!"); break; }
return value; }
private <T> void setEntity(Class<?> clazz, T instance, String pro, String value) throws SecurityException, NoSuchMethodException, Exception{ String innerPro = null; String outterPro = null; if (pro.contains(".")){ String[] pros = pro.split("\\."); outterPro = pros[0]; innerPro = pros[1]; storage.storeClass(instance.hashCode() + outterPro, clazz.getDeclaredMethod(this.initGetMethod(outterPro), null).getReturnType()); } String getMethod = this.initGetMethod(outterPro!=null?outterPro:pro); Class<?> type = clazz.getDeclaredMethod(getMethod, null).getReturnType(); Method method = clazz.getMethod(this.initSetMethod(outterPro!=null?outterPro:pro), type); if (type == String.class){ method.invoke(instance, value); }else if (type == int.class || type == Integer.class){ method.invoke(instance, Integer.parseInt("".equals(value) ? "0" : value)); }else if (type == long.class || type == Long.class){ method.invoke(instance, Long.parseLong("".equals(value) ? "0" : value)); }else if (type == float.class || type == Float.class){ method.invoke(instance, Float.parseFloat("".equals(value) ? "0" : value)); }else if (type == double.class || type == Double.class){ method.invoke(instance, Double.parseDouble("".equals(value) ? "0" : value)); }else if (type == Date.class){ method.invoke(instance, dateFormat.parse(value)); }else if (type == boolean.class|| type == Boolean.class){ method.invoke(instance, Boolean.parseBoolean("".equals(value) ? "false" : value)); }else if (type == byte.class|| type == Byte.class){ method.invoke(instance, Byte.parseByte(value)); }else{ Object ins = storage.getInstance(instance.hashCode() + outterPro); this.setEntity(ins.getClass(), ins, innerPro, value); method.invoke(instance, ins); } }
public String initSetMethod(String field) { return "set" + field.substring(0, 1).toUpperCase() + field.substring(1); }
public String initGetMethod(String field) { return "get" + field.substring(0, 1).toUpperCase() + field.substring(1); }
public boolean hasError() { return error.capacity() > 0; }
public StringBuffer getError() { return error; }
private class BeanStorage { private Map<String, Object> instances = new HashMap<String, Object>(); public void storeClass(String key, Class<?> clazz) throws Exception{ if (!instances.containsKey(key)){ instances.put(key, clazz.newInstance()); } } public Object getInstance(String key){ return instances.get(key); } }
public Workbook create(InputStream inp) throws IOException,InvalidFormatException { if (!inp.markSupported()) { inp = new PushbackInputStream(inp, 8); } if (POIFSFileSystem.hasPOIFSHeader(inp)) { return new HSSFWorkbook(inp); } if (POIXMLDocument.hasOOXMLHeader(inp)) { return new XSSFWorkbook(OPCPackage.open(inp)); } throw new IllegalArgumentException("你的excel版本目前poi解析不了"); } }
|
留言
欢迎交流想法。留言会通过 GitHub Issues 保存,首次使用需要登录 GitHub。