Java开发中如何用POI导入包含图片的Excel文件

前言

前导知识

本篇基于 注解 + 反射 实现Excel导入功能的实现。

原想把图片上传等方法抽象出来封装一个工具jar, 大家根据业务不同实现不同的逻辑, 由于时间原因, 本篇直接返回图片bytes, 在业务层处理~, 大家如有需求,自行修改源码

实现

还是老规矩, 直接上代码, 说明看注释。

定义Excel注解

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
package com.example.excel;

import java.lang.annotation.*;

/**
* @author cuishiying
* @date 2021-01-22
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExcelHeader {

enum Type {TEXT, IMAGE};

/**
* 表头
* @return
*/
String value() default "";

/**
* 列索引
* @return
*/
int columnIndex() default 0;

/**
* 字段类型
* @return
*/
Type type() default Type.TEXT;

}

定义数据基类

由于图片和数据需要做对应并回填到实体字段中, 所以这里抽取了实体基类

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
/**
* @author cuishiying
* @date 2021-01-22
*/
public class ExcelData implements Serializable {

/**
* 行号
*/
@ExcelHeader(value = "行号")
public String rowIndex;

public String getRowIndex() {
return rowIndex;
}

public void setRowIndex(String rowIndex) {
this.rowIndex = rowIndex;
}

@Override
public String toString() {
return "ExcelData{" +
"rowIndex='" + rowIndex + '\'' +
'}';
}
}

工具类

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;

/**
* @author cuishiying
* @date 2021-01-22
*/
@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 sheet = workbook.getSheetAt(0);
// 获取最大行数(或者sheet.getLastRowNum())
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 sheet = workbook.getSheetAt(0);
// 获取第一个sheet的图片数据
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);
}

/**
* 从Sheet中提取所有图片
*/
private List<Image> getImagesFromExcel(Sheet sheet) {

if (sheet instanceof XSSFSheet) {
// Excel 2007
XSSFDrawing patriarch = (XSSFDrawing) sheet.createDrawingPatriarch();
List<XSSFShape> shapes = patriarch.getShapes();
return convertShape2Image(sheet, shapes);
} else if (sheet instanceof HSSFSheet) {
// Excel 2003
HSSFPatriarch patriarch = (HSSFPatriarch) sheet.createDrawingPatriarch();
List<HSSFShape> shapes = patriarch.getChildren();
return convertShape2Image(sheet, shapes);
}
return Collections.emptyList();
}

/**
* 将Shape转换为图片
*/
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 {
// 行号, 作为唯一id
String rowIndex;
// 图片数据
byte[] bytes;

Image(String rowIndex, byte[] bytes) {
this.rowIndex = rowIndex;
this.bytes = bytes;
}
}

static class ImageUrl {
// 行号, 作为唯一id
String rowIndex;
// 图片url
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();
}
}

测试

假设我们需要导入微信相关信息

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
package com.example.excel;

import lombok.Data;
import lombok.ToString;

/**
* @author cuishiying
* @date 2021-01-22
*/
@Data
@ToString(callSuper = true)
public class WeixinData extends ExcelData {

/**
* 号码池名称
*/
@ExcelHeader(value = "号码池名称", columnIndex = 0)
private String name;

/**
* 微信号
*/
@ExcelHeader(value = "微信号", columnIndex = 1)
private String weixin;

/**
* 微信二维码
*/
@ExcelHeader(value = "微信二维码", columnIndex = 2, type = ExcelHeader.Type.IMAGE)
private String qrCode;

/**
* 权重
*/
@ExcelHeader(value = "权重", columnIndex = 3)
private String weight;

/**
* 启用禁用
*/
@ExcelHeader(value = "状态", columnIndex = 4)
private String enable;


}

模拟导入Excel文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* @author cuishiying
* @date 2021-01-22
*/
@Slf4j
public class Main {

public static void main(String[] args) throws Exception {
String excelFilePath = "/Users/cuishiying/Desktop/微信号码池导入模板2003.xls";
ExcelUtils excelUtils = new ExcelUtils();
List<WeixinData> weixinData = excelUtils.importExcel(new FileInputStream(excelFilePath), WeixinData.class);
List<ExcelUtils.Image> imagesFromExcel = excelUtils.getImagesFromExcel(new FileInputStream(excelFilePath));
log.info(weixinData.toString());
}
}

输出结果

1
21:43:16.084 [main] INFO com.example.excel.Main - [WeixinData(super=ExcelData{rowIndex='1'}, name=号码池1, weixin=mini-code1, qrCode=null, weight=10.0, enable=启用), WeixinData(super=ExcelData{rowIndex='2'}, name=号码池2, weixin=moni-code2, qrCode=null, weight=20.0, enable=启用)]

最后

本文到此结束,感谢阅读。如果您觉得不错,请关注公众号【当我遇上你】支持一下。