EasyPoi 导出表格

  • EasyPoiUtil 工具类
  • 设置表头 NewExcelExportStylerDefaultImpl 工具类
  • VO实体类 对应的是表的列名
  • Controller 1 未设置表头版本
  • Controller 2 设置表头版本
  • Service 查询导出Excel人员数据
  • ServiceImpl
  • 导出时分割
  • Mapper
  • Mapper.xml
  • 复杂表头

点击官方文档

EasyPoiUtil 工具类

package com.hollysys.server.common.excel;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.hollysys.server.vo.ExcelEmployeeVo;
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;/*** @Auther: HeJD* @Date: 2018/10/9 13:54* @Description:*/
public class EasyPoiUtil {/*** 功能描述:复杂导出Excel,包括文件名以及表名。创建表头** @author HeJD* @date 2018/10/9 13:54* @param list 导出的实体类* @param title 表头名称* @param sheetName sheet表名* @param pojoClass 映射的实体类* @param isCreateHeader 是否创建表头* @param fileName* @param response* @return*/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);}/*** 功能描述:复杂导出Excel,包括文件名以及表名,不创建表头** @author HeJD* @date 2018/10/9 13:54* @param list 导出的实体类* @param title 表头名称* @param sheetName sheet表名* @param pojoClass 映射的实体类* @param fileName* @param response* @return*/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));}/*** 功能描述:Map 集合导出** @author HeJD* @date 2018/10/9 13:54* @param list 实体集合* @param fileName 导出的文件名称* @param response* @return*/public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {defaultExport(list, fileName, response);}/*** 功能描述:默认导出方法** @author HeJD* @date 2018/10/9 13:54* @param list 导出的实体集合* @param fileName 导出的文件名* @param pojoClass pojo实体* @param exportParams ExportParams封装实体* @param response* @return*/private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) {Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);if (workbook != null) {downLoadExcel(fileName, response, workbook);}}/*** 功能描述:Excel导出** @author HeJD* @date 2018/10/9   15:35* @param fileName 文件名称* @param response* @param workbook Excel对象* @return*/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);}}/*** 功能描述:默认导出方法** @author HeJD* @date 2018/7/23 15:33* @param list 导出的实体集合* @param fileName 导出的文件名* @param response* @return*/private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);if (workbook != null) ;downLoadExcel(fileName, response, workbook);}/*** 功能描述:根据文件路径来导入Excel** @author HeJD* @date 2018/10/9 14:17* @param filePath 文件路径* @param titleRows 表标题的行数* @param headerRows 表头行数* @param pojoClass Excel实体类* @return*/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) {throw new RuntimeException("模板不能为空");} catch (Exception e) {e.printStackTrace();}return list;}/*** 功能描述:根据接收的Excel文件来导入Excel,并封装成实体类** @author HeJD* @date 2018/10/9 14:17* @param file 上传的文件* @param titleRows 表标题的行数* @param headerRows 表头行数* @param pojoClass Excel实体类* @return*/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) {throw new RuntimeException("excel文件不能为空");} catch (Exception e) {throw new RuntimeException(e.getMessage());}return list;}}

设置表头 NewExcelExportStylerDefaultImpl 工具类

