1、添加POI依赖

  1. <dependency>
  2. <groupId>org.apache.poi</groupId>
  3. <artifactId>poi-ooxml</artifactId>
  4. <version>3.9</version>
  5. </dependency>

2、创建EXCEL实体类

  1. package com.example.demo.model;
  2. import java.io.Serializable;
  3. import java.util.List;
  4. public class ExcelData implements Serializable {
  5. private static final long serialVersionUID = 6133772627258154184L;
  6. /**
  7. * 表头
  8. */
  9. private List<String> titles;
  10. /**
  11. * 数据
  12. */
  13. private List<List<Object>> rows;
  14. /**
  15. * 页签名称
  16. */
  17. private String name;
  18. public List<String> getTitles() {
  19. return titles;
  20. }
  21. public void setTitles(List<String> titles) {
  22. this.titles = titles;
  23. }
  24. public List<List<Object>> getRows() {
  25. return rows;
  26. }
  27. public void setRows(List<List<Object>> rows) {
  28. this.rows = rows;
  29. }
  30. public String getName() {
  31. return name;
  32. }
  33. public void setName(String name) {
  34. this.name = name;
  35. }
  36. }

3、创建表格工具类

  1. package com.example.demo.core.utils;
  2. import com.example.demo.model.ExcelData;
  3. import org.apache.poi.ss.usermodel.*;
  4. import org.apache.poi.ss.usermodel.Font;
  5. import org.apache.poi.xssf.usermodel.XSSFCellStyle;
  6. import org.apache.poi.xssf.usermodel.XSSFColor;
  7. import org.apache.poi.xssf.usermodel.XSSFSheet;
  8. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  9. import org.apache.poi.xssf.usermodel.extensions.XSSFCellBorder.BorderSide;
  10. import javax.servlet.http.HttpServletResponse;
  11. import java.awt.Color;
  12. import java.io.File;
  13. import java.io.FileOutputStream;
  14. import java.io.OutputStream;
  15. import java.net.URLEncoder;
  16. import java.util.List;
  17. public class ExcelUtils {
  18. /**
  19. * 使用浏览器选择路径下载
  20. * @param response
  21. * @param fileName
  22. * @param data
  23. * @throws Exception
  24. */
  25. public static void exportExcel(HttpServletResponse response, String fileName, ExcelData data) throws Exception {
  26. // 告诉浏览器用什么软件可以打开此文件
  27. response.setHeader("content-Type", "application/vnd.ms-excel");
  28. // 下载文件的默认名称
  29. response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xls", "utf-8"));
  30. exportExcel(data, response.getOutputStream());
  31. }
  32. public static int generateExcel(ExcelData excelData, String path) throws Exception {
  33. File f = new File(path);
  34. FileOutputStream out = new FileOutputStream(f);
  35. return exportExcel(excelData, out);
  36. }
  37. private static int exportExcel(ExcelData data, OutputStream out) throws Exception {
  38. XSSFWorkbook wb = new XSSFWorkbook();
  39. int rowIndex = 0;
  40. try {
  41. String sheetName = data.getName();
  42. if (null == sheetName) {
  43. sheetName = "Sheet1";
  44. }
  45. XSSFSheet sheet = wb.createSheet(sheetName);
  46. rowIndex = writeExcel(wb, sheet, data);
  47. wb.write(out);
  48. } catch (Exception e) {
  49. e.printStackTrace();
  50. } finally {
  51. //此处需要关闭 wb 变量
  52. out.close();
  53. }
  54. return rowIndex;
  55. }
  56. private static int writeExcel(XSSFWorkbook wb, Sheet sheet, ExcelData data) {
  57. int rowIndex = 0;
  58. writeTitlesToExcel(wb, sheet, data.getTitles());
  59. rowIndex = writeRowsToExcel(wb, sheet, data.getRows(), rowIndex);
  60. autoSizeColumns(sheet, data.getTitles().size() + 1);
  61. return rowIndex;
  62. }
  63. /**
  64. * 设置表头
  65. *
  66. * @param wb
  67. * @param sheet
  68. * @param titles
  69. * @return
  70. */
  71. private static int writeTitlesToExcel(XSSFWorkbook wb, Sheet sheet, List<String> titles) {
  72. int rowIndex = 0;
  73. int colIndex = 0;
  74. Font titleFont = wb.createFont();
  75. //设置字体
  76. titleFont.setFontName("simsun");
  77. //设置粗体
  78. titleFont.setBoldweight(Short.MAX_VALUE);
  79. //设置字号
  80. titleFont.setFontHeightInPoints((short) 14);
  81. //设置颜色
  82. titleFont.setColor(IndexedColors.BLACK.index);
  83. XSSFCellStyle titleStyle = wb.createCellStyle();
  84. //水平居中
  85. titleStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
  86. //垂直居中
  87. titleStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
  88. //设置图案颜色
  89. titleStyle.setFillForegroundColor(new XSSFColor(new Color(182, 184, 192)));
  90. //设置图案样式
  91. titleStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
  92. titleStyle.setFont(titleFont);
  93. setBorder(titleStyle, BorderStyle.THIN, new XSSFColor(new Color(0, 0, 0)));
  94. Row titleRow = sheet.createRow(rowIndex);
  95. titleRow.setHeightInPoints(25);
  96. colIndex = 0;
  97. for (String field : titles) {
  98. Cell cell = titleRow.createCell(colIndex);
  99. cell.setCellValue(field);
  100. cell.setCellStyle(titleStyle);
  101. colIndex++;
  102. }
  103. rowIndex++;
  104. return rowIndex;
  105. }
  106. /**
  107. * 设置内容
  108. *
  109. * @param wb
  110. * @param sheet
  111. * @param rows
  112. * @param rowIndex
  113. * @return
  114. */
  115. private static int writeRowsToExcel(XSSFWorkbook wb, Sheet sheet, List<List<Object>> rows, int rowIndex) {
  116. int colIndex;
  117. Font dataFont = wb.createFont();
  118. dataFont.setFontName("simsun");
  119. dataFont.setFontHeightInPoints((short) 14);
  120. dataFont.setColor(IndexedColors.BLACK.index);
  121. XSSFCellStyle dataStyle = wb.createCellStyle();
  122. dataStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
  123. dataStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
  124. dataStyle.setFont(dataFont);
  125. setBorder(dataStyle, BorderStyle.THIN, new XSSFColor(new Color(0, 0, 0)));
  126. for (List<Object> rowData : rows) {
  127. Row dataRow = sheet.createRow(rowIndex);
  128. dataRow.setHeightInPoints(25);
  129. colIndex = 0;
  130. for (Object cellData : rowData) {
  131. Cell cell = dataRow.createCell(colIndex);
  132. if (cellData != null) {
  133. cell.setCellValue(cellData.toString());
  134. } else {
  135. cell.setCellValue("");
  136. }
  137. cell.setCellStyle(dataStyle);
  138. colIndex++;
  139. }
  140. rowIndex++;
  141. }
  142. return rowIndex;
  143. }
  144. /**
  145. * 自动调整列宽
  146. *
  147. * @param sheet
  148. * @param columnNumber
  149. */
  150. private static void autoSizeColumns(Sheet sheet, int columnNumber) {
  151. for (int i = 0; i < columnNumber; i++) {
  152. int orgWidth = sheet.getColumnWidth(i);
  153. sheet.autoSizeColumn(i, true);
  154. int newWidth = (int) (sheet.getColumnWidth(i) + 100);
  155. if (newWidth > orgWidth) {
  156. sheet.setColumnWidth(i, newWidth);
  157. } else {
  158. sheet.setColumnWidth(i, orgWidth);
  159. }
  160. }
  161. }
  162. /**
  163. * 设置边框
  164. *
  165. * @param style
  166. * @param border
  167. * @param color
  168. */
  169. private static void setBorder(XSSFCellStyle style, BorderStyle border, XSSFColor color) {
  170. style.setBorderTop(border);
  171. style.setBorderLeft(border);
  172. style.setBorderRight(border);
  173. style.setBorderBottom(border);
  174. style.setBorderColor(BorderSide.TOP, color);
  175. style.setBorderColor(BorderSide.LEFT, color);
  176. style.setBorderColor(BorderSide.RIGHT, color);
  177. style.setBorderColor(BorderSide.BOTTOM, color);
  178. }
  179. }

