tnblog
首页
视频
资源
登录

ExportExcelUtil工具类

7639人阅读 2021/12/11 14:27 总访问:139738 评论:0 收藏:1 手机
分类: Java 学习
  1. 声明一点这个工具类不是我原创的,在别人代码里面看到的,借来用哈。。。。。。。
  2. <!--excel处理依赖 开始-->
  3. <dependency>
  4.     <groupId>org.apache.poi</groupId>
  5.     <artifactId>poi</artifactId>
  6.     <version>4.1.0</version>
  7. </dependency>
  8. <dependency>
  9.     <groupId>org.apache.poi</groupId>
  10.     <artifactId>poi-ooxml</artifactId>
  11.     <version>4.1.0</version>
  12.     <exclusions>
  13.         <exclusion>
  14.             <artifactId>poi</artifactId>
  15.             <groupId>org.apache.poi</groupId>
  16.         </exclusion>
  17.         <exclusion>
  18.             <artifactId>xmlbeans</artifactId>
  19.             <groupId>org.apache.xmlbeans</groupId>
  20.         </exclusion>
  21.     </exclusions>
  22. </dependency>
  23. <dependency>
  24.     <groupId>org.apache.poi</groupId>
  25.     <artifactId>poi-ooxml-schemas</artifactId>
  26.     <version>4.1.2</version>
  27. </dependency>
  28. <!--结束-->
  29. 这里是压缩文件处理类
  1. package com.example.oracle.util;
  2. import java.io.*;
  3. import java.util.Enumeration;
  4. import java.util.zip.*;
  5. public class ZipUtils {
  6.     static final int BUFFER = 8192;
  7.     static final String ZIP_SUFFIX = ".zip";
  8.     /**
  9.      * 压缩文件
  10.      *
  11.      * @param srcPath 要压缩的文件或文件夹(如:/usr/local/目录)
  12.      * @param zipPath 输出的zip文件路径(如:/usr/local/abc.zip)
  13.      * @throws IOException
  14.      */
  15.     public static void compress(String srcPath, String zipPath) throws IOException {
  16.         File srcFile = new File(srcPath);
  17.         File zipFile = new File(zipPath);
  18.         if (!srcFile.exists()) {
  19.             throw new FileNotFoundException(srcPath + "不存在!");
  20.         }
  21.         FileOutputStream out = null;
  22.         ZipOutputStream zipOut = null;
  23.         try {
  24.             out = new FileOutputStream(zipFile);
  25.             CheckedOutputStream cos = new CheckedOutputStream(out, new CRC32());
  26.             zipOut = new ZipOutputStream(cos);
  27.             String baseDir = "";
  28.             compress(srcFile, zipOut, baseDir);
  29.         } finally {
  30.             if (null != zipOut) {
  31.                 zipOut.close();
  32.                 out = null;
  33.             }
  34.             if (null != out) {
  35.                 out.close();
  36.             }
  37.         }
  38.     }
  39.     private static void compress(File file, ZipOutputStream zipOut, String baseDir) throws IOException {
  40.         if (file.isDirectory()) {
  41.             compressDirectory(file, zipOut, baseDir);
  42.         } else {
  43.             compressFile(file, zipOut, baseDir);
  44.         }
  45.     }
  46.     /** 压缩一个目录 */
  47.     private static void compressDirectory(File directory, ZipOutputStream zipOut, String baseDir) throws IOException {
  48.         File[] files = directory.listFiles();
  49.         for (int i = 0; i < files.length; i++) {
  50.             compress(files[i], zipOut, baseDir + directory.getName() + "/");
  51.         }
  52.     }
  53.     /** 压缩一个文件 */
  54.     private static void compressFile(File file, ZipOutputStream zipOut, String baseDir) throws IOException {
  55.         if (!file.exists()) {
  56.             return;
  57.         }
  58.         BufferedInputStream bis = null;
  59.         try {
  60.             bis = new BufferedInputStream(new FileInputStream(file));
  61.             ZipEntry entry = new ZipEntry(baseDir + file.getName());
  62.             zipOut.putNextEntry(entry);
  63.             int count;
  64.             byte data[] = new byte[BUFFER];
  65.             while ((count = bis.read(data, 0, BUFFER)) != -1) {
  66.                 zipOut.write(data, 0, count);
  67.             }
  68.         } finally {
  69.             if (null != bis) {
  70.                 bis.close();
  71.             }
  72.         }
  73.     }
  74.     /**
  75.      * 解压文件
  76.      *
  77.      * @param zipFile
  78.      * @param dstPath
  79.      * @throws IOException
  80.      */
  81.     public static void decompress(String zipFile, String dstPath) throws IOException {
  82.         File pathFile = new File(dstPath);
  83.         if (!pathFile.exists()) {
  84.             pathFile.mkdirs();
  85.         }
  86.         ZipFile zip = new ZipFile(zipFile);
  87.         for (Enumeration entries = zip.entries(); entries.hasMoreElements(); ) {
  88.             ZipEntry entry = (ZipEntry) entries.nextElement();
  89.             String zipEntryName = entry.getName();
  90.             InputStream in = null;
  91.             OutputStream out = null;
  92.             try {
  93.                 in = zip.getInputStream(entry);
  94.                 String outPath = (dstPath + "/" + zipEntryName).replaceAll("\\*""/");
  95.                 ;
  96.                 //判断路径是否存在,不存在则创建文件路径
  97.                 File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
  98.                 if (!file.exists()) {
  99.                     file.mkdirs();
  100.                 }
  101.                 //判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
  102.                 if (new File(outPath).isDirectory()) {
  103.                     continue;
  104.                 }
  105.                 out = new FileOutputStream(outPath);
  106.                 byte[] buf1 = new byte[1024];
  107.                 int len;
  108.                 while ((len = in.read(buf1)) > 0) {
  109.                     out.write(buf1, 0, len);
  110.                 }
  111.             } finally {
  112.                 if (null != in) {
  113.                     in.close();
  114.                 }
  115.                 if (null != out) {
  116.                     out.close();
  117.                 }
  118.             }
  119.         }
  120.         zip.close();
  121.     }
  122.     public static void main(String[] args) throws Exception {
  123.         String targetFolderPath = "/Users/test/zipFile/zipFolder";
  124.         String rawZipFilePath = "/Users/test/zipFile/raw.zip";
  125.         String newZipFilePath = "/Users/test/zipFile/new.zip";
  126.         //将Zip文件解压缩到目标目录
  127.         decompress(rawZipFilePath, targetFolderPath);
  128.         //将目标目录的文件压缩成Zip文件
  129.         compress(targetFolderPath, newZipFilePath);
  130.     }
  131. }

