一、POI介绍

Java POI有很多组件组成,其中有用于操作Excel格式文件的HSSF和用于操作Word的HWPF,其中常用的的包有:

二、xml引入依赖

<!--读取excel文件-->
<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.17</version>
</dependency>
<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.17</version>
</dependency>

三、使用Excel导出实例

导出需要提供要导出的数据,和定义Excel的格式(sheel名,表头,表格数据,宽度,及一些样式等)

controller 层获取输出流,设置文件类型,头信息,文件名等

@PostMapping("bookExcel")@ApiOperation("武侠小说列表导出")public void getBookExcel(HttpServletResponse response,String bookIds) {//从response中获取输出流try (OutputStream outputStream = response.getOutputStream()) {List<Book> bookList =bookService .selectAllExcel(bookIds);response.setContentType("application/vnd.ms-excel");response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("武侠小说汇总导出.xlsx", "UTF-8"));boolean success = excelExportService.bookExcel(outputStream, bookList);outputStream.flush();} catch (Exception e) {e.printStackTrace();}}

定义:Excel的表头,填充每个单元格数据,列宽度,sheel名

public boolean bookExcel(OutputStream outputStream, List<Book> bookList){List<String[]> content = new ArrayList<>();for (Book book : bookList) {String[] str=new String[7];str[0] = String.valueOf(book.getBookId());str[1] = String.valueOf(isNull(book.getBookname()));str[2] = String.valueOf(isNull(book.getAuthorname()));str[3] = String.valueOf(isNull(book.getMainperson()));str[4] = String.valueOf(isNull(book.getDepartment()));str[5] = String.valueOf(isNull(book.getEsoterica()));str[6] = String.valueOf(isNull(book.getCreatetime()));content.add(str);}int[] widths = {3000,6000,4000,8000,8000,8000,4000};List<String> title = new ArrayList<>();title.add("编号ID");title.add("书名");title.add("作者");title.add("主要人物");title.add("主要门派");title.add("出现武功高");title.add("出版日期");Workbook sxssfWorkbook=excelExportUtils.export(title,"书籍导出", widths, content);// 数据写入try {sxssfWorkbook.write(outputStream);} catch (IOException e) {e.printStackTrace();return false;}return true;}

通用的Excel导出方法:

public SXSSFWorkbook export(List<String> title, String name, int[] widths, List<String[]> content) {SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook();CellStyle titleStyle = titleStyle(sxssfWorkbook);CellStyle tableStyle = tableStyle(sxssfWorkbook);//单元名:SXSSFSheet sheet = sxssfWorkbook.createSheet(name);//每一列的宽度for (int i = 0; i < widths.length; i++) {sheet.setColumnWidth(i, widths[i]);}//设置标题SXSSFRow row =sheet.createRow(0);Cell cell = null;for (int i = 0; i < title.size(); i++) {cell = row.createCell(i);cell.setCellStyle(titleStyle);cell.setCellValue(title.get(i));}//设置内容if (content != null) {int num = 1;for (String[] contents : content) {row = sheet.createRow(num++);for (int i = 0; i < contents.length; i++) {cell = row.createCell(i);cell.setCellStyle(tableStyle);cell.setCellValue(contents[i]);}}}return sxssfWorkbook;}

设置表格内容样式:

public CellStyle titleStyle(SXSSFWorkbook workbook) {CellStyle titleStyle = workbook.createCellStyle();//设置字体Font font =workbook.createFont();font.setFontName("宋体");//设置字体font.setBold(true);//字体加粗font.setItalic(false);//字体是否倾斜font.setFontHeightInPoints((short)22);//设置字体大小font.setColor(IndexedColors.BLACK.index);//设置字体颜色titleStyle.setFont(font);//设置颜色://设置前景颜色titleStyle.setFillForegroundColor(IndexedColors.BRIGHT_GREEN.index);//设置颜色填充规则titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);//设置对齐方式:titleStyle.setAlignment(HorizontalAlignment.CENTER);titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);//设置边框样式:titleStyle.setBorderTop(BorderStyle.THIN);titleStyle.setBorderBottom(BorderStyle.THIN);titleStyle.setBorderLeft(BorderStyle.THIN);titleStyle.setBorderLeft(BorderStyle.THIN);//设置边框颜色:titleStyle.setBottomBorderColor(IndexedColors.BLACK.index);titleStyle.setTopBorderColor(IndexedColors.BLACK.index);titleStyle.setLeftBorderColor(IndexedColors.BLACK.index);titleStyle.setRightBorderColor(IndexedColors.BLACK.index);return titleStyle;}

导出带分组的Excel:

@Data
public class ExcelVo {//每一行数据private List<String> content = new ArrayList<>();//该行对应的子集数据private List<ExcelVo> excelVos = new ArrayList<>();
}

设置数据:

public boolean ExcelGroup(OutputStream outputStream, List<Book> bookList){// 设置数据List<ExcelVo> excelVoList = new ArrayList<>();if (bookList != null) {for (Book book : bookList) {ExcelVo excelVo = new ExcelVo();excelVo.getContent().add(String.valueOf(book.getBookId()));excelVo.getContent().add(book.getBookname());excelVo.getContent().add(book.getAuthorname());excelVo.getContent().add(book.getMainperson());excelVo.getContent().add(book.getDepartment());excelVo.getContent().add(book.getEsoterica());excelVoList.add(excelVo);List<Characters> list1 = characterMapper.selectBySource(book.getBookname());if (list1 != null) {//获取二级for (Characters ch : list1) {ExcelVo secondExcelVo = new ExcelVo();secondExcelVo.getContent().add(String.valueOf(ch.getCharacterId()));secondExcelVo.getContent().add(ch.getName());secondExcelVo.getContent().add(ch.getEsoterica());secondExcelVo.getContent().add(ch.getDepartment());secondExcelVo.getContent().add("-");secondExcelVo.getContent().add("-");excelVo.getExcelVos().add(secondExcelVo);}}}}int[] widths = {3000,6000,4000,8000,8000,8000,4000};List<String> title = new ArrayList<>();title.add("编号ID");title.add("书名");title.add("作者");title.add("主要人物");title.add("主要门派");title.add("出现武功");Workbook sxssfWorkbook=excelExportUtils.exportGroup(title,"书籍导出", widths, excelVoList);// 数据写入try {sxssfWorkbook.write(outputStream);} catch (IOException e) {e.printStackTrace();return false;}return true;
}

调用Excel生成方法:

public Workbook exportGroup(List<String> title, String name, int[] widths,List<ExcelVo> excelVoList) {SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(-1);Sheet sheet = sxssfWorkbook.createSheet(name);CellStyle tableStyle = tableStyle(sxssfWorkbook);CellStyle titleStyle = titleStyle(sxssfWorkbook);CellStyle leftStyle = titleStyle(sxssfWorkbook);//设置每一列单元格宽度for (int i = 0; i < widths.length; i++) {sheet.setColumnWidth(i, widths[i]);}Row row = sheet.createRow(0);Cell cell = null;for (int i = 0; i < title.size(); i++) {cell = row.createCell(i);cell.setCellStyle(titleStyle);cell.setCellValue(title.get(i));}if (excelVoList != null && excelVoList.size() > 0) {exportGroup(sheet, excelVoList, 1, tableStyle, leftStyle);}//将组合的"-"号显示在上方sheet.setRowSumsBelow(false);return sxssfWorkbook;
}public int exportGroup(Sheet sheet, List<ExcelVo> excelVoList, int num, CellStyle tableStyle, CellStyle leftStyle) {Row row = null; Cell cell = null;for (ExcelVo excelVo : excelVoList) {row = sheet.createRow(num++);//记录分组开始行号int start = num;for (int i = 0; i < excelVo.getContent().size(); i++) {cell = row.createCell(i);if (i == 0) {     cell.setCellStyle(leftStyle); //第一列数据左对齐} else {cell.setCellStyle(tableStyle);}cell.setCellValue(Optional.ofNullable(excelVo.getContent().get(i)).orElse(""));}//如果改行有子集数据,填充子集数据,获取分组结束行号if (excelVo.getExcelVos() != null && excelVo.getExcelVos().size() > 0) {num = exportGroup(sheet, excelVo.getExcelVos(), num, tableStyle, leftStyle);//行分组sheet.groupRow(start, num - 1);//设置默认收缩sheet.setRowGroupCollapsed(start,true);}}return num;
}

POI 导出Excel相关推荐

  1. POI 导出excel带小数点的数字格式显示不对解决方法

    POI 导出excel带小数点的数字格式显示不对解决方法 参考文章: (1)POI 导出excel带小数点的数字格式显示不对解决方法 (2)https://www.cnblogs.com/firstd ...

  2. cpu java poi 导出_java基于poi导出excel透视表代码实例

    这篇文章主要介绍了java基于poi导出excel透视表代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 从前,我是一个前端程序猿,怀着对打通 ...

  3. @excel注解_java bean 一对多,多对一 poi导出excel表格

    最近造了个poi导出 excel轮子 特点 java bean 一对多.多对一关系合并单元行 支持图片导出 Bean 一对多关系合并行 代码 public class User { @Excel(na ...

  4. Java POI 导出EXCEL经典实现 Java导出Excel

    转自http://blog.csdn.net/evangel_z/article/details/7332535 在web开发中,有一个经典的功能,就是数据的导入导出.特别是数据的导出,在生产管理或者 ...

  5. SpringMVC+Hibernate +MySql+ EasyUI实现POI导出Excel(二)

    为什么80%的码农都做不了架构师?>>> SpringMVC+Hibernate +MySql+ EasyUI实现CRUD(一) 大概的截图.很简单的小功能 注:使用的是MyEcli ...

  6. springboot中使用poi导出excel文件(亲测实现了第一个功能)

    1.POI简介 Jakarta POI 是一套用于访问微软格式文档的Java API. 组件HWPF用于操作Word的; 组件HSSF用于操作Excel格式文件. 2.常用组件 HSSFWorkboo ...

  7. java poi 导出excel 数字有问题

    在用poi导出excel时 导出的数字为文本格式(左上角有绿色三角) 原因: cell.setCellType(Cell.CELL_TYPE_NUMERIC); cell.setCellValue( ...

  8. java excel 导出图片_JAVA 使用 POI 导出 EXCEL 自定义背景颜色

    开发中常用表格导入和导出 Excel 是常见的功能. 在这里分享下使用 POI 导出表格的简单实现,也是为大家提供个思路吧,抛砖引玉,话不多说直接上代码. 1.项目引入 maven 依赖 <!- ...

  9. POI导出EXCEL设置高度和宽度

    -------------------------------------------------------------------------------SSFRow hssfRow = shee ...

  10. Java和poi导出excel报表

    一:poi jar下载地址:点击打开链接: 二:工程截图: 三:运行效果截图: 四:源代码: Student.java: package com.poi.bean;import java.util.D ...

最新文章

  1. python3语法错误-使用Python 3打印时出现语法错误
  2. python爬虫怎么爬小说_python从爬虫基础到爬取网络小说实例
  3. python报告 No module named 'main'错误
  4. 草稿 断开式绑定combobox
  5. java堆排序解决topk问题,利用堆排序来解决topK问题
  6. scrapy.request
  7. 为热门项目 若依(ruoyi) 添加flyway,自动管理数据库版本
  8. Oracle 10g 安装教程
  9. 配置阿里云镜像加速器
  10. 海思3559万能平台搭建:YUV422的踩坑记录
  11. 大话无线通讯基础之:WIFI和5G信道划分
  12. 基于文本挖掘的情人节微信聊天记录情感分析
  13. wps目录怎么加一条_WPS中如何正确插入目录_WPS怎么做目录
  14. 【学数据结构】-----串(顺序串、堆串、块链串)(7000字总结+代码+图)
  15. Android Studio 依赖Moudle
  16. 微信小程序--实现按钮跳转另一个页面
  17. 用keil软件完成STM32汇编程序的编写
  18. 国内免费(开源)CMS系统【大全】
  19. IMSI,SN,IMEI分别是什么意思
  20. unity 烘焙参数 设置_Unity5.×烘焙常规处理心得

热门文章

  1. EasyPoi Excel简单导出导入
  2. Hides for Mac v5.6.0.1 一键隐藏所有应用
  3. shiro学习一 (开涛的跟我学系列 ) 身份验证
  4. 安卓广告机带4G一体开发
  5. 人工智能/数据科学比赛汇总 2019.9
  6. python+pyecharts画地图
  7. 《SQL 入门教程》示例数据库
  8. 使用树莓派3B+ 制作一个属于自己的无线AP 无线路由器 一个Wi-Fi热点
  9. phpstorm 配置 Xdebug 调试
  10. spotify mp3_创建无监督学习的Spotify播放列表