本文只实现比较简单的Excel导入导出,提供思路,以抛砖引玉
第一步:新建一个实体类User
@Data
public class User {
@TableId
@ExcelProperty(value = "序号") // 导出Excel 的列名
private Integer id;
@ExcelProperty(value = "姓名")
private String name;
}
第二步:项目pom文件添加easyexcel的依赖
<dependency>
<groupId>com.alibabagroupId>
<artifactId>easyexcelartifactId>
<version>2.1.4version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>servlet-apiartifactId>
<version>2.5version>
dependency>
第三步:引入导入导出工具类
/**
* @author coder
* @date 2021/12/7
* 导出Excel工具类
*/
public class ExcelUtils {
/**
* 导出excel
*/
public static void exportData(HttpServletResponse response, String excelName, String sheetName, Class clazz, List data) throws Exception {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
excelName = URLEncoder.encode(excelName, "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + excelName + ExcelTypeEnum.XLSX.getValue());
EasyExcel.write(response.getOutputStream(), clazz).registerWriteHandler(new CustomCellWriteHandler()).sheet(sheetName).doWrite(data);
}
}
导出excel设置列自动宽度
/**
* @author
* @date 2021/12/7
* 导出excel设置列自动宽度
*/
public class CustomCellWriteHandler extends AbstractColumnWidthStyleStrategy {
private static final Logger LOGGER = LoggerFactory.getLogger(CustomCellWriteHandler.class);
private Map<Integer, Map<Integer, Integer>> CACHE = new HashMap<>();
@Override
protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);
if (needSetWidth) {
Map<Integer, Integer> maxColumnWidthMap = CACHE.get(writeSheetHolder.getSheetNo());
if (maxColumnWidthMap == null) {
maxColumnWidthMap = new HashMap<>();
CACHE.put(writeSheetHolder.getSheetNo(), maxColumnWidthMap);
}
Integer columnWidth = this.dataLength(cellDataList, cell, isHead);
if (columnWidth >= 0) {
if (columnWidth > 255) {
columnWidth = 255;
}
Integer maxColumnWidth = maxColumnWidthMap.get(cell.getColumnIndex());
if (maxColumnWidth == null || columnWidth > maxColumnWidth) {
maxColumnWidthMap.put(cell.getColumnIndex(), columnWidth);
writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), columnWidth * 256);
}
}
}
}
private Integer dataLength(List<CellData> cellDataList, Cell cell, Boolean isHead) {
if (isHead) {
return cell.getStringCellValue().getBytes().length;
} else {
CellData cellData = cellDataList.get(0);
CellDataTypeEnum type = cellData.getType();
if (type == null) {
return -1;
} else {
switch (type) {
case STRING:
return cellData.getStringValue().getBytes().length;
case BOOLEAN:
return cellData.getBooleanValue().toString().getBytes().length;
case NUMBER:
return cellData.getNumberValue().toString().getBytes().length;
default:
return -1;
}
}
}
}
}
导入工具类
/**
* 导入工具类
* @author coder
* @date 2021/12/7
*/
public class ExcelListener<T> extends AnalysisEventListener<T> {
//可以通过实例获取该值
private List<Object> datas = new ArrayList<Object>();
@Override
public void invoke(Object o, AnalysisContext analysisContext) {
datas.add(o);//数据存储到list,供批量处理,或后续自己业务逻辑处理。
doSomething(o);//根据自己业务做处理
}
private void doSomething(Object object) {
}
public List<Object> getDatas() {
return datas;
}
public void setDatas(List<Object> datas) {
this.datas = datas;
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
// datas.clear();//解析结束销毁不用的资源
}
}
第四步:实现导入导出
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
/**
* 导出
*/
@Override
public void exportExcel(HttpServletResponse response) {
List<User> list = baseMapper.selectUserList();
try {
ExcelUtils.exportData(response,"用户信息", "sheet1", User.class, list);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* EasyExcel实现导入
* @param file
* @return
*/
@Override
@SneakyThrows
public boolean importExcel(MultipartFile file) {
//获取文件流
InputStream inputStream = file.getInputStream();
//实例化实现了AnalysisEventListener接口的类
ExcelListener listener = new ExcelListener();
EasyExcelFactory.read(inputStream, User.class, listener).headRowNumber(1).build().readAll();
//获取数据
List<User> list = listener.getDatas();
return userService.saveBatch(list);
}
}