org.a..._spring boot poi导出excel">
当前位置:   article > 正文

SpringBoot中使用poi导出Excel_spring boot poi导出excel

spring boot poi导出excel

在项目中导出excel是难免不可缺少的,总结了一下,可以copy直接用。有什么地方不足的还请指出。

注意:这里固定了前台入参形式为json字符串,主要有两个key(title标题,data数据)如下:{"title":{},"data":[{},{},{}]}

  • pom依赖
  1. <dependency>
  2. <groupId>org.apache.poi</groupId>
  3. <artifactId>poi</artifactId>
  4. <version>4.1.0</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>net.sf.json-lib</groupId>
  8. <artifactId>json-lib</artifactId>
  9. <version>2.4</version>
  10. <classifier>jdk15</classifier>
  11. </dependency>
  • 工具类:ExcelUtil(如果方法报错,看一下是否导错包了,必须有json-lib jdk15的依赖哦)json-lib是一个java类库,用来处理json数据,包括生成和解析。
  1. package com.mycompany.myapp.web.rest.util;
  2. import net.sf.json.JSONArray;
  3. import net.sf.json.JSONObject;
  4. import org.apache.poi.hssf.usermodel.*;
  5. import org.apache.poi.ss.usermodel.HorizontalAlignment;
  6. import org.springframework.beans.factory.annotation.Value;
  7. import org.springframework.stereotype.Component;
  8. import java.io.File;
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11. import java.util.ArrayList;
  12. import java.util.Iterator;
  13. import java.util.List;
  14. @Component
  15. public class ExcelExportUtil {
  16. //文件下载地址
  17. public static String DOWNLOAD_URL;
  18. @Value("${downloadUrl}")
  19. public void setDownloadUrl(String downloadUrl) {
  20. DOWNLOAD_URL = downloadUrl;
  21. }
  22. public static void outPutExcel(String jsonParam) throws Exception {
  23. JSONObject jsonObject = JSONObject.fromObject(jsonParam);
  24. //文件名
  25. String fileName = jsonObject.getString("fileName");
  26. //文件存放路径
  27. String url = DOWNLOAD_URL + fileName + ".xls";
  28. //标题
  29. String title = jsonObject.getString("title");
  30. JSONObject jsonObjectTitle = JSONObject.fromObject(title);
  31. String[] titleArray = new String[jsonObjectTitle.size()];
  32. Iterator iteratorTitle = jsonObjectTitle.keys();
  33. int m = 0;
  34. while (iteratorTitle.hasNext()){
  35. String key = (String)iteratorTitle.next();
  36. titleArray[m] = jsonObjectTitle.getString(key);
  37. m++;
  38. }
  39. //数据
  40. String data = jsonObject.getString("data");
  41. JSONArray jsonArray = JSONArray.fromObject(data);
  42. List<Object[]> dataList = new ArrayList<>();
  43. for(int i = 0;i<jsonArray.size();i++){
  44. JSONObject json = jsonArray.getJSONObject(i);
  45. Object[] objects = new Object[json.size()];
  46. Iterator iterator = json.keys();
  47. int n = 0;
  48. while (iterator.hasNext()){
  49. String key = (String)iterator.next();
  50. objects[n] = json.getString(key);
  51. n++;
  52. }
  53. dataList.add(objects);
  54. }
  55. //字段为null时设置为""
  56. for(int i =0;i<dataList.size();i++){
  57. Object[] obj = dataList.get(i);
  58. for(int j = 0;j<obj.length;j++){
  59. if(obj[j]==null||"null".equals(obj[j])){
  60. obj[j] = "";
  61. }
  62. }
  63. }
  64. //excel创建
  65. HSSFWorkbook workbook = new HSSFWorkbook();
  66. HSSFSheet sheet = workbook.createSheet(fileName);
  67. createTitle(workbook,sheet,titleArray);
  68. for(int i =0;i<dataList.size();i++){
  69. HSSFRow row = sheet.createRow(i+1);
  70. Object[] obj = dataList.get(i);
  71. for(int j = 0;j<obj.length;j++){
  72. row.createCell(j).setCellValue(obj[j].toString());
  73. }
  74. }
  75. File file = new File(url);
  76. //文件不存在则创建
  77. if(!file.exists())
  78. {
  79. try {
  80. file.createNewFile();
  81. } catch (IOException e) {
  82. e.printStackTrace();
  83. }
  84. }
  85. FileOutputStream outputStream = new FileOutputStream(url);
  86. workbook.write(outputStream);
  87. outputStream.close();
  88. }
  89. //创建表头
  90. private static void createTitle(HSSFWorkbook workbook, HSSFSheet sheet,String[] titleArray) {
  91. HSSFRow row = sheet.createRow(0);
  92. //设置为居中加粗
  93. HSSFCellStyle style = workbook.createCellStyle();
  94. HSSFFont font = workbook.createFont();
  95. font.setBold(true);
  96. font.setFontName("仿宋");
  97. style.setAlignment(HorizontalAlignment.CENTER);
  98. style.setFont(font);
  99. HSSFCell cell;
  100. for(int i = 0;i<titleArray.length;i++){
  101. cell = row.createCell(i);
  102. cell.setCellValue(titleArray[i]);
  103. cell.setCellStyle(style);
  104. //自适应列宽
  105. sheet.autoSizeColumn((short)i);
  106. }
  107. }
  108. }
  • yml文件中自定义路径配置:
 比如:downloadUrl: /Users/parkin/Downloads/
  • 控制层调用:
  1. /**
  2. * 学校列表导出excel
  3. * @param jsonParam
  4. * @param response
  5. */
  6. @PostMapping(value = "/schoolsExcelExport",produces="application/octet-stream")
  7. @ResponseBody
  8. @PreAuthorize("hasRole(\""+ AuthoritiesConstants.ADMIN +"\")")
  9. public void schoolsExcelExport(@RequestBody String jsonParam, HttpServletResponse response) {
  10. try{
  11. String sheetName = "学校列表";
  12. //excel导出
  13. ExcelExportUtil.outPutExcel(jsonParam,response,sheetName);
  14. }
  15. catch (Exception ex){
  16. throw new BadRequestAlertException(ex.getMessage(),ENTITY_NAME,"param");
  17. }
  18. }
  • postman 测试:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/536825
推荐阅读
相关标签