4、创建ExcelConstant

  1. package com.example.demo.core.constant;
  2. public class ExcelConstant {
  3. /**
  4. * 生成文件存放路径
  5. */
  6. public static final String FILE_PATH = "C:\\Users\\Administrator\\Desktop\\";
  7. /**
  8. * 表格默认名称
  9. */
  10. public static final String FILE_NAME = "TEST.xls";
  11. }

5、创建ExcelController

  1. package com.example.demo.controller;
  2. import com.example.demo.core.aop.AnnotationLog;
  3. import com.example.demo.core.constant.ExcelConstant;
  4. import com.example.demo.core.ret.RetResponse;
  5. import com.example.demo.core.ret.RetResult;
  6. import com.example.demo.core.ret.ServiceException;
  7. import com.example.demo.core.utils.ExcelUtils;
  8. import com.example.demo.model.ExcelData;
  9. import com.example.demo.model.UserInfo;
  10. import com.example.demo.service.UserInfoService;
  11. import com.github.pagehelper.PageHelper;
  12. import com.github.pagehelper.PageInfo;
  13. import io.swagger.annotations.Api;
  14. import io.swagger.annotations.ApiImplicitParam;
  15. import io.swagger.annotations.ApiImplicitParams;
  16. import io.swagger.annotations.ApiOperation;
  17. import org.apache.shiro.SecurityUtils;
  18. import org.apache.shiro.authc.IncorrectCredentialsException;
  19. import org.apache.shiro.authc.UsernamePasswordToken;
  20. import org.apache.shiro.subject.Subject;
  21. import org.springframework.web.bind.annotation.*;
  22. import javax.annotation.Resource;
  23. import javax.servlet.http.HttpServletResponse;
  24. import java.util.ArrayList;
  25. import java.util.List;
  26. @RestController
  27. @RequestMapping("excel")
  28. public class ExcelController {
  29. @Resource
  30. private UserInfoService userInfoService;
  31. @PostMapping("/test")
  32. public RetResult<Integer> test(){
  33. int rowIndex = 0;
  34. List<UserInfo> list = userInfoService.selectAlla(0, 0);
  35. ExcelData data = new ExcelData();
  36. data.setName("hello");
  37. List<String> titles = new ArrayList();
  38. titles.add("ID");
  39. titles.add("userName");
  40. titles.add("password");
  41. data.setTitles(titles);
  42. List<List<Object>> rows = new ArrayList();
  43. for(int i = 0, length = list.size();i<length;i++){
  44. UserInfo userInfo = list.get(i);
  45. List<Object> row = new ArrayList();
  46. row.add(userInfo.getId());
  47. row.add(userInfo.getUserName());
  48. row.add(userInfo.getPassword());
  49. rows.add(row);
  50. }
  51. data.setRows(rows);
  52. try{
  53. rowIndex = ExcelUtils.generateExcel(data, ExcelConstant.FILE_PATH + ExcelConstant.FILE_NAME);
  54. }catch (Exception e){
  55. e.printStackTrace();
  56. }
  57. return RetResponse.makeOKRsp(Integer.valueOf(rowIndex));
  58. }
  59. @GetMapping("/test2")
  60. public void test2(HttpServletResponse response){
  61. int rowIndex = 0;
  62. List<UserInfo> list = userInfoService.selectAlla(0, 0);
  63. ExcelData data = new ExcelData();
  64. data.setName("hello");
  65. List<String> titles = new ArrayList();
  66. titles.add("ID");
  67. titles.add("userName");
  68. titles.add("password");
  69. data.setTitles(titles);
  70. List<List<Object>> rows = new ArrayList();
  71. for(int i = 0, length = list.size();i<length;i++){
  72. UserInfo userInfo = list.get(i);
  73. List<Object> row = new ArrayList();
  74. row.add(userInfo.getId());
  75. row.add(userInfo.getUserName());
  76. row.add(userInfo.getPassword());
  77. rows.add(row);
  78. }
  79. data.setRows(rows);
  80. try{
  81. ExcelUtils.exportExcel(response,"test2",data);
  82. }catch (Exception e){
  83. e.printStackTrace();
  84. }
  85. }
  86. }




