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 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
| package com.example.excel;
import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.tuple.Pair; import org.apache.poi.hssf.usermodel.HSSFPatriarch; import org.apache.poi.hssf.usermodel.HSSFShape; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFDrawing; import org.apache.poi.xssf.usermodel.XSSFShape; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.springframework.util.ReflectionUtils;
import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.math.BigDecimal; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.*; import java.util.stream.StreamSupport;
import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap;
@Slf4j public class ExcelUtils {
static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); private static final String ROW_INDEX = "rowIndex";
public <T extends ExcelData> List<T> importExcel(InputStream inputStream, Class<T> clz) throws Exception { List<T> list = new ArrayList<>(); Workbook workbook = WorkbookFactory.create(inputStream); Sheet sheet = workbook.getSheetAt(0); int rownum = sheet.getPhysicalNumberOfRows(); Field[] fields = clz.getDeclaredFields(); Row row = sheet.getRow(0); int column = row.getPhysicalNumberOfCells();
checkExcelHeader(fields, row); log.info("Excel导入, ts=[{}], rows=[{}], column=[{}]", LocalDateTime.now(), rownum, column);
for (int i = 1; i<rownum; i++) {
row = sheet.getRow(i); if (row == null) { break; }
T instance = clz.getDeclaredConstructor().newInstance();
for (Field field : fields) { if (field.isAnnotationPresent(ExcelHeader.class)) { ReflectionUtils.makeAccessible(field); Cell cell = getCell(row, field); if (cell == null) { continue; } Object value = getCellValue(cell); setFieldValue(instance, field, value);
} } setRowIndex(clz, instance, row.getRowNum()); list.add(instance); }
if (log.isDebugEnabled()) { log.debug("上传数据={}", list.toString()); } return list; }
public List<Image> getImagesFromExcel(InputStream inputStream) throws IOException { Workbook workbook = WorkbookFactory.create(inputStream); Sheet sheet = workbook.getSheetAt(0); return getImagesFromExcel(sheet); }
private void checkExcelHeader(Field[] fields, Row row) { for (Field field : fields) { if (field.isAnnotationPresent(ExcelHeader.class)) { Cell cell = getCell(row, field); if (cell == null || (Objects.nonNull(getCellValue(cell)) && !getCellValue(cell).equals(field.getAnnotation(ExcelHeader.class).value()))) { throw new RuntimeException("Excel格式错误"); } } } }
private <T extends ExcelData> void setRowIndex(Class<T> clz, T instance, Object rowIndex) throws NoSuchFieldException, IllegalAccessException { Field field = clz.getSuperclass().getDeclaredField(ROW_INDEX); ReflectionUtils.makeAccessible(field); setFieldValue(instance, field, rowIndex); }
private List<Image> getImagesFromExcel(Sheet sheet) {
if (sheet instanceof XSSFSheet) { XSSFDrawing patriarch = (XSSFDrawing) sheet.createDrawingPatriarch(); List<XSSFShape> shapes = patriarch.getShapes(); return convertShape2Image(sheet, shapes); } else if (sheet instanceof HSSFSheet) { HSSFPatriarch patriarch = (HSSFPatriarch) sheet.createDrawingPatriarch(); List<HSSFShape> shapes = patriarch.getChildren(); return convertShape2Image(sheet, shapes); } return Collections.emptyList(); }
private List<Image> convertShape2Image(Sheet sheet, Collection<? extends Shape> shapes) { Map<Integer, byte[]> imageByLocations = shapes.stream() .filter(Picture.class::isInstance) .map(s -> (Picture) s) .map(this::toMapEntry) .collect(toMap(Pair::getKey, Pair::getValue));
return StreamSupport.stream(sheet.spliterator(), false) .filter(this::isNotHeader) .map(row -> new Image(String.valueOf(row.getRowNum()), imageByLocations.get(row.getRowNum()))) .collect(toList()); }
boolean isNotHeader(Row row) { return row.getRowNum() != 0; }
Pair<Integer, byte[]> toMapEntry(Picture picture) { byte[] data = picture.getPictureData().getData(); ClientAnchor anchor = picture.getClientAnchor(); if (log.isDebugEnabled()) { log.debug("行: {}, 列: {}, 格式: {}", anchor.getRow1(), anchor.getCol1(), picture.getPictureData().suggestFileExtension()); } return Pair.of(anchor.getRow1(), data); }
static class Image { String rowIndex; byte[] bytes;
Image(String rowIndex, byte[] bytes) { this.rowIndex = rowIndex; this.bytes = bytes; } }
static class ImageUrl { String rowIndex; String url;
ImageUrl(String rowIndex, String url) { this.rowIndex = rowIndex; this.url = url; } }
private static Object getCellValue(Cell cell) { CellType cellType = cell.getCellType(); Object cellValue = null;
switch (cellType) { case STRING: cellValue = cell.getStringCellValue(); break; case BOOLEAN: cellValue = cell.getBooleanCellValue(); break; case ERROR: cellValue = cell.getErrorCellValue(); break; case NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { Date d = cell.getDateCellValue(); cellValue = dateTimeFormatter.format(LocalDateTime.ofInstant(d.toInstant(), ZoneId.systemDefault())); } else { double numericCellValue = cell.getNumericCellValue(); BigDecimal bdVal = BigDecimal.valueOf(numericCellValue); if ((bdVal + ".0").equals(Double.toString(numericCellValue))) { cellValue = bdVal; } else if (String.valueOf(numericCellValue).contains("E10")) { cellValue = BigDecimal.valueOf(numericCellValue).toPlainString(); } else { cellValue = numericCellValue; } } break; default: break; }
if (log.isDebugEnabled()) { log.debug("cellType={}, cellValue={}", cellType.name(), cellValue); } return cellValue; }
private static <T> void setFieldValue(T instance, Field field, Object value) throws IllegalAccessException {
if (field.getType() == int.class || field.getType() == Integer.class) { field.set(instance, value); } else if (field.getType() == long.class || field.getType() == Long.class) { field.set(instance, value); } else if (field.getType() == double.class || field.getType() == Double.class) { field.set(instance, value); } else if (field.getType() == String.class) { field.set(instance, String.valueOf(value)); } else if (field.getType() == LocalDateTime.class) { field.set(instance, LocalDateTime.parse(String.valueOf(value), dateTimeFormatter)); } }
private Cell getCell(Row row, Field field) { ExcelHeader annotation = field.getAnnotation(ExcelHeader.class); return row.getCell(annotation.columnIndex()); }
private void saveImage2Disk(byte[] data, String path, String imageName, String ext) throws IOException { String filePath = path + imageName + "." + ext; log.info("saveImage2Disk: [{}]", filePath); FileOutputStream out = new FileOutputStream(filePath); out.write(data); out.close(); } }
|