基于jeecgboot的flowable流程任务excel导出功能

简介: 基于jeecgboot的flowable流程任务excel导出功能

     因为之前没有做这个功能,用传统的jeecgboot的excel导出功能也不好,而且不实用,所以临时做了一个excel导出,不过以后还需要完善,支持查询结果以及更多功能。

    首先建一个ExcelUtils<T>类 ,T为需要输出的对象

    下面就是输出excel函数了,主要下面参数,一个标题,一个头列名称,一个是列名,dataset是list对象数据,filename是文件名,可以随便输入(因为实际暂时也不用),最后一个是日期格式

     public void exportExcel(HttpServletResponse response, String title, String[] headers, String[] columns, Collection<T> dataset, String filename, String datePattern)

package org.jeecg.common.util;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
/**
 * @Description: ExcelUtils<T> excel导出通用方法
 * @Author: nbacheng
 * @Date:   2023-03-01
 * @Version: V1.0
 */
@Slf4j
public class ExcelUtils<T> {
     
   public void exportExcel(HttpServletResponse response, String title, String[] headers, String[] columns, Collection<T> dataset, String filename, String datePattern){
      // 声明一个工作薄
      HSSFWorkbook workbook = new HSSFWorkbook();
      // 生成一个表格
      HSSFSheet sheet = workbook.createSheet(title);
      // 设置表格默认列宽度为15个字节
      sheet.setDefaultColumnWidth((int) 15);
      // 生成一个样式(用于标题)
      HSSFCellStyle style = workbook.createCellStyle();
      // 设置这些样式
      style.setFillForegroundColor(HSSFColor.HSSFColorPredefined.SKY_BLUE.getIndex());
      style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
      style.setBorderBottom(BorderStyle.THIN);
      style.setBorderLeft(BorderStyle.THIN); 
      style.setBorderRight(BorderStyle.THIN);
      style.setBorderTop(BorderStyle.THIN);
      style.setAlignment(HorizontalAlignment.CENTER);
      // 生成一个字体
      HSSFFont font = workbook.createFont();
      font.setColor(HSSFColor.HSSFColorPredefined.VIOLET.getIndex());
      font.setFontHeightInPoints((short) 12);
      font.setBold(true);
      // 把字体应用到当前的样式
      style.setFont(font);
      
      // 生成并设置另一个样式(用于内容)
      HSSFCellStyle style2 = workbook.createCellStyle();
      style2.setFillForegroundColor(HSSFColor.HSSFColorPredefined.LIGHT_YELLOW.getIndex());
      style2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
      style2.setBorderBottom(BorderStyle.THIN);
      style2.setBorderLeft(BorderStyle.THIN);
      style2.setBorderRight(BorderStyle.THIN);
      style2.setBorderTop(BorderStyle.THIN);
      style2.setAlignment(HorizontalAlignment.CENTER);
      style2.setVerticalAlignment(VerticalAlignment.CENTER);
      // 生成另一个字体
      HSSFFont font2 = workbook.createFont();
      font2.setBold(true);
      // 把字体应用到当前的样式
      style2.setFont(font2);
      // 产生表格标题行
      HSSFRow row = sheet.createRow(0);
      for (int i = 0; i < headers.length; i++) {
        HSSFCell cell = row.createCell(i);
        cell.setCellStyle(style);
        HSSFRichTextString text = new HSSFRichTextString(headers[i]);
        cell.setCellValue(text);
      }
      
      // 遍历集合数据,产生数据行
      Iterator<T> it = dataset.iterator();
      int index = 0;
      while (it.hasNext()) {
        index++;
        row = sheet.createRow(index);
        T t = (T) it.next();
        // 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
        //Field[] fields = t.getClass().getDeclaredFields();
        //for (int i = 0; i < fields.length; i++) {
        for (int i = 0; i < columns.length; i++) {
          HSSFCell cell = row.createCell(i);
          cell.setCellStyle(style2);
          //Field field = fields[i];
          //String fieldName = field.getName();
          String fieldName = columns[i];
          String getMethodName = "get"
              + fieldName.substring(0, 1).toUpperCase()
              + fieldName.substring(1);
          try {
            Class<? extends Object> tCls = t.getClass();
            Method getMethod = tCls.getMethod(getMethodName,
                new Class[] {});
            Object value = getMethod.invoke(t, new Object[] {});
            // 判断值的类型后进行强制类型转换
            String textValue = null;
            if (value instanceof Boolean) {
              boolean bValue = (Boolean) value;
              textValue = "男";
              if (!bValue) {
                textValue = "女";
              }
            } else if (value instanceof Date) {
              Date date = (Date) value;
              SimpleDateFormat sdf = new SimpleDateFormat(datePattern);
              textValue = sdf.format(date);
            } else {
              // 其它数据类型都当作字符串简单处理
              if(Objects.nonNull(value)) {
                textValue = value.toString();
              }
              else {
                textValue = "";
              }
              
            }
            // 如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成
            if (textValue != null) {
              Pattern p = Pattern.compile("^//d+(//.//d+)?$");
              Matcher matcher = p.matcher(textValue);
              if (matcher.matches()) {
                // 是数字当作double处理
                cell.setCellValue(Double.parseDouble(textValue));
              } else {
                HSSFRichTextString richString = new HSSFRichTextString(
                    textValue);
                HSSFFont font3 = workbook.createFont();
                //font3.setColor(HSSFColor.BLUE.index);
                richString.applyFont(font3);
                cell.setCellValue(richString);
              }
            }
          } catch (SecurityException e) {
            e.printStackTrace();
          } catch (NoSuchMethodException e) {
            e.printStackTrace();
          } catch (IllegalArgumentException e) {
            e.printStackTrace();
          } catch (IllegalAccessException e) {
            e.printStackTrace();
          } catch (InvocationTargetException e) {
            e.printStackTrace();
          } finally {
            // 清理资源
          }
        }
      }
      try {
        //OutputStream out = new FileOutputStream("/opt/upFiles/"+filename);
        //workbook.write(out);
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition",
                        "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            workbook.write(response.getOutputStream());
        //out.close();
        log.info("导出成功");
      } catch (IOException e) {
        e.printStackTrace();
      }finally{
        try {
          workbook.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
     }
}

调用的例子

/**
     * 导出excel
     *
     * @param request
     * @param HttpServletResponse response, FlowTaskDto flowTaskDto
     */
     @RequestMapping(value = "/myExportXls")
     public void myExportXls(HttpServletResponse response, FlowTaskDto flowTaskDto) {
       
        String[] headers = { "任务编号", "流程名称", "流程类别", "流程版本", "业务主键", "提交时间","流程状态","耗时","当前节点","办理"};
        String[] columns = { "procInsId","procDefName","category","procDefVersion","businessKey","createTime","finishTime","duration","taskName","assigneeName"};
        List<FlowTaskDto> listflowtask = ((Page<FlowTaskDto>)flowTaskService.myProcessNew(1, 10, flowTaskDto).getResult()).getRecords();
        ExcelUtils<FlowTaskDto> eu = new ExcelUtils<FlowTaskDto>();
        eu.exportExcel(response, "标题", headers, columns, listflowtask, "test.xls", "yyyy-MM-dd HH:mm:ss");//目前这个文件名没有什么用,前端传过来会修改掉
    }

前端修改一下地址就可以:

如:    exportXlsUrl: "/flowable/task/myExportXls",

实际效果如下:

 

相关文章
|
2月前
|
关系型数据库 MySQL Shell
不通过navicat工具怎么把查询数据导出到excel表中
不通过navicat工具怎么把查询数据导出到excel表中
32 0
|
6天前
|
SQL C# 数据库
EPPlus库的安装和使用 C# 中 Excel的导入和导出
本文介绍了如何使用EPPlus库在C#中实现Excel的导入和导出功能。首先,通过NuGet包管理器安装EPPlus库,然后提供了将DataGridView数据导出到Excel的步骤和代码示例,包括将DataGridView转换为DataTable和使用EPPlus将DataTable导出为Excel文件。接着,介绍了如何将Excel数据导入到数据库中,包括读取Excel文件、解析数据、执行SQL插入操作。
EPPlus库的安装和使用 C# 中 Excel的导入和导出
|
3天前
|
前端开发 Java easyexcel
SpringBoot操作Excel实现单文件上传、多文件上传、下载、读取内容等功能
SpringBoot操作Excel实现单文件上传、多文件上传、下载、读取内容等功能
13 6
|
15天前
|
存储 Java
java的Excel导出,数组与业务字典匹配并去掉最后一个逗号
java的Excel导出,数组与业务字典匹配并去掉最后一个逗号
34 2
|
2月前
|
前端开发 JavaScript
使用Vue+xlsx+xlsx-style实现导出自定义样式的Excel文件
本文介绍了在Vue项目中使用`xlsx`和`xlsx-style`(或`xlsx-style-vite`)库实现导出具有自定义样式的Excel文件的方法,并提供了详细的示例代码和操作效果截图。
337 1
使用Vue+xlsx+xlsx-style实现导出自定义样式的Excel文件
|
2月前
|
前端开发 Python
使用Python+openpyxl实现导出自定义样式的Excel文件
本文介绍了如何使用Python的openpyxl库导出具有自定义样式的Excel文件,包括设置字体、对齐方式、行列宽高、边框和填充等样式,并提供了完整的示例代码和运行效果截图。
40 1
使用Python+openpyxl实现导出自定义样式的Excel文件
|
2月前
|
SQL 分布式计算 DataWorks
DataWorks产品使用合集之如何直接导出excel文件
DataWorks作为一站式的数据开发与治理平台,提供了从数据采集、清洗、开发、调度、服务化、质量监控到安全管理的全套解决方案,帮助企业构建高效、规范、安全的大数据处理体系。以下是对DataWorks产品使用合集的概述,涵盖数据处理的各个环节。
|
2月前
|
JavaScript 前端开发 easyexcel
基于SpringBoot + EasyExcel + Vue + Blob实现导出Excel文件的前后端完整过程
本文展示了基于SpringBoot + EasyExcel + Vue + Blob实现导出Excel文件的完整过程,包括后端使用EasyExcel生成Excel文件流,前端通过Blob对象接收并触发下载的操作步骤和代码示例。
229 0
基于SpringBoot + EasyExcel + Vue + Blob实现导出Excel文件的前后端完整过程
|
2月前
|
数据管理 数据处理 数据库
分享一个导出数据到 Excel 的解决方案
分享一个导出数据到 Excel 的解决方案
|
2月前
|
SQL
SQL SERVER 查询表结构,导出到Excel 生成代码用
SQL SERVER 查询表结构,导出到Excel 生成代码用
33 0
下一篇
无影云桌面