主要处理类

  1. package com.example.oracle.util;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.apache.poi.ss.usermodel.BorderStyle;
  4. import org.apache.poi.ss.usermodel.HorizontalAlignment;
  5. import org.apache.poi.ss.util.CellRangeAddress;
  6. import org.apache.poi.xssf.usermodel.*;
  7. import org.apache.tomcat.util.http.fileupload.FileUtils;
  8. import org.springframework.util.ObjectUtils;
  9. import javax.servlet.ServletOutputStream;
  10. import javax.servlet.http.HttpServletResponse;
  11. import java.io.*;
  12. import java.lang.reflect.Field;
  13. import java.lang.reflect.InvocationTargetException;
  14. import java.lang.reflect.Method;
  15. import java.net.URLEncoder;
  16. import java.text.SimpleDateFormat;
  17. import java.util.*;
  18. import java.util.regex.Matcher;
  19. import java.util.regex.Pattern;
  20. @Slf4j
  21. public class ExportExcelUtil<T{
  22.     // 新版Excel文件后缀
  23.     private static final String EXCEL_SUFFIX = ".xlsx";
  24.     /**
  25.      * 导出多Sheet的Excel到HttpServletResponse流中(注:字段定义顺序需跟表头完全一致)
  26.      *
  27.      * (导出Excel格式:表头内容居中,字体略大于正文,颜色深灰色。正文文本类型对齐方式居左,数字类型对齐方式居右。仅有数据的单元格,有边框环绕,实体类的属性顺序即为表头顺序)
  28.      *
  29.      * @param fileName          Excel文件名
  30.      * @param sheetNames        多个Sheet工作表的名称列表(不可重复)
  31.      * @param titleList         多个Sheet的标题名称列表(没有标题,则传null)
  32.      * @param headersList       多个Sheet的表头列表
  33.      * @param dataLists         多个Sheet的数据源
  34.      * @param response          Http响应
  35.      * @param pattern           时间类型数据的格式,默认:yyyy-MM-dd HH:mm:ss
  36.      * @param isExportNullField 空字段是否导出(true:导出,false:不导出)
  37.      *
  38.      */
  39.     public static <T> void exportExcel(String fileName, List<String> sheetNames, List<String> titleList,
  40.                                        List<List<String>> headersList, List<List<T>> dataLists, HttpServletResponse response, String pattern,
  41.                                        boolean isExportNullField) {
  42.         XSSFWorkbook wb = exportAllExcel(sheetNames, titleList, headersList, dataLists, pattern, isExportNullField);
  43.         setResponseHeader(response, replaceSpecialCharacter(fileName));
  44.         ServletOutputStream out = null;
  45.         try {
  46.             out = response.getOutputStream();
  47.             wb.write(out);
  48.         } catch (IOException e) {
  49.             e.printStackTrace();
  50.         } finally {
  51.             try {
  52.                 out.flush();
  53.                 out.close();
  54.                 wb.close();
  55.             } catch (IOException e) {
  56.                 e.printStackTrace();
  57.             }
  58.         }
  59.     }
  60.     /**
  61.      * 导出多Sheet动态列的Excel到HttpServletResponse流中(注:字段定义顺序需跟表头完全一致)
  62.      *
  63.      * @param fileName          Excel文件名
  64.      * @param sheetNames        多个Sheet工作表的名称列表(不可重复)
  65.      * @param titleList         多个Sheet的标题名称列表(没有标题,则传null)
  66.      * @param headersList       多个Sheet的表头列表
  67.      * @param dataLists         多个Sheet的数据源
  68.      * @param response          Http响应
  69.      * @param pattern           时间类型数据的格式,默认:yyyy-MM-dd HH:mm:ss
  70.      * @param isExportNullField 空字段是否导出(true:导出,false:不导出,导出空单元格显示为"--")
  71.      */
  72.     public static void exportDynamicExcel(String fileName, List<String> sheetNames, List<String> titleList,
  73.                                           List<List<String>> headersList, List<List<Map<String, Object>>> dataLists, HttpServletResponse response,
  74.                                           String pattern, boolean isExportNullField) {
  75.         XSSFWorkbook wb = exportDynamicExcelImpl(sheetNames, titleList, headersList, dataLists, pattern,
  76.                 isExportNullField);
  77.         setResponseHeader(response, replaceSpecialCharacter(fileName));
  78.         ServletOutputStream out = null;
  79.         try {
  80.             out = response.getOutputStream();
  81.             wb.write(out);
  82.         } catch (IOException e) {
  83.             e.printStackTrace();
  84.         } finally {
  85.             try {
  86.                 out.flush();
  87.                 out.close();
  88.                 wb.close();
  89.             } catch (IOException e) {
  90.                 e.printStackTrace();
  91.             }
  92.         }
  93.     }
  94.     /**
  95.      * 导出多个Excel并压缩到zip包中
  96.      *
  97.      * @param response          HttpServletResponse
  98.      * @param excelList         多个Excel数据源
  99.      * @param filePath          导出路径(文件夹)
  100.      * @param zipName           压缩包名,如(ABC)
  101.      * @param pattern           Excel中的时间格式
  102.      * @param isExportNullField 空字段是否导出(true:导出,false:不导出,导出空单元格显示为"--")
  103.      */
  104.     public static void exportExcelsToZip(HttpServletResponse response, List<Map<String, Object>> excelList,
  105.                                          String filePath, String zipName, String pattern, boolean isExportNullField) {
  106.         setZipResponseHeader(response, replaceSpecialCharacter(zipName), true".zip");
  107.         long timestamp = System.nanoTime();
  108.         // 本次导出,生成一个excel文件的上级文件夹
  109.         String targetPath = filePath + File.separator + "temp" + File.separator + timestamp + File.separator + zipName;
  110.         for (Map<String, Object> excelMap : excelList) {
  111.             XSSFWorkbook wb = exportDynamicExcelImpl((List<String>) excelMap.get("sheetNames"), null,
  112.                     (List<List<String>>) excelMap.get("headers"),
  113.                     (List<List<Map<String, Object>>>) excelMap.get("dataLists"), pattern, isExportNullField);
  114.             // Excel输出路径示例:/usr/local/tomcat/excels/temp/1649149721911900/报表20210416/xx名称-20210416.xlsx
  115.             String excelPath =
  116.                     targetPath + File.separator + replaceSpecialCharacter(excelMap.get("fileName").toString())
  117.                             + EXCEL_SUFFIX;
  118.             try {
  119.                 File file = new File(excelPath);
  120.                 FileUtils.forceMkdirParent(file);
  121.                 FileOutputStream outputStream = new FileOutputStream(file);
  122.                 wb.write(outputStream);
  123.                 outputStream.close();
  124.                 wb.close();
  125.                 log.info("成功导出Excel:" + file.getName());
  126.             } catch (IOException e) {
  127.                 log.warn("导出Excel时,创建文件出错");
  128.                 e.printStackTrace();
  129.             } finally {
  130.                 try {
  131.                     wb.close();
  132.                 } catch (IOException e) {
  133.                     e.printStackTrace();
  134.                 }
  135.             }
  136.         }
  137.         // 将所有Excel压缩,并写入到response中
  138.         ServletOutputStream out = null;
  139.         FileInputStream fileInputStream = null;
  140.         try {
  141.             // zip输出路径示例:/usr/local/tomcat/excels/temp/1649149721911900/日报20210416.zip
  142.             String outputPath =
  143.                     filePath + File.separator + "temp" + File.separator + timestamp + File.separator + zipName
  144.                             + ZipUtils.ZIP_SUFFIX;
  145.             ZipUtils.compress(targetPath, outputPath);
  146.             File zipFile = new File(outputPath);
  147.             fileInputStream = new FileInputStream(zipFile);
  148.             BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
  149.             out = response.getOutputStream();
  150.             byte[] bytes = new byte[bufferedInputStream.available()];
  151.             // 必须加此行代码,否则下载的Zip包损坏
  152.             int read = bufferedInputStream.read(bytes);
  153.             out.write(bytes);
  154.         } catch (IOException e) {
  155.             e.printStackTrace();
  156.         } finally {
  157.             try {
  158.                 out.flush();
  159.                 out.close();
  160.                 fileInputStream.close();
  161.             } catch (IOException e) {
  162.                 e.printStackTrace();
  163.             }
  164.         }
  165.     }
  166.     /**
  167.      * 设置响应的类型、编码和文件名称
  168.      *
  169.      * @param response
  170.      * @param fileName
  171.      */
  172.     public static void setResponseHeader(HttpServletResponse response, String fileName) {
  173.         try {
  174.             response.reset();
  175.             response.setContentType("application/msexcel");// 设置生成的文件类型
  176.             response.setCharacterEncoding("UTF-8");// 设置文件头编码方式和文件名
  177.             // 在浏览器中测试生效,postman中文件名为response,无法修改
  178.             response.setHeader("Content-disposition""attachment;filename=".concat(String
  179.                     .valueOf(URLEncoder.encode(replaceSpecialCharacter(fileName) + EXCEL_SUFFIX, "UTF-8"))));
  180.             // 此设置,可保证web端可以取到文件名
  181.             response.setHeader("Access-Control-Expose-Headers""Content-Disposition");
  182.             // 网关服务会校验是否有"Download"标识
  183.             response.setHeader("Response-Type""Download");
  184.         } catch (Exception ex) {
  185.             ex.printStackTrace();
  186.         }
  187.     }
  188.     /**
  189.      * 设置Zip下载的响应的类型、编码和文件名称
  190.      *
  191.      * @param response  http响应
  192.      * @param fileName  文件名
  193.      * @param urlEncode 是否URLEncode
  194.      * @param zipSuffix zip后缀名(默认为.zip)
  195.      */
  196.     public static void setZipResponseHeader(HttpServletResponse response, String fileName, boolean urlEncode,
  197.                                             String zipSuffix) {
  198.         try {
  199.             if (zipSuffix == null) {
  200.                 zipSuffix = ".zip";
  201.             }
  202.             String downloadName = urlEncode == true ?
  203.                     String.valueOf(URLEncoder.encode(replaceSpecialCharacter(fileName) + zipSuffix, "UTF-8")) :
  204.                     String.valueOf(replaceSpecialCharacter(fileName) + zipSuffix);
  205.             response.reset();
  206.             // 设置生成的文件类型
  207.             response.setContentType("application/x-zip-compressed");
  208.             //response.setContentType("application/octet-stream");
  209.             // 设置文件头编码方式和文件名
  210.             response.setCharacterEncoding("UTF-8");
  211.             response.setHeader("Content-Disposition""attachment;filename=".concat(downloadName));
  212.             response.setHeader("Access-Control-Expose-Headers""Content-Disposition");
  213.             // 网关服务会校验是否有"Download"标识
  214.             response.setHeader("Response-Type""Download");
  215.         } catch (Exception ex) {
  216.             ex.printStackTrace();
  217.         }
  218.     }
  219.     /**
  220.      * 设置响应的类型、编码和文件名称
  221.      *
  222.      * @param response
  223.      * @param fileName
  224.      */
  225.     public static void setResponseHeader(HttpServletResponse response, String fileName, boolean urlEncode) {
  226.         try {
  227.             String downloadName = urlEncode == true ?
  228.                     String.valueOf(URLEncoder.encode(replaceSpecialCharacter(fileName) + EXCEL_SUFFIX, "UTF-8")) :
  229.                     String.valueOf(replaceSpecialCharacter(fileName) + EXCEL_SUFFIX);
  230.             response.reset();
  231.             response.setContentType("application/msexcel");// 设置生成的文件类型
  232.             response.setCharacterEncoding("UTF-8");// 设置文件头编码方式和文件名
  233.             // 在浏览器中测试生效,postman中文件名为response,无法修改
  234.             response.setHeader("Content-Disposition""attachment;filename=".concat(downloadName));
  235.             response.setHeader("Access-Control-Expose-Headers""Content-Disposition");
  236.             // 网关服务会校验是否有"Download"标识
  237.             response.setHeader("Response-Type""Download");
  238.         } catch (Exception ex) {
  239.             ex.printStackTrace();
  240.         }
  241.     }
  242.     /**
  243.      * 多Sheet导出实现
  244.      *
  245.      * @param sheetNames        Sheet页名称列表
  246.      * @param titleList         标题列表
  247.      * @param headersList       表头列表
  248.      * @param dataLists         sheet数据源列表
  249.      * @param pattern           时间格式
  250.      * @param isExportNullField 是否导出空字段
  251.      * @return
  252.      */
  253.     private static <T> XSSFWorkbook exportAllExcel(List<String> sheetNames, List<String> titleList,
  254.                                                    List<List<String>> headersList, List<List<T>> dataLists, String pattern, boolean isExportNullField) {
  255.         // 创建一个工作薄
  256.         XSSFWorkbook workbook = new XSSFWorkbook();
  257.         for (int i = 0; i < dataLists.size(); i++) {
  258.             // 创建一个工作表
  259.             XSSFSheet sheet = workbook.createSheet(replaceSpecialCharacter(sheetNames.get(i)));
  260.             // 设置单元格列宽度为16个字节
  261.             sheet.setDefaultColumnWidth((short16);
  262.             // 创建表头样式
  263.             XSSFCellStyle headersStyle = workbook.createCellStyle();
  264.             headersStyle.setBorderTop(BorderStyle.THIN);
  265.             headersStyle.setBorderBottom(BorderStyle.THIN);
  266.             headersStyle.setBorderLeft(BorderStyle.THIN);
  267.             headersStyle.setBorderRight(BorderStyle.THIN);
  268.             // 表头内容对齐方式:居中
  269.             headersStyle.setAlignment(HorizontalAlignment.CENTER);
  270.             XSSFFont headersFont = workbook.createFont();
  271.             // 设置字体格式
  272.             headersFont.setColor(new XSSFColor(java.awt.Color.DARK_GRAY));
  273.             headersFont.setFontHeightInPoints((short14);
  274.             // 表头样式应用生效
  275.             headersStyle.setFont(headersFont);
  276.             XSSFCellStyle dataSetStyle = workbook.createCellStyle();
  277.             // 正文单元格边框样式
  278.             dataSetStyle.setBorderBottom(BorderStyle.THIN);
  279.             dataSetStyle.setBorderRight(BorderStyle.THIN);
  280.             dataSetStyle.setBorderLeft(BorderStyle.THIN);
  281.             // 数据内容对齐方式:居左
  282.             // dataSetStyle.setAlignment(HorizontalAlignment.CENTER_SELECTION);
  283.             XSSFFont dataSetFont = workbook.createFont();
  284.             // 正文字体颜色
  285.             dataSetFont.setColor(new XSSFColor(java.awt.Color.BLACK));
  286.             // 为正文设置样式
  287.             dataSetStyle.setFont(dataSetFont);
  288.             // 获取当前Sheet页的表头
  289.             List<String> headers = headersList.get(i);
  290.             int index = 0;
  291.             if (!ObjectUtils.isEmpty(titleList)) {
  292.                 String titleName = titleList.get(i);
  293.                 if (!ObjectUtils.isEmpty(titleName)) {
  294.                     XSSFCellStyle titleStyle = workbook.createCellStyle();
  295.                     // 将首行合并居中作为标题栏
  296.                     sheet.addMergedRegion(new CellRangeAddress(000, headers.size() - 1));
  297.                     XSSFFont titleFont = workbook.createFont();
  298.                     // 设置标题字体大小
  299.                     titleFont.setFontHeightInPoints((short20);
  300.                     // 设置标题字体样式
  301.                     titleStyle.setFont(titleFont);
  302.                     // 创建标题行并设置样式
  303.                     XSSFRow titleRow = sheet.createRow(0);
  304.                     XSSFCell titleCell = titleRow.createCell(0);
  305.                     titleCell.setCellStyle(titleStyle);
  306.                     titleCell.setCellValue(titleName);
  307.                     index = 1;
  308.                 }
  309.             }
  310.             // 创建表头并设置样式
  311.             XSSFRow row = sheet.createRow(index);
  312.             for (short j = 0; j < headers.size(); j++) {
  313.                 XSSFCell cell = row.createCell(j);
  314.                 cell.setCellStyle(headersStyle);
  315.                 XSSFRichTextString text = new XSSFRichTextString(headers.get(j));
  316.                 cell.setCellValue(text);
  317.             }
  318.             // 导出正文数据,并设置其样式
  319.             Iterator<?> it = dataLists.get(i).iterator();
  320.             while (it.hasNext()) {
  321.                 index++;
  322.                 row = sheet.createRow(index);
  323.                 Object entity = it.next();
  324.                 // 利用反射,根据实体类属性的先后顺序,动态调用其getXxx()方法,得到属性值
  325.                 Field[] fields = entity.getClass().getDeclaredFields();
  326.                 for (short k = 0; k < fields.length; k++) {
  327.                     XSSFCell cell = row.createCell(k);
  328.                     Field field = fields[k];
  329.                     String fieldName = field.getName();
  330.                     String getMethodName = "get" + fieldName.substring(01).toUpperCase() + fieldName.substring(1);
  331.                     try {
  332.                         @SuppressWarnings("rawtypes")
  333.                         Class entityClass = entity.getClass();
  334.                         @SuppressWarnings("unchecked")
  335.                         Method getMethod = entityClass.getMethod(getMethodName, new Class[] {});
  336.                         Object value = getMethod.invoke(entity, new Object[] {});
  337.                         String textValue = null;
  338.                         // 如果是时间类型,格式化
  339.                         if (value instanceof Date) {
  340.                             Date date = (Date) value;
  341.                             pattern = pattern == null || pattern.equals("") ? "yyyy-MM-dd HH:mm:ss" : pattern;
  342.                             SimpleDateFormat sdf = new SimpleDateFormat(pattern);
  343.                             textValue = sdf.format(date);
  344.                         } else {
  345.                             // 若字段为空且允许导出空字段,则将null导出为""
  346.                             textValue = value == null && isExportNullField ? "" : value.toString();
  347.                         }
  348.                         if (!textValue.equals("")) {
  349.                             // 有数据时边框环绕
  350.                             cell.setCellStyle(dataSetStyle);
  351.                             // 正则判断是否为数值
  352.                             Pattern p = Pattern.compile("^\\d+(\\.\\d+)?$");
  353.                             Matcher matcher = p.matcher(textValue);
  354.                             if (matcher.matches()) {
  355.                                 // 是数字当作double处理,整型也不会补充小数点
  356.                                 cell.setCellValue(Double.parseDouble(textValue));
  357.                             } else {
  358.                                 // 不是数字类型作为文本输出
  359.                                 cell.setCellValue(textValue);
  360.                             }
  361.                         }
  362.                     } catch (SecurityException | NoSuchMethodException | IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
  363.                         e.printStackTrace();
  364.                     }
  365.                 }
  366.             }
  367.         }
  368.         return workbook;
  369.     }
  370.     /**
  371.      * 多Sheet导出动态列到Excel实现(数据源为Map)
  372.      *
  373.      * @param sheetNames        Sheet页名称列表
  374.      * @param titleList         标题列表
  375.      * @param headersList       表头列表
  376.      * @param dataLists         sheet数据源列表
  377.      * @param pattern           时间格式
  378.      * @param isExportNullField 是否导出空字段
  379.      * @return XSSFWorkbook workbook
  380.      */
  381.     private static XSSFWorkbook exportDynamicExcelImpl(List<String> sheetNames, List<String> titleList,
  382.                                                        List<List<String>> headersList, List<List<Map<String, Object>>> dataLists, String pattern,
  383.                                                        boolean isExportNullField) {
  384.         // 创建一个工作薄
  385.         XSSFWorkbook workbook = new XSSFWorkbook();
  386.         for (int i = 0; i < dataLists.size(); i++) {
  387.             // 创建一个工作表
  388.             XSSFSheet sheet = workbook.createSheet(replaceSpecialCharacter(sheetNames.get(i)));
  389.             // 设置单元格列宽度为16个字节
  390.             sheet.setDefaultColumnWidth((short16);
  391.             // 创建表头样式
  392.             XSSFCellStyle headersStyle = workbook.createCellStyle();
  393.             headersStyle.setBorderTop(BorderStyle.THIN);
  394.             headersStyle.setBorderBottom(BorderStyle.THIN);
  395.             headersStyle.setBorderLeft(BorderStyle.THIN);
  396.             headersStyle.setBorderRight(BorderStyle.THIN);
  397.             // 表头内容对齐方式:居中
  398.             headersStyle.setAlignment(HorizontalAlignment.CENTER);
  399.             XSSFFont headersFont = workbook.createFont();
  400.             // 设置字体格式
  401.             headersFont.setColor(new XSSFColor(java.awt.Color.DARK_GRAY, new DefaultIndexedColorMap()));
  402.             headersFont.setFontHeightInPoints((short12);
  403.             // 表头样式应用生效
  404.             headersStyle.setFont(headersFont);
  405.             // 设置单元格内内容换行
  406.             headersStyle.setWrapText(true);
  407.             XSSFCellStyle dataSetStyle = workbook.createCellStyle();
  408.             // 正文单元格边框样式
  409.             dataSetStyle.setBorderBottom(BorderStyle.THIN);
  410.             dataSetStyle.setBorderRight(BorderStyle.THIN);
  411.             dataSetStyle.setBorderLeft(BorderStyle.THIN);
  412.             // 数据内容对齐方式:居左
  413.             // dataSetStyle.setAlignment(HorizontalAlignment.CENTER_SELECTION);
  414.             XSSFFont dataSetFont = workbook.createFont();
  415.             // 正文字体颜色
  416.             dataSetFont.setColor(new XSSFColor(java.awt.Color.BLACK, new DefaultIndexedColorMap()));
  417.             // 为正文设置样式
  418.             dataSetStyle.setFont(dataSetFont);
  419.             // 获取当前Sheet页的表头
  420.             List<String> headers = headersList.get(i);
  421.             int index = 0;
  422.             if (!ObjectUtils.isEmpty(titleList)) {
  423.                 String titleName = titleList.get(i);
  424.                 if (!ObjectUtils.isEmpty(titleName)) {
  425.                     XSSFCellStyle titleStyle = workbook.createCellStyle();
  426.                     // 将首行合并居中作为标题栏
  427.                     sheet.addMergedRegion(new CellRangeAddress(000, headers.size() - 1));
  428.                     XSSFFont titleFont = workbook.createFont();
  429.                     // 设置标题字体大小
  430.                     titleFont.setFontHeightInPoints((short20);
  431.                     // 设置标题字体样式
  432.                     titleStyle.setFont(titleFont);
  433.                     // 创建标题行并设置样式
  434.                     XSSFRow titleRow = sheet.createRow(0);
  435.                     XSSFCell titleCell = titleRow.createCell(0);
  436.                     titleCell.setCellStyle(titleStyle);
  437.                     titleCell.setCellValue(titleName);
  438.                     index = 1;
  439.                 }
  440.             }
  441.             // 创建表头并设置样式
  442.             XSSFRow row = sheet.createRow(index);
  443.             for (short j = 0; j < headers.size(); j++) {
  444.                 XSSFCell cell = row.createCell(j);
  445.                 cell.setCellStyle(headersStyle);
  446.                 XSSFRichTextString text = new XSSFRichTextString(headers.get(j));
  447.                 cell.setCellValue(text);
  448.             }
  449.             // 导出正文数据,并设置其样式
  450.             ListIterator<Map<String, Object>> it = dataLists.get(i).listIterator();
  451.             while (it.hasNext()) {
  452.                 try {
  453.                     index++;
  454.                     row = sheet.createRow(index);
  455.                     Map<String, Object> map = it.next();
  456.                     headers = new ArrayList<String>(map.keySet());
  457.                     List<Object> values = new ArrayList<Object>(map.values());
  458.                     for (int k = 0; k < map.keySet().size(); k++) {
  459.                         try {
  460.                             XSSFCell cell = row.createCell(k);
  461.                             cell.setCellStyle(dataSetStyle);
  462.                             String textValue = null;
  463.                             Object value = values.get(k);
  464.                             // 如果是时间类型,格式化
  465.                             if (value instanceof Date) {
  466.                                 Date date = (Date) value;
  467.                                 pattern = pattern == null || pattern.equals("") ? "yyyy-MM-dd HH:mm:ss" : pattern;
  468.                                 SimpleDateFormat sdf = new SimpleDateFormat(pattern);
  469.                                 textValue = sdf.format(date);
  470.                             } else {
  471.                                 // 若字段为空且用户允许导出空字段,则将null导出为"--"
  472.                                 textValue = value == null && isExportNullField ? "--" : value.toString();
  473.                             }
  474.                             if (!textValue.equals("")) {
  475.                                 // 有数据时边框环绕
  476.                                 //cell.setCellStyle(dataSetStyle);
  477.                                 // 正则判断是否为数值
  478.                                 Pattern p = Pattern.compile("^\\d+(\\.\\d+)?$");
  479.                                 Matcher matcher = p.matcher(textValue);
  480.                                 if (matcher.matches()) {
  481.                                     // 是数字当作double处理,整型也不会补充小数点
  482.                                     cell.setCellValue(Double.parseDouble(textValue));
  483.                                 } else {
  484.                                     // 不是数字类型作为文本输出
  485.                                     cell.setCellValue(textValue);
  486.                                 }
  487.                             }
  488.                         } catch (Exception e) {
  489.                             e.printStackTrace();
  490.                         }
  491.                     }
  492.                 } catch (Exception e) {
  493.                     e.printStackTrace();
  494.                 }
  495.             }
  496.         }
  497.         return workbook;
  498.     }
  499.     /**
  500.      * 用下划线替换所有特殊字符
  501.      *
  502.      * @param targetStr 目标字符串
  503.      */
  504.     public static String replaceSpecialCharacter(String targetStr) {
  505.         if (null != targetStr && !"".equals(targetStr.trim())) {
  506.             String regEx = "[\\\\|:/\"<>?*\\[\\] ]";
  507.             Pattern p = Pattern.compile(regEx);
  508.             Matcher m = p.matcher(targetStr);
  509.             return m.replaceAll("_");
  510.         }
  511.         return null;
  512.     }
  513. }
  1. 测试
  2. @RequestMapping(value = "/exportExcel", method = RequestMethod.GET)
  3. @ResponseBody
  4. public void exportExcelTest(HttpServletResponse response) {
  5.     // 调用你的服务,获取数据源
  6.     List<List<MroOriginalInfo>> dataLists = new ArrayList<>();
  7.     List<MroOriginalInfo> mroOriginalInfoList= mroOriginalInfoService.getList();
  8.     dataLists.add(mroOriginalInfoList);
  9.     if (dataLists != null && dataLists.size() > 0) {
  10.         try {
  11.             // Sheet页名称列表
  12.             List<String> sheetNames = new ArrayList<String>();
  13.             sheetNames.add("基站id");//这里必须写一个名称,不然要报错
  14.             // 一个Sheet页表头名称列表
  15.             List<String> headers = new ArrayList<String>(
  16.                     Arrays.asList("任务编号""任务发起地市""时间""基站id""传输标记"));
  17.             // 模拟多个Sheet页表头
  18.             List<List<String>> headersList = Arrays.asList(headers, headers, headers);
  19.             // 多个Sheet页标题列表(若)
  20.             List<String> titleList = new ArrayList<String>();
  21.             ExportExcelUtil
  22.                     .exportExcel("Excel文件名", sheetNames, titleList, headersList, dataLists, response, nulltrue);
  23.         } catch (Exception e) {
  24.             log.error("导出基站数据出错", e);
  25.         }
  26.     }
  27. }


评价

net core使用jwt 三: 使用过滤器实现通用token验证Token验证工具

net core使用jwt二 : 验证前台传递的tokenhttp://www.tnblog.net/aojiancc2/article/details/2845过滤器实现通用token验证...

JDBC抽取成工具

没抽取前的样式 抽取步骤一、编写配置文件,并创建二、创建JDBC工具类1、所需步骤1.1、步骤1、21.2、步骤3有一个propert...

Dapper 工具

安装Dapper Install-Package Dapper -Version 2.0.123 DapperHelper类 public class DapperHelper { private ...

常用的很厉害的工具

图片压缩相对图片无损放大来说是小kiss。下面是非常非常帅气的图片无损放大http://bigjpg.com/图片压缩https://www.upyun.c...

一些有用的资源分享(工具+电子书)

工具类图片相关工具TinyPNG:https://tinypng.com/ 免费的在线图片压缩工具,压缩率高,无损画质,直接拖拽使用,很方便。p...

开发自己的代码生成工具

在一个项目中其实有很多代码都是重复的,几乎每个基础模块的代码都有增删改查的功能,而这些功能都是大同小异,如果这些功...

windoes 强力下载工具Internet Download Manager

大家好,我是刘小贱,今天呢我给大家推荐一款Windows系统上的下载神器:Internet Download Manager ,这款软件通过在浏览器上...

oralce plsql打开执行sql的工具

如果不小心关闭了,要打开执行sql的工具栏如下箭头的地方右键即可

maven与工具(eclipse)的集成

1、下载maven插件apache-maven-3.6.22、下载jdk1.8并安装配置环境变量3、解压插件并配置环境变量(JAVA_HOME配置jdk根目录、...

editor.md自定义工具

editor.md自定义工具栏很简单,下载后例子自带了,怎么配置和百度编辑器的很类似也是返回一个数组配置即可你可能不知道这些...

nodejs编写工具--WebStorm

前言:hello老铁们我们又见面了,前面给大家简单的说了ABP框架 今天给大家分享的是Node.js的编写工具WebStom因为ABP要用到...

Linux 文本处理工具 sed

文本处理工具 sed[TOC] sed 介绍 sed 是一种非交互式的流编辑器,它会集于原文件进行文本处理,但并不会修改原有的文...

Jemeter压力测试工具

Jemeter 压力测试工具[TOC] JMeter 简介 阿帕奇JMeter的?应用程序是开源软件,100%纯Java应用而设计的负载测试功能...

如何破解傲软GIF录制工具

前言:hello 小伙伴们 大家好 咋们又见面了 我是小付今天要和大家分享的是破解版的傲软GIF录制工具,有些时候我们在编写博客...

开发winform xml文件生成C类文件工具

最近项目中用到了博通PLC采集图像数据保存的业务,需要解析软件返回的xml文件,然后保存到数据库。为了方便就自己整了一个x...
写代码里面打羽毛球最好的
排名
23
文章
19
粉丝
5
评论
1
Android studio打包脱坑1
剑轩 : 现在在做android了哇?
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术
相思只在:丁香枝上,豆蔻梢头。