1.添加Maven依赖
cn.afterturn
easypoi-base
3.2.0
cn.afterturn
easypoi-web
3.2.0
cn.afterturn
easypoi-annotation
3.2.0
org.projectlombok
lombok
provided
2.自定义EasyPoiUtils工具类
public final class EasyPoiUtils {
private EasyPoiUtils() {}
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) {
throw new RuntimeException(e);
}
}
private static void defaultExport(List dataList, Class clz, String fileName, HttpServletResponse response, ExportParams exportParams) {
Workbook workbook = ExcelExportUtil.exportExcel(exportParams, clz, dataList);
if (workbook != null) {
downLoadExcel(fileName, response, workbook);
}
}
public static void exportExcel(List dataList, String title, String sheetName, Class clz, String fileName, boolean isCreateHeader, HttpServletResponse response) {
ExportParams exportParams = new ExportParams(title, sheetName);
exportParams.setCreateHeadRows(isCreateHeader);
defaultExport(dataList, clz, fileName, response, exportParams);
}
public static void exportExcel(List dataList, String title, String sheetName, Class clz, String fileName, HttpServletResponse response) {
defaultExport(dataList, clz, fileName, response, new ExportParams(title, sheetName));
}
private static void defaultExport(List
3.Excel导入
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ExportUser {
@Excel(name = "用户名", width = 10)
private String username;
@Excel(name = "创建时间", format = "yyyy-MM-dd", width = 15)
private Date createTime;
}
@RequestMapping("/import/users")
@ResponseBody
public List importUsers(@RequestParam MultipartFile file) {
return EasyPoiUtils.importExcel(file, ExportUser.class);
}
4.Excel导出
@RequestMapping(value = "/export/users", method = RequestMethod.GET)
public void exportUsers(HttpServletResponse response) {
List userList = getUserList();
EasyPoiUtils.exportExcel(userList, "用户列表", "用户报表", ExportUser.class, "用户明细报表.xls", response);
}
private List getUserList() {
List userList = new ArrayList<>();
userList.add(new ExportUser("tom", new Date()));
userList.add(new ExportUser("jack", new Date()));
userList.add(new ExportUser("123", new Date()));
return userList;
}
5.测试
导出:http://localhost:8080/demo/export/users
导入:http://localhost:8080/demo/import/users (用postman或者curl测试吧)
源码 https://gitee.com/jsjack_wang/springboot-demo dev-easypoi分支