添加依赖

    1. <dependency>
    2. <groupId>org.springframework.boot</groupId>
    3. <artifactId>spring-boot-starter-web</artifactId>
    4. </dependency>
    5. <dependency>
    6. <groupId>org.springframework.boot</groupId>
    7. <artifactId>spring-boot-starter-test</artifactId>
    8. <scope>test</scope>
    9. </dependency>
    10. <!-- 导出excel -->
    11. <dependency>
    12. <groupId>org.apache.poi</groupId>
    13. <artifactId>poi</artifactId>
    14. <version>3.14</version>
    15. </dependency>
    16. <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
    17. <dependency>
    18. <groupId>org.apache.poi</groupId>
    19. <artifactId>poi-ooxml</artifactId>
    20. <version>3.14</version>
    21. </dependency>
    22. <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-contrib -->
    23. <dependency>
    24. <groupId>org.apache.poi</groupId>
    25. <artifactId>poi-contrib</artifactId>
    26. <version>3.6</version>
    27. </dependency>
    28. <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
    29. <dependency>
    30. <groupId>org.apache.poi</groupId>
    31. <artifactId>poi-ooxml-schemas</artifactId>
    32. <version>3.17</version>
    33. </dependency>
    34. <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad -->
    35. <dependency>
    36. <groupId>org.apache.poi</groupId>
    37. <artifactId>poi-scratchpad</artifactId>
    38. <version>3.17</version>
    39. </dependency>

    新建一个实体类,命名为User.java;

    1. package com.twf.springcloud.ExportExcel.po;
    2. import java.io.Serializable;
    3. public class User implements Serializable{
    4. private static final long serialVersionUID = -9180229310895087286L;
    5. private String name; // 姓名
    6. private String sex; // 性别
    7. private Integer age; // 年龄
    8. private String phoneNo; // 手机号
    9. private String address; // 地址
    10. private String hobby; // 爱好
    11. public User(String name, String sex, Integer age, String phoneNo, String address, String hobby) {
    12. super();
    13. this.name = name;
    14. this.sex = sex;
    15. this.age = age;
    16. this.phoneNo = phoneNo;
    17. this.address = address;
    18. this.hobby = hobby;
    19. }
    20. public String getName() {
    21. return name;
    22. }
    23. public void setName(String name) {
    24. this.name = name;
    25. }
    26. public String getSex() {
    27. return sex;
    28. }
    29. public void setSex(String sex) {
    30. this.sex = sex;
    31. }
    32. public Integer getAge() {
    33. return age;
    34. }
    35. public void setAge(Integer age) {
    36. this.age = age;
    37. }
    38. public String getPhoneNo() {
    39. return phoneNo;
    40. }
    41. public void setPhoneNo(String phoneNo) {
    42. this.phoneNo = phoneNo;
    43. }
    44. public String getAddress() {
    45. return address;
    46. }
    47. public void setAddress(String address) {
    48. this.address = address;
    49. }
    50. public String getHobby() {
    51. return hobby;
    52. }
    53. public void setHobby(String hobby) {
    54. this.hobby = hobby;
    55. }
    56. @Override
    57. public String toString() {
    58. return "User [name=" + name + ", sex=" + sex + ", age=" + age + ", phoneNo=" + phoneNo + ", address=" + address
    59. + ", hobby=" + hobby + "]";
    60. }
    61. }

    新建一个excel样式工具类;

    1. package com.twf.springcloud.ExportExcel.utils;
    2. import org.apache.poi.hssf.usermodel.HSSFCellStyle;
    3. import org.apache.poi.hssf.usermodel.HSSFFont;
    4. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    5. import org.apache.poi.hssf.util.HSSFColor;
    6. import org.apache.poi.ss.usermodel.CellStyle;
    7. import org.apache.poi.ss.usermodel.Font;
    8. import org.apache.poi.xssf.streaming.SXSSFCell;
    9. import org.apache.poi.xssf.streaming.SXSSFRow;
    10. import org.apache.poi.xssf.streaming.SXSSFSheet;
    11. import org.apache.poi.xssf.streaming.SXSSFWorkbook;
    12. /**
    13. * excle样式工具类
    14. */
    15. public class ExcelFormatUtil {
    16. /**
    17. * 设置报表头样式
    18. * @param workbook
    19. * @return
    20. */
    21. public static CellStyle headSytle(SXSSFWorkbook workbook){
    22. // 设置style1的样式,此样式运用在第二行
    23. CellStyle style1 = workbook.createCellStyle();// cell样式
    24. // 设置单元格背景色,设置单元格背景色以下两句必须同时设置
    25. style1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);// 设置填充样式
    26. style1.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);// 设置填充色
    27. // 设置单元格上、下、左、右的边框线
    28. style1.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    29. style1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    30. style1.setBorderRight(HSSFCellStyle.BORDER_THIN);
    31. style1.setBorderTop(HSSFCellStyle.BORDER_THIN);
    32. Font font1 = workbook.createFont();// 创建一个字体对象
    33. font1.setBoldweight((short) 10);// 设置字体的宽度
    34. font1.setFontHeightInPoints((short) 10);// 设置字体的高度
    35. font1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 粗体显示
    36. style1.setFont(font1);// 设置style1的字体
    37. style1.setWrapText(true);// 设置自动换行
    38. style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 设置单元格字体显示居中(左右方向)
    39. style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 设置单元格字体显示居中(上下方向)
    40. return style1;
    41. }
    42. /**
    43. * 设置报表体样式
    44. * @param wb
    45. * @return
    46. */
    47. public static CellStyle contentStyle(SXSSFWorkbook wb){
    48. // 设置style1的样式,此样式运用在第二行
    49. CellStyle style1 = wb.createCellStyle();// cell样式
    50. // 设置单元格上、下、左、右的边框线
    51. style1.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    52. style1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    53. style1.setBorderRight(HSSFCellStyle.BORDER_THIN);
    54. style1.setBorderTop(HSSFCellStyle.BORDER_THIN);
    55. style1.setWrapText(true);// 设置自动换行
    56. style1.setAlignment(HSSFCellStyle.ALIGN_LEFT);// 设置单元格字体显示居中(左右方向)
    57. style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 设置单元格字体显示居中(上下方向)
    58. return style1;
    59. }
    60. /**
    61. * 设置报表标题样式
    62. * @param workbook
    63. * @return
    64. */
    65. public static HSSFCellStyle titleSytle(HSSFWorkbook workbook,short color,short fontSize){
    66. // 设置style1的样式,此样式运用在第二行
    67. HSSFCellStyle style1 = workbook.createCellStyle();// cell样式
    68. // 设置单元格背景色,设置单元格背景色以下两句必须同时设置
    69. //style1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);// 设置填充样式
    70. //short fcolor = color;
    71. if(color != HSSFColor.WHITE.index){
    72. style1.setFillForegroundColor(color);// 设置填充色
    73. }
    74. // 设置单元格上、下、左、右的边框线
    75. style1.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    76. style1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    77. style1.setBorderRight(HSSFCellStyle.BORDER_THIN);
    78. style1.setBorderTop(HSSFCellStyle.BORDER_THIN);
    79. HSSFFont font1 = workbook.createFont();// 创建一个字体对象
    80. font1.setBoldweight(fontSize);// 设置字体的宽度
    81. font1.setFontHeightInPoints(fontSize);// 设置字体的高度
    82. font1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 粗体显示
    83. style1.setFont(font1);// 设置style1的字体
    84. style1.setWrapText(true);// 设置自动换行
    85. style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 设置单元格字体显示居中(左右方向)
    86. style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 设置单元格字体显示居中(上下方向)
    87. return style1;
    88. }
    89. /**
    90. *设置表头
    91. * @param sheet
    92. */
    93. public static void initTitleEX(SXSSFSheet sheet, CellStyle header,String title[],int titleLength[]) {
    94. SXSSFRow row0 = sheet.createRow(0);
    95. row0.setHeight((short) 800);
    96. for(int j = 0;j<title.length; j++) {
    97. SXSSFCell cell = row0.createCell(j);
    98. //设置每一列的字段名
    99. cell.setCellValue(title[j]);
    100. cell.setCellStyle(header);
    101. sheet.setColumnWidth(j, titleLength[j]);
    102. }
    103. }
    104. }

    新建一个Service接口;

    1. package com.twf.springcloud.ExportExcel.sevice;
    2. import javax.servlet.http.HttpServletRequest;
    3. import javax.servlet.http.HttpServletResponse;
    4. import org.springframework.http.ResponseEntity;
    5. public interface ExportService {
    6. ResponseEntity<byte[]> exportExcel(HttpServletRequest request, HttpServletResponse response);
    7. }

    新建一个Service接口实现类;

    1. package com.twf.springcloud.ExportExcel.sevice.impl;
    2. import java.io.ByteArrayInputStream;
    3. import java.io.ByteArrayOutputStream;
    4. import java.io.IOException;
    5. import java.io.InputStream;
    6. import java.util.ArrayList;
    7. import java.util.List;
    8. import javax.servlet.http.HttpServletRequest;
    9. import javax.servlet.http.HttpServletResponse;
    10. import org.apache.poi.ss.usermodel.CellStyle;
    11. import org.apache.poi.xssf.streaming.SXSSFCell;
    12. import org.apache.poi.xssf.streaming.SXSSFRow;
    13. import org.apache.poi.xssf.streaming.SXSSFSheet;
    14. import org.apache.poi.xssf.streaming.SXSSFWorkbook;
    15. import org.slf4j.Logger;
    16. import org.slf4j.LoggerFactory;
    17. import org.springframework.http.ResponseEntity;
    18. import org.springframework.stereotype.Service;
    19. import com.twf.springcloud.ExportExcel.controller.BaseFrontController;
    20. import com.twf.springcloud.ExportExcel.po.User;
    21. import com.twf.springcloud.ExportExcel.sevice.ExportService;
    22. import com.twf.springcloud.ExportExcel.utils.ExcelFormatUtil;
    23. @Service
    24. public class ExportServiceImpl implements ExportService{
    25. Logger logger = LoggerFactory.getLogger(ExportServiceImpl.class);
    26. @Override
    27. public ResponseEntity<byte[]> exportExcel(HttpServletRequest request, HttpServletResponse response) {
    28. try {
    29. logger.info(">>>>>>>>>>开始导出excel>>>>>>>>>>");
    30. // 造几条数据
    31. List<User> list = new ArrayList<>();
    32. list.add(new User("唐三藏", "男", 30, "13411111111", "东土大唐", "取西经"));
    33. list.add(new User("孙悟空", "男", 29, "13411111112", "菩提院", "打妖怪"));
    34. list.add(new User("猪八戒", "男", 28, "13411111113", "高老庄", "偷懒"));
    35. list.add(new User("沙悟净", "男", 27, "13411111114", "流沙河", "挑担子"));
    36. BaseFrontController baseFrontController = new BaseFrontController();
    37. return baseFrontController.buildResponseEntity(export((List<User>) list), "用户表.xls");
    38. } catch (Exception e) {
    39. e.printStackTrace();
    40. logger.error(">>>>>>>>>>导出excel 异常,原因为:" + e.getMessage());
    41. }
    42. return null;
    43. }
    44. private InputStream export(List<User> list) {
    45. logger.info(">>>>>>>>>>>>>>>>>>>>开始进入导出方法>>>>>>>>>>");
    46. ByteArrayOutputStream output = null;
    47. InputStream inputStream1 = null;
    48. SXSSFWorkbook wb = new SXSSFWorkbook(1000);// 保留1000条数据在内存中
    49. SXSSFSheet sheet = wb.createSheet();
    50. // 设置报表头样式
    51. CellStyle header = ExcelFormatUtil.headSytle(wb);// cell样式
    52. CellStyle content = ExcelFormatUtil.contentStyle(wb);// 报表体样式
    53. // 每一列字段名
    54. String[] strs = new String[] { "姓名", "性别", "年龄", "手机号", "地址","爱好" };
    55. // 字段名所在表格的宽度
    56. int[] ints = new int[] { 5000, 5000, 5000, 5000, 5000, 5000 };
    57. // 设置表头样式
    58. ExcelFormatUtil.initTitleEX(sheet, header, strs, ints);
    59. logger.info(">>>>>>>>>>>>>>>>>>>>表头样式设置完成>>>>>>>>>>");
    60. if (list != null && list.size() > 0) {
    61. logger.info(">>>>>>>>>>>>>>>>>>>>开始遍历数据组装单元格内容>>>>>>>>>>");
    62. for (int i = 0; i < list.size(); i++) {
    63. User user = list.get(i);
    64. SXSSFRow row = sheet.createRow(i + 1);
    65. int j = 0;
    66. SXSSFCell cell = row.createCell(j++);
    67. cell.setCellValue(user.getName()); // 姓名
    68. cell.setCellStyle(content);
    69. cell = row.createCell(j++);
    70. cell.setCellValue(user.getSex()); // 性别
    71. cell.setCellStyle(content);
    72. cell = row.createCell(j++);
    73. cell.setCellValue(user.getAge()); // 年龄
    74. cell.setCellStyle(content);
    75. cell = row.createCell(j++);
    76. cell.setCellValue(user.getPhoneNo()); // 手机号
    77. cell.setCellStyle(content);
    78. cell = row.createCell(j++);
    79. cell.setCellValue(user.getAddress()); // 地址
    80. cell.setCellStyle(content);
    81. cell = row.createCell(j++);
    82. cell.setCellValue(user.getHobby()); // 爱好
    83. cell.setCellStyle(content);
    84. }
    85. logger.info(">>>>>>>>>>>>>>>>>>>>结束遍历数据组装单元格内容>>>>>>>>>>");
    86. }
    87. try {
    88. output = new ByteArrayOutputStream();
    89. wb.write(output);
    90. inputStream1 = new ByteArrayInputStream(output.toByteArray());
    91. output.flush();
    92. } catch (Exception e) {
    93. e.printStackTrace();
    94. } finally {
    95. try {
    96. if (output != null) {
    97. output.close();
    98. if (inputStream1 != null)
    99. inputStream1.close();
    100. }
    101. } catch (IOException e) {
    102. e.printStackTrace();
    103. }
    104. }
    105. return inputStream1;
    106. }
    107. }

    新建一个下载文件的通用controller;

    1. package com.twf.springcloud.ExportExcel.controller;
    2. import java.io.InputStream;
    3. import java.net.URLEncoder;
    4. import java.util.HashMap;
    5. import java.util.Map;
    6. import org.apache.poi.util.IOUtils;
    7. import org.slf4j.Logger;
    8. import org.slf4j.LoggerFactory;
    9. import org.springframework.http.HttpHeaders;
    10. import org.springframework.http.HttpStatus;
    11. import org.springframework.http.ResponseEntity;
    12. import org.springframework.util.StringUtils;
    13. import org.springframework.validation.annotation.Validated;
    14. @Validated
    15. public class BaseFrontController {
    16. /**
    17. * slf4j 日志 logger
    18. */
    19. protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    20. /**
    21. * 下载文件,纯SpringMVC的API来完成
    22. *
    23. * @param is 文件输入流
    24. * @param name 文件名称,带后缀名
    25. *
    26. * @throws Exception
    27. */
    28. public ResponseEntity<byte[]> buildResponseEntity(InputStream is, String name) throws Exception {
    29. logger.info(">>>>>>>>>>>>>>>>>>>>开始下载文件>>>>>>>>>>");
    30. if (this.logger.isDebugEnabled())
    31. this.logger.debug("download: " + name);
    32. HttpHeaders header = new HttpHeaders();
    33. String fileSuffix = name.substring(name.lastIndexOf('.') + 1);
    34. fileSuffix = fileSuffix.toLowerCase();
    35. Map<String, String> arguments = new HashMap<String, String>();
    36. arguments.put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    37. arguments.put("xls", "application/vnd.ms-excel");
    38. String contentType = arguments.get(fileSuffix);
    39. header.add("Content-Type", (StringUtils.hasText(contentType) ? contentType : "application/x-download"));
    40. if(is!=null && is.available()!=0){
    41. header.add("Content-Length", String.valueOf(is.available()));
    42. header.add("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + URLEncoder.encode(name, "UTF-8"));
    43. byte[] bs = IOUtils.toByteArray(is);
    44. logger.info(">>>>>>>>>>>>>>>>>>>>结束下载文件-有记录>>>>>>>>>>");
    45. logger.info(">>>>>>>>>>结束导出excel>>>>>>>>>>");
    46. return new ResponseEntity<>(bs, header, HttpStatus.OK);
    47. }else{
    48. String string="数据为空";
    49. header.add("Content-Length", "0");
    50. header.add("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + URLEncoder.encode(name, "UTF-8"));
    51. logger.info(">>>>>>>>>>>>>>>>>>>>结束下载文件-无记录>>>>>>>>>>");
    52. logger.info(">>>>>>>>>>结束导出excel>>>>>>>>>>");
    53. return new ResponseEntity<>(string.getBytes(), header, HttpStatus.OK);
    54. }
    55. }
    56. }

    新建一个controller,作为请求的入口;

    1. package com.twf.springcloud.ExportExcel.controller;
    2. import javax.servlet.http.HttpServletRequest;
    3. import javax.servlet.http.HttpServletResponse;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.http.ResponseEntity;
    6. import org.springframework.web.bind.annotation.RequestMapping;
    7. import org.springframework.web.bind.annotation.RestController;
    8. import com.twf.springcloud.ExportExcel.sevice.ExportService;
    9. @RestController
    10. @RequestMapping("/exportExcel/")
    11. public class ExportController {
    12. @Autowired
    13. private ExportService exportService;
    14. // 导出excel
    15. @RequestMapping("exportExcel")
    16. public ResponseEntity<byte[]> exportExcel(HttpServletRequest request, HttpServletResponse response) {
    17. return exportService.exportExcel(request,response);
    18. }
    19. }