package com.hollysys.server.common.excel;import cn.afterturn.easypoi.excel.export.styler.AbstractExcelExportStyler;
import cn.afterturn.easypoi.excel.export.styler.IExcelExportStyler;
import org.apache.poi.ss.usermodel.*;/*** @author :xiezhijian* @date :Created in 2020/3/18 11:55* @description:表头自定义* @parameter:* @modified By:* @version: $*/
public class NewExcelExportStylerDefaultImpl extends AbstractExcelExportStylerimplements IExcelExportStyler {public NewExcelExportStylerDefaultImpl(Workbook workbook) {super.createStyles(workbook);}@Overridepublic CellStyle getTitleStyle(short color) {CellStyle titleStyle = workbook.createCellStyle();Font font = this.workbook.createFont();font.setBold(true); // 字体加粗titleStyle.setFont(font);titleStyle.setAlignment(HorizontalAlignment.CENTER);//居中titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中titleStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());//设置颜色(黄色)titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);titleStyle.setBorderRight(BorderStyle.THIN);//设置右边框titleStyle.setAlignment(CellStyle.ALIGN_CENTER);titleStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);titleStyle.setWrapText(true);return titleStyle;}@Overridepublic CellStyle stringSeptailStyle(Workbook workbook, boolean isWarp) {CellStyle style = workbook.createCellStyle();style.setAlignment(CellStyle.ALIGN_CENTER);style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);style.setDataFormat(STRING_FORMAT);if (isWarp) {style.setWrapText(true);}return style;}@Overridepublic CellStyle getHeaderStyle(short color) {CellStyle titleStyle = workbook.createCellStyle();Font font = workbook.createFont();font.setFontHeightInPoints((short) 12);titleStyle.setFont(font);titleStyle.setAlignment(CellStyle.ALIGN_CENTER);titleStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);return titleStyle;}@Overridepublic CellStyle stringNoneStyle(Workbook workbook, boolean isWarp) {CellStyle style = workbook.createCellStyle();style.setAlignment(CellStyle.ALIGN_CENTER);style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);style.setDataFormat(STRING_FORMAT);if (isWarp) {style.setWrapText(true);}return style;}
}

VO实体类 对应的是表的列名

package com.hollysys.server.vo;import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.Data;import javax.validation.constraints.NotBlank;/*** @Author: ligang* @Date: 2019/12/11 9:48*/
@Data
public class ExcelEmployeeVo {@Excel(name = "序号", orderNum = "0")private Integer rowNum;//isColumnHidden = true 隐藏列@Excel(name = "id",isColumnHidden = true)private Integer id;@Excel(name = "姓名", orderNum = "1")private String name;@Excel(name = "工资号", orderNum = "2")private String salaryNum;@Excel(name = "性别", orderNum = "3")private String gender;@Excel(name = "单位", orderNum = "4",width = 20)private String departmentName;@Excel(name = "职务", orderNum = "5")private String roleName;@Excel(name = "资格证书", orderNum = "6",width = 20,isWrap = true)private String licenses;
}

Controller 1 未设置表头版本

