SpringBoot 集成 Easypoi 实现导入导出
Easypoi 实现导入导出
官方文档:http://easypoi.mydoc.io/
相关依赖
<!-- easypoi -->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-spring-boot-starter</artifactId>
<version>4.1.0</version>
</dependency>
编写相关工具类,在 com.zyxx.skeleton.assembly
下创建easypoi.util
包,然后再创建工具类 EasyPoiExcelUtils
package com.zyxx.skeleton.assembly.easypoi.util;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.zyxx.skeleton.core.global.enums.StatusEnums;
import com.zyxx.skeleton.core.global.exception.GlobalException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
/**
* Excel导入导出工具类
*
* @author Tellsea
* @date 2019/9/4
* 官方文档:http://easypoi.mydoc.io/
* 参考文章:https://blog.csdn.net/Thinkingcao/article/details/85005930
*/
@Slf4j
public class EasyPoiExcelUtils {
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName,
boolean isCreateHeader, HttpServletResponse response) {
ExportParams exportParams = new ExportParams(title, sheetName);
exportParams.setCreateHeadRows(isCreateHeader);
defaultExport(list, pojoClass, fileName, response, exportParams);
}
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName,
HttpServletResponse response) {
defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
}
public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
defaultExport(list, fileName, response);
}
private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response,
ExportParams exportParams) {
Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
downLoadExcel(fileName, response, workbook);
}
private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
try {
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
workbook.write(response.getOutputStream());
} catch (IOException e) {
log.error("EasyPoiExcelUtils: 下载错误");
throw new GlobalException(StatusEnums.SERVER_ERROR);
}
}
private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
downLoadExcel(fileName, response, workbook);
}
public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
if (StringUtils.isBlank(filePath)) {
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
List<T> list = null;
try {
list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
} catch (NoSuchElementException e) {
log.error("EasyPoiExcelUtils: 模板不能为空");
throw new GlobalException(StatusEnums.SERVER_ERROR);
} catch (Exception e) {
e.printStackTrace();
log.error("EasyPoiExcelUtils: 导入错误");
throw new GlobalException(StatusEnums.SERVER_ERROR);
}
return list;
}
public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows,
Class<T> pojoClass) {
if (file == null) {
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
List<T> list = null;
try {
list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
} catch (NoSuchElementException e) {
log.error("EasyPoiExcelUtils: excel文件不能为空");
throw new GlobalException(StatusEnums.SERVER_ERROR);
} catch (Exception e) {
log.error("EasyPoiExcelUtils: 导入错误");
throw new GlobalException(StatusEnums.SERVER_ERROR);
}
return list;
}
}
测试案例
在 com.zyxx.customized.controller
下创建 EasyPoiExcelController
测试案例
package com.zyxx.customized.controller;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.zyxx.common.entity.UserInfo;
import com.zyxx.common.service.UserInfoService;
import com.zyxx.skeleton.assembly.easypoi.util.EasyPoiExcelUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/**
* Excel 导入导出
*
* @author: Tellsea
* @date: 2019/09/04
*/
@Api(tags = "Excel 导入导出")
@Slf4j
@Controller
@RequestMapping("excel")
public class EasyPoiExcelController {
@Autowired
private UserInfoService userInfoService;
@ApiOperation("导出")
@GetMapping("export")
public void export(HttpServletResponse response) {
List<UserInfo> list = userInfoService.selectAll();
EasyPoiExcelUtils.exportExcel(list, "easypoi导出功能", "导出sheet1", UserInfo.class, "系统用户表.xls", response);
}
@ApiOperation("导入")
@PostMapping("import")
public String importTest(@RequestParam("file") MultipartFile file) {
ImportParams importParams = new ImportParams();
// 数据处理
importParams.setHeadRows(1);
importParams.setTitleRows(1);
// 需要验证
importParams.setNeedVerify(false);
try {
ExcelImportResult<UserInfo> result = ExcelImportUtil.importExcelMore(file.getInputStream(), UserInfo.class, importParams);
List<UserInfo> list = result.getList();
list.forEach(userInfo -> {
log.info("从Excel导入数据到数据库的详细为 :{}", JSONObject.toJSONString(userInfo));
});
log.info("从Excel导入数据一共 {} 行 ", list.size());
} catch (IOException e) {
log.error("导入失败:{}", e.getMessage());
} catch (Exception e1) {
log.error("导入失败:{}", e1.getMessage());
}
return "导入成功";
}
}