引入依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.15</version>
</dependency>
定义相关对象
import lombok.Data;
import java.io.Serializable;
/**
* @Author: yz
* @Description:
*/
@Data
public class FieldInfo implements Serializable {
// 字段名称
private String fieldName;
// 所在表格
private Integer tableIndex;
// 所在行
private Integer row;
// 所在列
private Integer cell;
// 字段类型 1-数字类型,2-图片,3-普通字符,4-Boolean
private String fieldType;
// 图片下标
private Integer pictureIndex;
// 图片路径
private String picturePath;
}
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* @Author: yz
* @Description:
*/
@Data
public class ImportEntity implements Serializable {
private List<FieldInfo> fieldInfos;
}
准备模板
导入导出代码
import com.example.demo.entity.FieldInfo;
import com.example.demo.entity.ImportEntity;
import com.example.demo.handler.MyInvocationHandler;
import org.apache.ibatis.session.SqlSession;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.cglib.proxy.Proxy;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;
/**
* @Author: yz
* @Description:
*/
public class ImportCommonUtil {
private static final String STARTS_WITH = "${";
private static final String END_WITH = "}";
/**
* 获取导入对象字段信息
*
* @param filePath
* @return
*/
private static ImportEntity getImportEntity(String filePath) {
ImportEntity importEntity = new ImportEntity();
List<FieldInfo> fieldInfos = new ArrayList<>();
importEntity.setFieldInfos(fieldInfos);
try {
// 读取文档
FileInputStream in = new FileInputStream(filePath);
// 按照文档格式处理
if (filePath.toLowerCase().endsWith("docx")) {
// 得到word文档的信息 -> 2007
XWPFDocument xwpf = new XWPFDocument(in);
List<XWPFTable> tables = xwpf.getTables();
tables.stream().forEach(table -> {
int indexOfTable = tables.indexOf(table);
List<XWPFTableRow> rows = table.getRows();
rows.stream().forEach(row -> {
int indexOfRow = rows.indexOf(row);
List<XWPFTableCell> tableCells = row.getTableCells();
for (int i = 0; i < tableCells.size(); i++) {
XWPFTableCell xwpfTableCell = tableCells.get(i);
String text = xwpfTableCell.getText();
if (xwpfTableCell.getText().startsWith(STARTS_WITH)) {
FieldInfo fieldInfo = new FieldInfo();
fieldInfo.setTableIndex(indexOfTable);
fieldInfo.setRow(indexOfRow);
fieldInfo.setCell(i);
String fieldName = text.replace(STARTS_WITH, "").replace(END_WITH, "");
fieldInfo.setFieldName(fieldName);
fieldInfos.add(fieldInfo);
}
}
});
});
} else {
// 处理doc格式 -> 2003版本
POIFSFileSystem pfs = new POIFSFileSystem(in);
HWPFDocument hwpf = new HWPFDocument(pfs);
// 得到文档的读取范围
Range range = hwpf.getRange();
TableIterator tableIterator = new TableIterator(range);
Integer total = 0;
while (tableIterator.hasNext()) {
Table table = tableIterator.next();
total += 1;
int numRows = table.numRows();
for (int i = 0; i < numRows; i++) {
TableRow row = table.getRow(i);
int numCells = row.numCells();
for (int j = 0; j < numCells; j++) {
TableCell cell = row.getCell(j);
String text = cell.text();
if (text.startsWith(STARTS_WITH)) {
FieldInfo fieldInfo = new FieldInfo();
fieldInfo.setTableIndex(total + 1);
fieldInfo.setRow(i);
fieldInfo.setCell(j);
String fieldName = text.substring(text.indexOf("{"), text.indexOf(END_WITH));
fieldInfo.setFieldName(fieldName);
fieldInfos.add(fieldInfo);
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return importEntity;
}
/*
private static <T> void batchSave(Class<T> tClass, List<T> dataList) {
// 获取Mapper地址
try {
SqlSession sqlSession = MyBatisUtils.openSession();
String mapper = tClass.getSimpleName() + "Mapper";
//这里要写全类名
Class interfaceImpl = Class.forName(mapper);
Object instance = Proxy.newProxyInstance(
interfaceImpl.getClassLoader(),
new Class[]{interfaceImpl},
(InvocationHandler) new MyInvocationHandler(sqlSession.getMapper(interfaceImpl))
);
Method method = instance.getClass().getMethod("batchSave", List.class);
method.invoke(instance, dataList);
} catch (Exception e) {
e.printStackTrace();
}
}*/
/**
* 读取文档中表格并获取对象数据
*
* @param filePath
* @param list
* @param tClass
* @param <T>
* @return
*/
public static <T> List<T> tableInWord(String filePath, List<ImportEntity> list, Class<T> tClass) {
return list.stream().map(importEntity -> {
return getInstance(filePath, tClass, importEntity);
}).collect(Collectors.toList());
}
private static <T> T getInstance(String filePath, Class<T> tClass, ImportEntity importEntity) {
List<FieldInfo> fieldInfos = importEntity.getFieldInfos();
T newInstance = null;
try {
newInstance = tClass.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
try {
//载入文档
FileInputStream in = new FileInputStream(filePath);
// 处理docx格式 即office2007以后版本
if (filePath.toLowerCase().endsWith("docx")) {
//word 2007 图片不会被读取, 表格中的数据会被放在字符串的最后
//得到word文档的信息
XWPFDocument xwpf = new XWPFDocument(in);
List<XWPFTable> tables = xwpf.getTables();
List<XWPFPictureData> pictures = xwpf.getAllPictures();
for (FieldInfo fieldInfo : fieldInfos) {
XWPFTableCell cell = tables.get(fieldInfo.getTableIndex()).getRow(fieldInfo.getRow()).getCell(fieldInfo.getCell());
Field field = null;
try {
field = tClass.getField(fieldInfo.getFieldName());
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
field.setAccessible(true);
String fieldType = fieldInfo.getFieldType();
try {
if ("1".equals(fieldType)) {
field.set(newInstance, Integer.valueOf(cell.getText()));
} else if ("2".equals(fieldType)) {
String url = pictureTQDocx(pictures.get(fieldInfo.getPictureIndex()), fieldInfo.getPicturePath());
field.set(newInstance, url);
} else if ("3".equals(fieldType)) {
field.set(newInstance, cell.getText());
} else if ("4".equals(fieldType)) {
field.set(newInstance, Boolean.valueOf(cell.getText()));
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
} else {
// 处理doc格式 即office2003版本
POIFSFileSystem pfs = new POIFSFileSystem(in);
HWPFDocument hwpf = new HWPFDocument(pfs);
List<Picture> allPictures = hwpf.getPicturesTable().getAllPictures();
//得到文档的读取范围
Range range = hwpf.getRange();
TableIterator tableIterator = new TableIterator(range);
//得到word中的表格
Map<Integer, Table> tableMap = new HashMap<>();
Integer total = 0;
while (tableIterator.hasNext()) {
Table next = tableIterator.next();
Integer key = total;
total += 1;
tableMap.put(key, next);
}
for (FieldInfo fieldInfo : fieldInfos) {
Table table = tableMap.get(fieldInfo.getTableIndex());
TableCell cell = table.getRow(fieldInfo.getRow()).getCell(fieldInfo.getCell());
Field field = null;
try {
field = tClass.getField(fieldInfo.getFieldName());
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
field.setAccessible(true);
String fieldType = fieldInfo.getFieldType();
try {
if ("1".equals(fieldType)) {
field.set(newInstance, Integer.valueOf(cell.text()));
} else if ("2".equals(fieldType)) {
String url = pictureTQDoc(allPictures.get(fieldInfo.getPictureIndex()), fieldInfo.getPicturePath());
field.set(newInstance, url);
} else if ("3".equals(fieldType)) {
field.set(newInstance, cell.text());
} else if ("4".equals(fieldType)) {
field.set(newInstance, Boolean.valueOf(cell.text()));
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return newInstance;
}
/**
* 提取DOCX图片,并保存,返回可访问路径
*
* @param picture
* @param resourceBaseUrl
* @return
* @throws IOException
*/
public static String pictureTQDocx(XWPFPictureData picture, String resourceBaseUrl) throws IOException {
FileOutputStream fileOutputStream;
StringBuilder picturePath = getPicturePathBuilder(resourceBaseUrl);
picturePath.append(System.currentTimeMillis()).append(".").append(picture.suggestFileExtension());
String string = picturePath.toString();
fileOutputStream = new FileOutputStream(new File(resourceBaseUrl + string));
fileOutputStream.write(picture.getData());
return string;
}
/**
* 提取DOC图片,并保存,返回可访问路径
*
* @param picture
* @param resourceBaseUrl
* @return
* @throws IOException
*/
public static String pictureTQDoc(Picture picture, String resourceBaseUrl) throws IOException {
FileOutputStream fileOutputStream = null;
String path = null;
try {
StringBuilder picturePath = getPicturePathBuilder(resourceBaseUrl);
picturePath.append(System.currentTimeMillis()).append(picture.suggestFullFileName());
path = picturePath.toString();
fileOutputStream = new FileOutputStream(new File(resourceBaseUrl + path));
picture.writeImageContent(fileOutputStream);
fileOutputStream.close();
} finally {
if (fileOutputStream != null) {
fileOutputStream.close();
}
return path;
}
}
private static StringBuilder getPicturePathBuilder(String resourcePath) {
StringBuilder append = new StringBuilder().append("ufop")
.append(File.separator)
.append("img")
.append(File.separator)
.append(DateUtil.DateFormatYearMonthDay(new Date()))
.append(File.separator);
File file = new File(resourcePath + append);
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
return append;
}
}
欢迎大家提出宝贵的意见