   @ApiOperation("根据节点导出人员信息Excel表")@GetMapping("/exportExcel")public ApiResultData exportExcel(@RequestParam("path") String path,@RequestParam("deptName") String deptName, HttpServletResponse response) {// 查询要导出的数据List<ExcelEmployeeVo> list = pmsEmployeeService.getListEmployee(path);EasyPoiUtil.exportExcel(list,deptName+"人员信息","人员信息",ExcelEmployeeVo.class,deptName+"人员信息.xls",response);return new ApiResultData(1,"成功");}

Controller 2 设置表头版本

/***根据节点导出人员信息Excel表* @param path* @param deptName* @param response* @return*/@ApiOperation("根据节点导出人员信息Excel表")@GetMapping("/exportExcel")public ApiResultData exportExcel(@RequestParam("path") String path,@RequestParam("deptName") String deptName, HttpServletResponse response) {// 查询要导出的数据List<ExcelEmployeeVo> list = pmsEmployeeService.getListEmployee(path);// 主要导出方法ExportParams exportParams = new ExportParams();exportParams.setTitle(deptName+"人员信息");exportParams.setSheetName("人员信息");exportParams.setStyle(NewExcelExportStylerDefaultImpl.class);Workbook workbook = ExcelExportUtil.exportExcel(exportParams, ExcelEmployeeVo.class, list);try {response.setCharacterEncoding("UTF-8");response.setHeader("content-Type", "application/vnd.ms-excel");response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(deptName+"人员信息.xls", "UTF-8"));workbook.write(response.getOutputStream());} catch (IOException e) {e.printStackTrace();}return new ApiResultData(1,"成功");}

Service 查询导出Excel人员数据

List<ExcelEmployeeVo> getListEmployee(String path);

ServiceImpl

 /*** 获取表格** @param path* @return*/@Overridepublic List<ExcelEmployeeVo> getListEmployee(String path) {// 获取部门IDList<Integer> deptIds = pmsDepartmentMapper.getDeptIdsByPath(path);// 获取表格List<ExcelEmployeeVo> list = pmsEmployeeMapper.getExcelList(deptIds);for (ExcelEmployeeVo excelEmployeeVo : list) {List<Integer> licenseIds =employeeLicensesMapper.getLicensesByEmployee(excelEmployeeVo.getId());// 查询证书名称if (licenseIds.size() > 0) {List<String> licensesName = pmsLicensesMapper.getLicensesListById(licenseIds);String strLicenses = String.join("\n", licensesName);excelEmployeeVo.setLicenses(strLicenses);}}return list;}

导出时分割

@Overridepublic List<ExcelDevRecordVo> getRecordListByStation(Integer stationId) {List<ExcelDevRecordVo> excelDevRecordVos =pmsDevRecordMapper.getRecordListByStationId(stationId);for (ExcelDevRecordVo excelDevRecordVo : excelDevRecordVos) {if (excelDevRecordVo.getProperty() != null) {List<Integer> pids = JSON.parseArray(excelDevRecordVo.getProperty(), Integer.class);if (pids.size() > 0) {List<String> propertyList = pmsCfgPropertyMapper.getNamesByIds(pids);String propertyStr = String.join(";", propertyList);excelDevRecordVo.setProperty(propertyStr);}}if (excelDevRecordVo.getContent() != null) {List<Integer> tids = JSON.parseArray(excelDevRecordVo.getContent(), Integer.class);if (tids.size() > 0) {List<String> taskList = pmsCfgTaskContentMapper.getNamesByIds(tids);String contentStr = String.join(";"+"\n", taskList);excelDevRecordVo.setContent(contentStr);}}if (excelDevRecordVo.getChangeArea() != null) {List<Integer> cids = JSON.parseArray(excelDevRecordVo.getChangeArea(), Integer.class);if (cids.size() > 0) {List<String> devList = pmsDevRecordMapper.getNamesByIds(cids);String devStr = String.join(";", devList);excelDevRecordVo.setChangeArea(devStr);}}if (excelDevRecordVo.getDevPosition() != null) {List<Integer> pids = JSON.parseArray(excelDevRecordVo.getDevPosition(), Integer.class);if (pids.size() > 0) {List<String> devList = pmsCfgPositionMapper.getNamesByIds(pids);String devStr = String.join(";", devList);excelDevRecordVo.setDevPosition(devStr);}}}return excelDevRecordVos;}

Mapper

/*** 查找节点下的单位id列表* @return List*/List<Integer> getDeptIdsByPath(String path);
  /*** 查询Excel人员导出数据** @param deptIds* @return*/List<ExcelEmployeeVo> getExcelList(@Param("deptIds") List<Integer> deptIds);

Mapper.xml

<select id="getDeptIdsByPath" resultType="java.lang.Integer">SELECT id FROM pms_department WHERE path LIKE CONCAT(#{path},'%') AND is_del = 0</select>
<select id="getExcelList" resultType="com.hollysys.server.vo.ExcelEmployeeVo">SELECT@rownum := @rownum + 1 AS rownum, res.* FROM(SELECTe.id,e.`name`,e.salary_num salaryNum,e.gender,d.`name` departmentName,r.`name` roleNameFROMpms_employee eLEFT JOIN pms_role r ON e.role_id = r.idLEFT JOIN pms_department d ON e.department_id = d.idWHEREe.is_del = 0 AND d.is_del = 0 AND e.name != 'admin' AND e.is_public = 0<if test="deptIds != null and deptIds.size()>0 ">AND e.department_id IN<foreach collection="deptIds" item="deptId" index="index" open="(" close=")" separator=",">#{deptId}</foreach></if>ORDER BYe.gmt_create DESC) res , ( SELECT @rownum := 0 ) r</select>

复杂表头

复杂表头

EasyPoi 导出表格并设置表头相关推荐

  1. easypoi导出excel不设置样式_POI Excel导出样式设置

    HSSFSheet sheet = workbook.createSheet("sheetName"); //创建sheet sheet.setVerticallyCenter(t ...

  2. easypoi导出excel不设置样式_EasyPOI 导出excel设置边框,背景颜色,字体样式

    EasyPOI 导出excel设置边框,背景颜色,字体样式 EasyPOI 导出代码示例ExportParams exportParams = new ExportParams(); exportPa ...

  3. easypoi导出隔行样式设置

    导出excel需要设置隔行背景样式,如下图: 1.ExcelUtil 导出工具类 /*** 导出设置隔行背景色* @param params* @param list* @param pojoClas ...

  4. (Table)操作:Element-ui 中 Table 表格的设置表头/去除下标线/设置行间距等属性的使用及 slot-scope=“scope“ 的使用案例

    Ⅰ.Element-ui 提供的Table组件与想要目标情况的对比: 1.Element-ui 提供Table组件情况: 其一.Element-ui 自提供的Table代码情况为(示例的代码): // ...

  5. easypoi导出excel不设置样式_EasyExcel为单个Cell设置样式

    EasyExcel是阿里巴巴对POI封装的一个库,号称解决了POI的OOM问题,并且在使用上也更方便一些 然而我在使用的时候发现还是有很多坑,其中一个比较头疼的是对单个单元格样式的设置.EasyExc ...

  6. Vue使用Export2Excel导出表格时隐藏表头

    真实需求并不是要隐藏表头,而是因为后端返回的数据就把表头给拼上去了... 所以不能再加一个header. 直接再代码中不写header,会报错 excel.export_json_to_excel({ ...

  7. easypoi导出excel不设置样式_解决EasyPoi导出excel文件后打开提示格式错误的问题

    excel文件下载成功后打开文件遇到错误 之前的下载代码: private static void downLoadExcel(String fileName, HttpServletResponse ...

  8. JAVA导出excel如何设置表头跨行或者跨列,跪求各位大神了

    sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 0));// 开始行,结束行,开始列,结束列.只能是POI了吧?java还有其他方法吗? 转载于 ...

  9. vue+elementui系统利用Export2Excel.js将表格内容导出到excel,并设置表头文字水平垂直居中

    写在前面:这是纯前端导出,导出的表格是二级表头,内容是四级单元格(单元格内有四小格),这几个点学会之后应该能适应大部分导出excel的需求了.本次功能记录真实有效.对于之前没接触过导出excel需求的 ...

最新文章

  1. MySQL中MyISAM 和 InnoDB 的基本区别
  2. 上海博彦科技 千万别来_这个年产值2870亿元的科技园区,将率多家企业亮相本届服贸会...
  3. ES6 iterator 迭代器
  4. python pymysql用法_Python使用pymysql小技巧
  5. CNN 用于手写体识别 matlab 代码理解
  6. 全国计算机一级考试难度高吗,计算机等级考试分几级 考试难度大不大
  7. Kaggle比赛——预测未来销售(一)
  8. bim 骗局_来自建筑行业的BIM骗局
  9. windows cmd批处理终端 快速编辑模式
  10. 计算机考研的初试和复试的区别,考研初试和复试之间的区别
  11. selenium怎样定位web提示语
  12. 跨域问题(Vue开发中遇到的跨域问题)以及解决方法
  13. chromium 下载地址
  14. 测试用例之因果图分析法
  15. itunes无法安装到win7系统更新服务器失败怎么办啊,Win7系统安装iTunes失败出错无法安装的解决方法...
  16. ROS小车基于yocs_smoother_velocity做速度平滑处理
  17. 结合GSM协议文档与Tems工具捕捉到的GSM手机数据,分析L3消息。以0418-8r0为例.
  18. Android实现控制第三方音乐播放器暂停/播放
  19. 工程制图 ( 制图的基本知识和基本技能)
  20. css获取第n个元素之后所有的元素

热门文章

  1. #第七章 双波不干涉理论 ​一、双波不干涉理论的分级方法
  2. JavaSE阶段笔记
  3. 睡眠助手APP开发解决方案
  4. input输入框只能输入11位数字
  5. 企业实战, java、spingboot微信扫码支付,页面生成微信二维码,微信扫码付款,websocket通知,处理订单!复制粘贴代码直接开干
  6. php药膳 源码,药膳
  7. 【leetcode刷题】找到需补充粉笔的学生编号
  8. parent.layer.open打开的页面向上个页面传值
  9. java学习0701(前端内容知识)
  10. BLDC在3D风扇屏(全息风扇屏原理)上的应用----Trinamic(TMC)解决方案