原文地址:Mr_初晨

Spring Boot:添加导出Excel表格功能的更多相关文章

  1. spring boot poi 导出Excel

    public class ExcelData implements Serializable { private static final long serialVersionUID = 444401 ...

  2. spring mvc项目中导出excel表格简单实现

    查阅了一些资料,才整理出spring mvc 项目导出excel表格的实现,其实很是简单,小计一下,方便以后查阅,也希望帮助有需要的朋友. 1.导入所需要依赖(Jar包).我使用的是maven,所以坐 ...

  3. Spring Boot 导出Excel表格

    Spring Boot 导出Excel表格 添加支持 <!--添加导入/出表格依赖--> <dependency> <groupId>org.apache.poi& ...

  4. PHP导入导出excel表格图片(转)

    写excel的时候,我用过pear的库,也用过pack压包的头,同样那些利用smarty等作的简单替换xml的也用过,csv的就更不用谈了.呵呵.(COM方式不讲了,这种可读的太多了,我也写过利用wp ...

  5. EasyUi通过POI 实现导出xls表格功能

    Spring +EasyUi+Spring Jpa(持久层) EasyUi通过POI 实现导出xls表格功能 EasyUi界面: 点击导出按钮实现数据导入到xls表格中 第一步:修改按钮事件: @Co ...

  6. PHP导入导出excel表格图片的代码和方法大全

    基本上导出的文件分为两种: 1:类Excel格式,这个其实不是传统意义上的Excel文件,只是因为Excel的兼容能力强,能够正确打开而已.修改这种文件后再保存,通常会提示你是否要转换成Excel文件 ...

  7. Element-ui组件库Table表格导出Excel表格

    安装npm install --save xlsx file-saver 两个插件的详细地址在下面 https://github.com/SheetJS/js-xlsxhttps://github.c ...

  8. java导出excel表格

    java导出excel表格: 1.导入jar包 <dependency> <groupId>org.apache.poi</groupId> <artifac ...

  9. NPOI导出excel表格应用

    最近接到一个需求,在原有系统上做二次开发 ,要求导出DataGridView数据到Excel表格中.要求如下: 兼容所有excel版本: 导出后excel各列的样式,字段类型不变. 成型如下:

随机推荐

  1. 第四章节 BJROBOT 线速度校正 【ROS全开源阿克曼转向智能网联无人驾驶车】

    BJROBOT 线速度校正   1.把小车平放在地板上,用卷尺作为测量刻度,选取车头或者车尾处作为小车的起点, 打开资料里的虚拟机,打开一个终端 ssh 过去主控端启动 roslaunch znjro ...

  2. SpringBoot整合Shiro权限框架实战

    什么是ACL和RBAC ACL Access Control list:访问控制列表 优点:简单易用,开发便捷 缺点:用户和权限直接挂钩,导致在授予时的复杂性,比较分散,不便于管理 例子:常见的文件系 ...

  3. Sqoop(二)常用命令及常数解析

    一.常用命令列举 二.命令及参数详解 1.数据库连接 2.import 3.export 4.hive

  4. 强大生产力工具Alfred

    今天要给大家介绍的工具是Alfred,一款Mac下的高效生产力产品.它能做什么呢?简单的说就是:让你能够通过打几个字,就可以完成原本需要一顿操作的事情.举一个简单的栗子:如果我们要在Google搜索一 ...

  5. 如何使用蓝湖设计稿同时适配PC及移动端

    如何使用蓝湖设计稿同时适配PC及移动端 项目需求: 一套代码同时适配PC及移动端 方案: pc端采用px布局,移动端采用rem布局,通过媒体查询(media query)切换 坑: 尝试过使用post ...

  6. 关于.NET中的控制反转(三)- 依赖注入之 Autofac

    一.Autofac简介 Autofac和其他容器的不同之处是它和C#语言的结合非常紧密,在使用过程中对你的应用的侵入性几乎为零,更容易与第三方的组件集成.Autofac的主要特性如下: 组件侵入性为零 ...

  7. Java菜鸟在IP问题踩坑了

    之前有做过获取客户端公网IP的项目 一般都是 正常的request.getRemoteAddr 或者request.getRemoteHost 可获取到客户端的公网IP, 或者项目部署在有nginx代 ...

  8. selenium自动化 | 借助百度AI开放平台识别验证码登录职教云

    #通过借助百度AI开放平台识别验证码登录职教云 from PIL import Image from aip import AipOcr import unittest # driver.get(zj ...

  9. explain select * from xuehao;

    mysql> explain select * from xuehao;+----+-------------+--------+------+---------------+------+-- ...

  10. leetcode 93. Restore IP Addresses(DFS, 模拟)

    题目链接 leetcode 93. Restore IP Addresses 题意 给定一段序列,判断可能组成ip数的所有可能集合 思路 可以采用模拟或者DFS的想法,把总的ip数分成四段,每段判断是 ...