EasyPoi官方文档: http://easypoi.mydoc.io/.

一 导出

1 引入依赖

<dependency><!-- easypoi导出 --><groupId>cn.afterturn</groupId><artifactId>easypoi-spring-boot-starter</artifactId><version>4.3.0</version>
</dependency><dependency><!-- Hutool是一个Java工具包 --><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>${hutool.version}</version>
</dependency>

2 新建Excel导出工具类

此处使用sa-token示例项目下工具类EasyExcelUtil
sa-token官方文档: http://sa-token.dev33.cn/doc/index.html#/.

public class EasyExcelUtil {private static final String HSSF = ".xls";private static final String XSSF = ".xlsx";/*** 注解导出** @param dataList 数据* @param aClass   类对象* @param params   excel参数* @param fileName 文件名称* @param modelMap* @param request* @param response*/public static void normalExcel(List<?> dataList,Class<?> aClass,ExportParams params,String fileName,ModelMap modelMap,HttpServletRequest request,HttpServletResponse response) {modelMap.put(NormalExcelConstants.DATA_LIST, dataList);modelMap.put(NormalExcelConstants.CLASS, aClass);modelMap.put(NormalExcelConstants.PARAMS, params);modelMap.put(NormalExcelConstants.FILE_NAME, fileName);PoiBaseView.render(modelMap, request, response, NormalExcelConstants.EASYPOI_EXCEL_VIEW);}/*** 注解导出** @param dataList 数据* @param aClass   类对象* @param params   excel参数* @param fileName 文件名称* @param response*/@Deprecatedpublic static void normalExcel(List<?> dataList,Class<?> aClass, ExportParams params,String fileName, HttpServletResponse response) {try {Workbook workbook = ExcelExportUtil.exportExcel(params, aClass, dataList);if (workbook instanceof HSSFWorkbook) {fileName += HSSF;} else {fileName += XSSF;}ServletOutputStream outputStream = response.getOutputStream();response.setHeader(HttpHeaders.CONTENT_DISPOSITION, StrUtil.format("attachment;filename={}", URLUtil.encode(fileName, CharsetUtil.UTF_8)));response.setContentType(CharsetUtil.UTF_8);workbook.write(outputStream);IoUtil.close(outputStream);IoUtil.close(workbook);} catch (IOException e) {e.printStackTrace();}}/*** 模板导出** @param map* @param params* @param fileName* @param modelMap* @param request* @param response*/public static void templateExcel(Map<String, Object> map, TemplateExportParams params, String fileName, ModelMap modelMap, HttpServletRequest request,HttpServletResponse response) {modelMap.put(TemplateExcelConstants.FILE_NAME, fileName);modelMap.put(TemplateExcelConstants.PARAMS, params);modelMap.put(TemplateExcelConstants.MAP_DATA, map);PoiBaseView.render(modelMap, request, response,TemplateExcelConstants.EASYPOI_TEMPLATE_EXCEL_VIEW);}/*** map 导出** @param list* @param entity* @param params* @param fileName* @param modelMap* @param request* @param response*/public static void mapExcel(List<Map<String, Object>> list, List<ExcelExportEntity> entity, ExportParams params, String fileName, ModelMap modelMap, HttpServletRequest request,HttpServletResponse response) {modelMap.put(MapExcelConstants.MAP_LIST, list);modelMap.put(MapExcelConstants.ENTITY_LIST, entity);modelMap.put(MapExcelConstants.PARAMS, params);modelMap.put(MapExcelConstants.FILE_NAME, fileName);PoiBaseView.render(modelMap, request, response, MapExcelConstants.EASYPOI_MAP_EXCEL_VIEW);}/*** 大数据导出* <p>http://doc.wupaas.com/docs/easypoi/easypoi-1c10lbsojh62f</p>** @param aClass* @param params* @param dataParams* @param excelExportServer* @param modelMap* @param request* @param response*/public static void bigExcel(Class<?> aClass, ExportParams params, Map<String, Object> dataParams, IExcelExportServer excelExportServer, ModelMap modelMap, HttpServletRequest request,HttpServletResponse response) {modelMap.put(BigExcelConstants.CLASS, aClass);modelMap.put(BigExcelConstants.PARAMS, params);//就是我们的查询参数,会带到接口中,供接口查询使用modelMap.put(BigExcelConstants.DATA_PARAMS, dataParams);modelMap.put(BigExcelConstants.DATA_INTER, excelExportServer);PoiBaseView.render(modelMap, request, response, BigExcelConstants.EASYPOI_BIG_EXCEL_VIEW);}
}

3 新建导出实体类

项目需要引入lombok,编译器需安装lombok插件,不使用@Data标签可忽略。

@Data
public class SwordOutputExcel {@Excel(orderNum = "0", name = "id", width = 36)private String id;@Excel(orderNum = "1", name = "名称", width = 30)private String name;@Excel(orderNum = "2", name = "属性", width = 30, replace = {"巨剑_0", "太刀_1", "光剑_2", "左轮_3"})private String type;
}

4 自定义样式设置

新建样式类EasyExcelStyle继承默认样式类ExcelExportStylerDefaultImpl

public class EasyExcelStyle extends ExcelExportStylerDefaultImpl {public EasyExcelStyle(Workbook workbook) {super(workbook);}/*** 标题样式* @param color* @return*/@Overridepublic CellStyle getTitleStyle(short color) {CellStyle titleStyle = workbook.createCellStyle();titleStyle.setAlignment(HorizontalAlignment.CENTER);titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);titleStyle.setWrapText(true);
//        titleStyle.setFont(getFont(workbook, (short) 11, false));// 背景色titleStyle.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);return titleStyle;}@Overridepublic CellStyle stringSeptailStyle(Workbook workbook, boolean isWarp) {CellStyle style = workbook.createCellStyle();style.setAlignment(HorizontalAlignment.CENTER);style.setVerticalAlignment(VerticalAlignment.CENTER);style.setDataFormat(STRING_FORMAT);if (isWarp) {style.setWrapText(true);}return style;}/*** 列表头样式* @param color* @return*/@Overridepublic CellStyle getHeaderStyle(short color) {CellStyle titleStyle = workbook.createCellStyle();Font font = workbook.createFont();font.setFontHeightInPoints((short) 12);titleStyle.setFont(font);titleStyle.setAlignment(HorizontalAlignment.CENTER);titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);return titleStyle;}@Overridepublic CellStyle stringNoneStyle(Workbook workbook, boolean isWarp) {CellStyle style = workbook.createCellStyle();style.setAlignment(HorizontalAlignment.CENTER);style.setVerticalAlignment(VerticalAlignment.CENTER);style.setDataFormat(STRING_FORMAT);if (isWarp) {style.setWrapText(true);}return style;}/*** 字体样式** @param size   字体大小* @param isBold 是否加粗* @return*/private Font getFont(Workbook workbook, short size, boolean isBold) {Font font = workbook.createFont();// 字体样式font.setFontName("宋体");// 是否加粗font.setBold(isBold);// 字体大小font.setFontHeightInPoints(size);return font;}
}

新建样式枚举类

public enum EasyExcelStyleType {NONE("默认样式", ExcelExportStylerDefaultImpl.class),ONE("自定义样式一", EasyExcelStyle.class);EasyExcelStyleType(String str, Class<?> cla) {this.str = str;this.cla = cla;}private String str;private Class<?> cla;public String getStr() {return str;}public void setStr(String str) {this.str = str;}public Class<?> getCla() {return cla;}public void setCla(Class<?> cla) {this.cla = cla;}
}

5 控制器

 @GetMapping("/exportExcel")public void exportExcel(HttpServletRequest request, HttpServletResponse response) {// 要导出数据SwordOutputExcel s1 = new SwordOutputExcel();s1.setId(IdUtil.simpleUUID());s1.setName("紫芸双影剑");s1.setType("0");SwordOutputExcel s2 = new SwordOutputExcel();s2.setId(IdUtil.simpleUUID());s2.setName("细雪之舞");s2.setType("1");List<SwordOutputExcel> list = new ArrayList<>();list.add(s1);list.add(s2);ModelMap modelMap = new ModelMap();ExportParams exportParams = new ExportParams();// 自定义样式设置exportParams.setStyle(EasyExcelStyleType.ONE.getCla());EasyExcelUtil.normalExcel(list, SwordOutputExcel.class, exportParams, "武器" + Instant.now().getEpochSecond(), modelMap, request, response);}

6 前端发送请求

<h3>导出Excel</h3>
<a href="/customUser/exportExcel">导出</a>

7 测试结果

二 导入

1 新建导入类

主类

@Data
public class SwordImportEntity {@Excel(name = "id")private String id;@Excel(name = "名称")private String name;@Excel(name = "类型", replace = {"巨剑_0", "太刀_1", "光剑_2", "左轮_3"})private String type;@ExcelCollection(name = "拥有玩家")private List<SwordUserEntity> userEntityList;
}

子类

@Data
public class SwordUserEntity {@Excel(name = "玩家昵称")private String userName;@Excel(name = "玩家职业", replace = {"剑魂_0", "漫游_1", "散打_2"})private String occupation;@Excel(name = "创建时间")private Date createTime;
}

2 导入Excel表格

表格

3 控制器

 @PostMapping("/importExcel")@ResponseBodypublic Map<String, Object> importUser(@RequestParam("uploadFile") MultipartFile multipartFile) {Map<String, Object> map = new HashMap<>(2);ImportParams params = new ImportParams();/*** 这里需要注意表头的行数设置一定要正确!否则集合数据将无法读取,* 可以通过WPS或者office查看实际表头所占用的行数,* 一定要区分表头与标题的区别,表头是列名称,标题是表头上面的文字,* 本文示例文件中没有标题,所以setTitleRows为0*/// 设置表头行数params.setHeadRows(2);// 标题行设置为0行,默认是0,可以不设置params.setTitleRows(0);try {List<SwordImportEntity> result = ExcelImportUtil.importExcel(multipartFile.getInputStream(), SwordImportEntity.class, params);for (SwordImportEntity t : result) {// 自定义数据校验略// 打印数据System.out.println(t);}map.put("code", 200);map.put("msg", "导入成功");} catch (Exception e) {e.printStackTrace();}return map;}

4 前端发送请求

<h3>导入Excel</h3>
<input id="fileId" type="file" name="uploadFile" value="请选择文件">
<a onclick="uploadFile();" style="cursor: pointer; display: inline-block;background-color: aqua">导入</a>function uploadFile() {let fileobj = $("#fileId")[0].files[0];console.log(fileobj);let form = new FormData();form.append("uploadFile", fileobj);$.ajax({type: 'POST',url: '/customUser/importExcel',data: form,// 告诉jquery要传输data对象processData: false,// 告诉jquery不需要增加请求头对于contentType的设置contentType: false,success: function (arg) {console.log(arg)}})
}

5 测试结果

EasyPoi Excel简单导出导入相关推荐

  1. 转---SQL与EXCEL交互(导出/导入)

    SQL与EXCEL交互(导出/导入) EXCE->SQL //方案一: 通过OleDB方式获取Excel文件的数据,然后通过DataSet中转到SQL Server openFileDialog ...

  2. springboot整合poi(使用EXCEL模板导出导入)

    springboot整合poi 依赖 <!-- poi依赖--><dependency><groupId>org.apache.poi</groupId> ...

  3. Java中excel的导出导入

    spring boot项目: pom.xml: <?xml version="1.0"?> <project xsi:schemaLocation="h ...

  4. easypoi利用模板导出图片到Excel;解决easypoi导出图片到合并单元格单元格被拉伸的问题

    easypoi的封装是非常好的,用起来很简单. 官方教程地址:http://easypoi.mydoc.io/ 但是在使用模板导出图片到合并单元格时出问题了,官网找了好几遍没找到方案. 其实官方早就实 ...

  5. java关于excel的导出_[转载]关于JAVA导出Excel

    现在正在做的项目中涉及大量的Excel文件导出导入操作,都是使用Java Excel来操作. Java Excel是一开放源码项目,通过它Java开发人员可以读取Excel文件的内容.创建新的Exce ...

  6. springmvc使用easypoi导出导入Excel表(1):导出Excel表

    编译工具:eclipse 项目:maven+ssm springmvc使用easypoi导出导入Excel表(2):导入Excel表 在pom.xml引入easypoi的依赖包: <!--eas ...

  7. Java 利用EasyPoi做Excel模板的导入导出操作

    Java 利用EasyPoi做Excel模板的导入导出操作 项目背景 加入pom依赖 项目Excel模板图 代码实现 首先是实体类定义 Excel 实现导入 Excel的导出 结束语 项目背景 作为一 ...

  8. 【JavaWeb开发】使用java实现简单的Excel文件的导入与导出(POI)

    前言:在实际的开发中,我们经常需要用户在界面中输入大量重复且有规律的数据,但是一个表单一个表单的填写效率过慢,而且过多的表单也会给JavaWeb的业务逻辑开发带来不小的困扰,所以我们可以使用一个Exc ...

  9. EasyPOI使用 导出导入Excel数据

    导入依赖 <!--easy poi依赖--> <dependency><groupId>cn.afterturn</groupId><artifa ...

最新文章

  1. 数据呈现 | 20大数据可视化工具测评
  2. Kotlin实战指南四:区间
  3. uniSWF使用注意事项
  4. c语言文件归并问题_C语言 | 选择法对10个数排序
  5. Mysql事项,视图,函数,触发器命令
  6. 贪心策略——部分背包问题
  7. 【英语学习】【WOTD】cumulate 释义/词源/示例
  8. 传华为将有2万名CNBG员工转岗CBG 回应:该消息不属实
  9. 4-1-getOutputStream()或getWriter()发送响应消息体及分析为什么不能同时使用
  10. oracle中自定义异常编号,Oracle自定义异常的使用
  11. Kubernetes 常见运维技巧总结
  12. javascript原型和原型链
  13. 【图像去噪】基于matlab维纳滤波图像去噪【含Matlab源码 725期】
  14. 软考中级【数据库系统工程师】第0章:如何自学备考,考试介绍考什么,备考教材,上午和下午的体型分数分布,备考课程链接,个人备考感谢
  15. 树莓派开机自动运行python程序的方法
  16. http网站快捷免费升级到https
  17. Collections中Counter函数,namedtuple函数,defaultdict函数的使用
  18. 关于加强销售费用管理的探讨
  19. Bitlocker加密到一半怎么停止?
  20. 自己搭建的k8s集群,怎么做负载均衡?

热门文章

  1. 读书有益——》生僻字、可能念错的字
  2. 点线面的意义_论文:点线面在设计中的运用
  3. 运用frame、frameset框架不显示问题
  4. dig 域名信息查询
  5. 跨考计算机日程记录01
  6. 关于keras.sum()和kears.softmax()等函数中维度的理解
  7. python正则表达式例题_python—正则表达式实例
  8. Ubuntu-安装输入法
  9. php 获取当前域名大胡子,养黄金大胡子的小经验
  10. 视频知识点(14)- 来,咱们聊一聊 I 帧和 IDR 帧的区别