poi打印

官网:http://deepoove.com/poi-tl

打印

   package com.guodi.bpm.form.service.impl;

import cn.hutool.core.map.CaseInsensitiveMap;
import cn.hutool.core.map.MapUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.converters.date.DateNumberConverter;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.deepoove.poi.util.RegexUtils;
import com.guodi.bpm.form.service.IPrintService;
import com.guodi.bpm.form.service.factory.PrintFormatFactory;
import com.guodi.bpm.form.util.minio.MinioTemplates;
import com.guodi.bpm.model.constant.BpmConstant;
import com.guodi.bpm.model.enums.BoxFormatEnum;
import com.guodi.bpm.model.enums.FormatEnum;
import com.guodi.bpm.model.enums.PhotoFormatEnum;
import com.guodi.bpm.model.vo.request.*;
import com.guodi.bpm.model.vo.response.CustDelegateInfoResponse;
import com.guodi.bpm.form.model.vo.response.DelegateMyExcelResponse;
import com.guodi.bpm.form.model.vo.response.DelegateToMeExcelResponse;
import com.guodi.bpm.form.util.excel.ExcelUtil;
import com.guodi.bpm.form.util.excel.TimestampNumberConverter;
import com.guodi.bpm.tool.util.formatUtil.FormatUtil;
import org.apache.commons.codec.Charsets;
import org.apache.commons.math3.exception.NullArgumentException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lwh
 * @description: 打印/导出
 * @date: 2023/6/28 19:05
 */
@Service
public class PrintServiceImpl implements IPrintService {

    @Resource
    private MinioTemplates minioTemplates;

    @Override
    public String formPrint(FormPrintRequest request, Map<String, Object> paramMap, String templatePath) {
        try {
            Map<String, Object> datasMap = new CaseInsensitiveMap(paramMap);
            //由于路径带了存储桶名称,因为需要去除存储桶
            String bucketName = minioTemplates.getBucketName();
            String objectName = templatePath;
            if (objectName.indexOf(bucketName) != -1) {
                objectName = objectName.substring(objectName.indexOf(bucketName) + bucketName.length());
            }
            InputStream inputStream = minioTemplates.getObject(objectName);
            XWPFDocument document = new XWPFDocument(inputStream);

            //获取表格内容
            XWPFWordExtractor xwpfWordExtractor = new XWPFWordExtractor(document);
            String text = xwpfWordExtractor.getText();

            //格式化处理特殊格式(时间、二维码、图片)
            this.customFormat(datasMap, text);

            //动态行表格渲染
            LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();

            ConfigureBuilder builder = Configure.builder();
            //修改默认标签
            builder.buildGramer("${", "}");
            //标签正则,去除除了标签前后缀外的任意字符
            builder.buildGrammerRegex(RegexUtils.createGeneral("${", "}"));

            Configure config = builder.build();

            //动态表格日期格式化
            String[] split = text.split("\\$\\{|\\}|\\[|\\]");
            for (String s : split) {
                Object tbDate = datasMap.get(s);
                //获取子表的数据,格式化数据
                if (tbDate instanceof List) {
                    config = builder.bind(s, policy).build();
                    List<Map<String, Object>> tbData = (List<Map<String, Object>>) datasMap.get(s);
                    for (Map<String, Object> tableDatum : tbData) {
                        this.subTableFormat(tableDatum, text);
                    }
                }
            }
            XWPFTemplate template = XWPFTemplate.compile(document, config);
            template.render(datasMap);

            //把XWPFTemplate对象转为输入流
            InputStream toInputStream = this.convertToInputStream(template);

            //获取instId、当前时间作为minio上传的路径
            String instId = request.getInstId();
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
            String nowTime = dateFormat.format(calendar.getTime());

            //关闭资源
            document.close();

            //存储对象文件到minio服务器
            String docxUrl = minioTemplates.putObject(BpmConstant.FORM_PRINT_URL + instId + "/" + request.getFileName() + nowTime + ".docx", toInputStream);
            System.out.println("文件地址================== " + docxUrl);
            return docxUrl;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("打印错误"+e.getMessage());
        }
    }

    public InputStream convertToInputStream(XWPFTemplate template) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        template.write(outputStream);
        return new ByteArrayInputStream(outputStream.toByteArray());
    }

    public void customFormat(Map<String, Object> entry, String text) {
        //截取每个值,正则表达式分割${}
        String[] split = text.split("\\$\\{|\\}");
        getSplitValue(entry, split);
    }


    public void subTableFormat(Map<String, Object> entry, String text) {
        //截取每个值,正则表达式分割[]的值
        String[] split = text.split("\\[|\\]");
        getSplitValue(entry, split);
    }

    private void getSplitValue(Map<String, Object> entry, String[] split) {
        for (String s : split) {
            String[] strings = s.split("\\|");
            //处理特殊类型打印
            for (String string : strings) {
                //获取字段
                String oneValue = strings[0];
                //获取字段对应的值
                Object value = entry.get(oneValue);
                if (BoxFormatEnum.CHK.name().equals(string)) {
                    //处理复选框CHK
                    String format = strings[1];
                    //调用打印数据格式化工厂
                    handleBoxValue(entry, s, strings, format, value);
                } else if (BoxFormatEnum.CHKG.name().equals(string)) {
                    //处理复选框CHK json
                    String format = strings[1];
                    if (BoxFormatEnum.CHKG.name().equals(format)) {
                        Object formatValue = PrintFormatFactory.formatValue(value, format, null);
                        entry.put(s, formatValue == null ? "" : formatValue);
                    }
                } else if (BoxFormatEnum.RDO.name().equals(string)) {
                    //处理单选框RDO
                    String format = strings[1];
                    if (BoxFormatEnum.RDO.name().equals(format)) {
                        handleBoxValue(entry, s, strings, format, value);
                    }
                } else if (BoxFormatEnum.RDOG.name().equals(string)) {
                    //处理单选框RDO json
                    String format = strings[1];
                    if (BoxFormatEnum.RDOG.name().equals(format)) {
                        //调用打印数据格式化工厂
                        Object formatValue = PrintFormatFactory.formatValue(value, format, null);
                        entry.put(s, formatValue == null ? "" : formatValue);
                    }
                } else if (PhotoFormatEnum.IMG.name().equals(string)) {
                    //处理单张图片IMG
                    //调用打印数据格式化工厂
                    imageFormat(entry, s);
                } else if (PhotoFormatEnum.IMGLIST.name().equals(string)) {
                    //处理多张图片IMGLIST
                    imageFormat(entry, s);
                } else if (PhotoFormatEnum.IMG_STR.name().equals(string)) {
                    //处理二维码、条形码IMG_STR
                    String imageSubstring = s.substring(1);
                    String[] splits = imageSubstring.split("\\|");
                    String vKey = splits[0];
                    String values = (String) entry.get(vKey);
                    //打印数据格式化工厂
                    Object formatValue = PrintFormatFactory.formatValue(values, string, null);
                    entry.put(imageSubstring, formatValue == null ? "" : formatValue);
                }
            }
            //判断是否有这个格式转换类型
            FormatUtil timeFormat = this.getTimeFormat(s);
            if (timeFormat != null) {
                //时间打印格式化数据
                String oneValue = strings[0];
                String format = strings[1];
                Object value = entry.get(oneValue);
                if (value != null) {
                    //打印数据格式化工厂
                    Object formatValue = PrintFormatFactory.formatValue(value, format, null);
                    entry.put(s, StringUtils.isEmpty(formatValue.toString()) ? "" : formatValue);
                }
            }
        }
    }

    //处理单选框,复选框,value值(默认值)
    private void handleBoxValue(Map<String, Object> entry, String s, String[] strings, String format, Object value) {
        if (BoxFormatEnum.CHK.name().equals(format) || BoxFormatEnum.RDO.name().equals(format)) {
            if (strings.length > 2) {
                Object formatValue = PrintFormatFactory.formatValue(value, format, strings[2]);
                entry.put(s, formatValue == null ? "" : formatValue);
            } else {
                Object formatValue = PrintFormatFactory.formatValue(value, format, null);
                entry.put(s, formatValue == null ? "" : formatValue);
            }
        }
    }

    //处理单张图片,多张图片,value值(size)
    private void imageFormat(Map<String, Object> entry, String s) {
        String imageSubstring = s.substring(1);
        String[] splits = imageSubstring.split("\\|");
        String vKey = splits[0];
        String format = splits[1];
        if (format.equals(PhotoFormatEnum.IMG.name()) || format.equals(PhotoFormatEnum.IMGLIST.name())) {
            String value = (String) entry.get(vKey);
            if (splits.length > 2 ) {
                Object formatValue = PrintFormatFactory.formatValue(value, format, splits[2]);
                entry.put(imageSubstring, formatValue == null ? "" : formatValue);
            } else {
                //打印数据格式化工厂
                Object formatValue = PrintFormatFactory.formatValue(value, format, null);
                entry.put(imageSubstring,formatValue == null? "": formatValue);
            }
        }

    }

    /**
     * 判断是否存在对应时间数字类型枚举
     *
     * @param stringTime 字符串
     * @return
     */
    public FormatUtil getTimeFormat(String stringTime) {
        FormatEnum[] cnEnums = FormatEnum.values();
        for (FormatEnum value : cnEnums) {
            if (stringTime.indexOf(String.valueOf(value)) != -1) {
                return new FormatUtil();
            }
        }
        return null;
    }


    /**
     * @param customField  表头数据
     * @param outputStream 输出流
     * @param templatePath 模板路径
     * @param extension    模板类型
     * @param dataList     数据
     * @description: 箱列表导出
     * @author lwh
     * @date: 2023/8/7 9:36
     */
    @Override
    public void export(LinkedHashMap<String, String> customField, OutputStream outputStream, List<Map<String, Object>> dataList, String templatePath, String extension,Map<String,String> vars) {
        try {
            //无模板
            if (Objects.isNull(templatePath)) {
                if (MapUtil.isEmpty(customField)) {
                    throw new RuntimeException("无模板打印情況下,自定义字段[customField]不能为空");
                }
                Set<String> fieldKeys = customField.keySet();
                //构建表头
                List<List<String>> heads = new ArrayList<>();
                for (String fieldKey : fieldKeys) {
                    String fieldName = customField.get(fieldKey);
                    //是否为子表导出,格式(姓名|xm)
                    if (vars.containsValue("subtleExport") && dataList.size() == 0){
                        StringBuffer sb = new StringBuffer();
                        sb.append(fieldName + ("|")+fieldKey );
                        heads.add(Collections.singletonList(sb.toString()));
                    }else {
                        heads.add(Collections.singletonList(fieldName));
                    }
                    if (Objects.isNull(fieldKey) || Objects.isNull(fieldName)) {
                        throw new RuntimeException("自定义字段信息不能为空");
                    }
                }
                List<List<Object>> datas = null;
                //时间转类型
                if (Objects.nonNull(dataList)) {
                    dataList.forEach(d -> {
                        d.forEach((key, value) -> {
                            if (d.get(key) instanceof Date) {
                                String time = FormatUtil.toUpper(d.get(key).toString(), null);
                                d.put(key, time);
                            }
                        });
                    });
                    //构建表数据
                    datas = dataList
                            .stream()
                            .map(dataMap -> fieldKeys.stream().map(k -> dataMap.get(k)).collect(Collectors.toList()))
                            .collect(Collectors.toList());
                }
                EasyExcel.write(outputStream)
                        .head(heads)
                        .registerWriteHandler(new SimpleColumnWidthStyleStrategy(25))
                        .registerConverter(new TimestampNumberConverter())
                        .registerConverter(new DateNumberConverter())
                        .autoCloseStream(false)
                        .sheet("数据")
                        .doWrite(datas);
            } else {
                //有模板
                if (templatePath == null) {
                    throw new RuntimeException("打印模板不存在");
                }
                if (!"xlsx".equals(extension)) {
                    throw new RuntimeException("只支持xlsx模板导出");
                }
                String bucketName = minioTemplates.getBucketName();
                String objectName = templatePath.substring(bucketName.length() + 2);
                InputStream inputStream = minioTemplates.getObject(objectName);

                EasyExcel.write(outputStream)
                        .withTemplate(inputStream)
                        .registerConverter(new TimestampNumberConverter())
                        .registerConverter(new DateNumberConverter())
                        .autoCloseStream(false)
                        .sheet()
                        .doFill(dataList);
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
            throw new RuntimeException("箱列表导出失败!" + e.getMessage());
        }
    }

    /**
     * @description: 委托列表导出
     * @author lwh
     * @date: 2023/8/7 14:27
     */
    @Override
    public void delegateExport(DelegatetExportRequest request, HttpServletResponse response, List<CustDelegateInfoResponse> datas) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding(Charsets.UTF_8.name());
            String fileName = URLEncoder.encode("导出数据", Charsets.UTF_8.name());
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            if ("my".equals(request.getCategory())) {
                ExcelUtil.export(response.getOutputStream(), "我的委托列表", "数据表",
                        datas.stream().map(info -> {
                            DelegateMyExcelResponse excelResponse = new DelegateMyExcelResponse();
                            BeanUtils.copyProperties(info, excelResponse);
                            //状态(0-未生效,1-已生效,2-已失效)
                            if ("0".equals(info.getStatus())) {
                                excelResponse.setStatusName("未生效");
                            } else if ("1".equals(info.getStatus())) {
                                excelResponse.setStatusName("已生效");
                            } else {
                                excelResponse.setStatusName("已失效");
                            }
                            return excelResponse;
                        })
                                .collect(Collectors.toList()),
                        DelegateMyExcelResponse.class);
            } else {
                ExcelUtil.export(response.getOutputStream(), "委托给我列表", "数据表",
                        datas.stream().map(info -> {
                            DelegateToMeExcelResponse excelToMeResponse = new DelegateToMeExcelResponse();
                            BeanUtils.copyProperties(info, excelToMeResponse);
                            //状态(0-未生效,1-已生效,2-已失效)
                            if ("0".equals(info.getStatus())) {
                                excelToMeResponse.setStatusName("未生效");
                            } else if ("1".equals(info.getStatus())) {
                                excelToMeResponse.setStatusName("已生效");
                            } else {
                                excelToMeResponse.setStatusName("已失效");
                            }
                            return excelToMeResponse;
                        })
                                .collect(Collectors.toList()),
                        DelegateToMeExcelResponse.class);
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("委托导出失败!" + e.getMessage());
        }
    }


    @Override
    public List<Map<String, String>> subtleImport(MultipartFile file) {
        InputStream inputStream = null;
        try {
            String filename = file.getOriginalFilename();
            if (filename == null) {
                throw new NullArgumentException();
            }
            inputStream = file.getInputStream();
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(inputStream);
            List<Map<String, String>> maps = new ArrayList<>();
            Map<String, String> headMap = new HashMap<>();
            int i = 0;
            for (Sheet xssfSheet : xssfWorkbook) {
                if (xssfSheet == null) {
                    continue;
                }
                //处理当前页,循环读取每一行
                for (int rowNum = 0; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
                    Map<String, String> dataMap = new HashMap<>();
                    Row xssfRow = xssfSheet.getRow(rowNum);
                    int minColIx = xssfRow.getFirstCellNum();
                    int maxColIx = xssfRow.getLastCellNum();
                    List<String> rowList = new ArrayList<>();
                    //遍历行,获取cell元素
                    for (int colIx = minColIx; colIx < maxColIx; colIx++) {
                        XSSFCell cell = (XSSFCell) xssfRow.getCell(colIx);
                        if (cell == null) {
                            continue;
                        }
                        if (rowNum == 0) {
                            headMap.put(String.valueOf(i), cell.toString());
                            i++;
                        }
                        rowList.add(cell.toString());
                        if (rowNum > 0) {
                            String key = headMap.get(String.valueOf(colIx));
                            String[] split = key.split("\\|");
                            dataMap.put(split[1], cell.toString());
                        }
                    }
                    if (rowNum > 0) {
                        maps.add(dataMap);
                    }
                }
            }
            return maps;
        } catch (IOException e) {
            throw new RuntimeException("导入数据失败");
        }finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


图片

package com.guodi.bpm.form.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.deepoove.poi.data.PictureRenderData;
import com.deepoove.poi.data.PictureType;
import com.deepoove.poi.data.Pictures;
import com.guodi.bpm.form.model.dto.PrintPhotoFormatDTO;
import com.guodi.bpm.form.service.IPrintFormatValue;
import com.guodi.bpm.form.util.minio.MinioTemplates;
import com.guodi.bpm.model.enums.PhotoFormatEnum;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Description: 打印图片格式转换
 *
 * @Author: 洪家洪
 * @Date: 2023/8/9 11:19
 **/
@Service("ImageFormatImpl")
public class ImageFormatImpl implements IPrintFormatValue {

    @Resource
    private MinioTemplates minioTemplates;

    @Override
    public boolean containsFormat(String format) {
        try {
            return PhotoFormatEnum.valueOf(format) != null;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public Object formatValue(Object value, String format, String setting) {
        String valueString = value != null ? value.toString() : null;
        if (format.equals(PhotoFormatEnum.IMG.name())) {
            return this.photoFormat(valueString, setting);
        } else if (format.equals(PhotoFormatEnum.IMG_STR.name())) {
            return this.qrCodeFormat(valueString);
        } else if (format.equals(PhotoFormatEnum.IMGLIST.name())) {
            return this.photoFormatList(valueString, setting);
        }
        return null;
    }

    //打印处理多张图片
    public List<PrintPhotoFormatDTO> photoFormatList(String value, String setting) {
        //截取模版图片宽高
        int width = 0;
        int height = 0;
        if (Objects.nonNull(setting)) {
            //获取宽高
            String[] size = setting.split("x");
            //宽
            width = Integer.parseInt(size[0]);
            //高
            height = Integer.parseInt(size[1]);
        }
        //获取minio图片地址
        List<String> objectUrls = getPhotoUrls(value);
        List<PrintPhotoFormatDTO> nameList = new ArrayList<>();
        if (objectUrls.size() > 0) {
            for (String objectUrl : objectUrls) {
                PrintPhotoFormatDTO photoFormatDTO = new PrintPhotoFormatDTO();
                if (width == 0) {
                    photoFormatDTO.setNAME(Pictures.of(objectUrl).create());
                } else {
                    photoFormatDTO.setNAME(Pictures.of(objectUrl).size(width, height).create());
                }
                nameList.add(photoFormatDTO);
            }
            return nameList;
        }
        return null;
    }

    //打印处理单张图片
    public PictureRenderData photoFormat(String value, String setting) {
        //截取模版图片宽高
        int width = 0;
        int height = 0;

        if (Objects.nonNull(setting)) {
            //获取宽高
            String[] size = setting.split("x");
            //宽
            width = Integer.parseInt(size[0]);
            //高
            height = Integer.parseInt(size[1]);
        }
        //获取minio图片地址
        List<String> objectUrls = getPhotoUrls(value);
        if (objectUrls.size() > 0) {
            //判断是否有设置图片大小,没设置默认图片大小
            if (width == 0) {
                return Pictures.of(objectUrls.get(0)).create();
            } else {
                return Pictures.of(objectUrls.get(0)).size(width, height).create();
            }
        }
        return null;
    }

    //打印处理二维码
    public PictureRenderData qrCodeFormat(String value) {
        if (Objects.nonNull(value)) {
            return Pictures.ofBase64(value, PictureType.PNG).create();
        }
        return null;
    }


    //获取minio图片地址
    private List<String> getPhotoUrls(String value) {
        //获取到图片路径存到list
        List<String> photoUrls = new ArrayList<>();
        if (Objects.nonNull(value)) {
            JSONArray jsonArray = new JSONArray(value);
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                //获取图片路径
                String filePath = jsonObject.getStr("filePath");
                photoUrls.add(filePath);
            }
        }
        //由于路径带了存储桶名称,因为需要去除存储桶
        List<String> photoUrlList = new ArrayList<>();
        for (String photoUrl : photoUrls) {
            String url = photoUrl.substring(photoUrl.indexOf("from-file"));
            photoUrlList.add(url);
        }
        //获取minio图片文件绝对路径
        List<String> objectUrls = new ArrayList<>();
        for (String objectName : photoUrlList) {
            String objectUrl = minioTemplates.getObjectUrl(objectName);
            objectUrls.add(objectUrl);
        }
        return objectUrls;
    }
}

单复选框

package com.guodi.bpm.form.service.impl;

import cn.hutool.core.util.EnumUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.deepoove.poi.data.TextRenderData;
import com.deepoove.poi.data.style.Style;
import com.guodi.bpm.form.service.IPrintFormatValue;
import com.guodi.bpm.model.enums.BoxFormatEnum;
import com.guodi.bpm.model.enums.FormatEnum;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * Description: 打印复选框 、单选框格式转换
 *
 * @Author: 洪家洪
 * @Date: 2023/8/9 11:18
 **/
@Service("BoxFormatImpl")
public class BoxFormatImpl implements IPrintFormatValue {
    @Override
    public boolean containsFormat(String format) {
        try {
            return BoxFormatEnum.valueOf(format) != null;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public Object formatValue(Object value, String format, String setting) {
        String valueString = value != null ? value.toString() : null;
        if (BoxFormatEnum.CHK.name().equals(format)) {
            return this.handleCheckBox(valueString, setting);
        } else if (BoxFormatEnum.CHKG.name().equals(format)) {
            return this.handleCheckBoxJson(valueString);
        } else if (BoxFormatEnum.RDO.name().equals(format)) {
            return this.handleRadio(valueString, setting);
        } else if (BoxFormatEnum.RDOG.name().equals(format)) {
            return this.handleRadioJson(valueString);
        }
        return null;
    }

    //处理复选框
    public TextRenderData handleCheckBox(String value, String setting) {
        //勾选 F0FE 25A1 25A0
        TextRenderData selSymbol = new TextRenderData("■", new Style("Wingdings 2", 10.5));
        //不勾选  ■ □
        TextRenderData unselSymbol = new TextRenderData("□", new Style("Wingdings 2", 10.5));
        //复选简单值模式
        if (StrUtil.isNotBlank(value) && !"[]".equals(value) || (StrUtil.isNotBlank(value) && StrUtil.isNotBlank(setting) && value.indexOf(setting) != -1)) {
            return selSymbol;
        } else {
            return unselSymbol;
        }
    }

    //复选框JSON组模式
    public StringBuffer handleCheckBoxJson(String value) {
        Map<String, Boolean> checkColorMap = new LinkedHashMap<>();
        JSONArray jsonArray = new JSONArray(value);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            //获取checkbox的值与是否勾选标识
            String checkBoxValue = jsonObject.getStr("value");//对应模板字典编号
            String checkBoxLabel = jsonObject.getStr("label");//对应模板字典名称
            String ifCheckBox = jsonObject.getStr("checked");
            boolean aBoolean = Boolean.parseBoolean(ifCheckBox);
            checkColorMap.put(checkBoxLabel, aBoolean);
        }
        StringBuffer sb = new StringBuffer();
        Set<Map.Entry<String, Boolean>> entries = checkColorMap.entrySet();
        for (Map.Entry<String, Boolean> map : entries) {
            String checkBox;
            // 勾选(一个大写的R加上Wingdings 2字体就是一个勾选的方框)
            if (map.getValue()) {
                checkBox = "■";
            } else {
                // 不勾选的unicode编码
                checkBox = "□";
            }
            sb.append(checkBox).append(map.getKey() + "  ");
        }
        return sb;
    }


    //处理单选框
    public TextRenderData handleRadio(String value, String setting) {
        //勾选 009E
        TextRenderData selSymbol = new TextRenderData("●", new Style("Wingdings 2", 10.5));
        //不勾选 0099
        TextRenderData unselSymbol = new TextRenderData("○", new Style("Wingdings 2", 10.5));
        //简单值模式
        if (StrUtil.isNotBlank(value) || (StrUtil.isNotBlank(setting) && value.equals(setting))) {
            return selSymbol;
        } else {
            return unselSymbol;
        }
    }


    //处理单选框json
    public StringBuffer handleRadioJson(String value) {
        //复选框JSON组模式
        Map<String, Boolean> checkColorMap = new LinkedHashMap<>();
        JSONArray jsonArray = new JSONArray(value);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            //获取checkbox的值与是否勾选标识
            String checkBoxLabel = jsonObject.getStr("label");//对应模板字典名称
            String checkBoxValue = jsonObject.getStr("value");//对应模板字典编号
            String ifCheckBox = jsonObject.getStr("checked");
            boolean aBoolean = Boolean.parseBoolean(ifCheckBox);
            checkColorMap.put(checkBoxLabel, aBoolean);
        }
        StringBuffer sb = new StringBuffer();
        Set<Map.Entry<String, Boolean>> entries = checkColorMap.entrySet();
        for (Map.Entry<String, Boolean> map : entries) {
            String checkBox;
            // 勾选 \uF0A4
            if (map.getValue()) {
                checkBox = "●";
            } else {
                // 不勾选 \uF0A1
                checkBox = "○";
            }
            sb.append(checkBox).append(map.getKey() + "  ");
        }
        return sb;
    }

}

通用数字,时间格式转换

package com.guodi.bpm.tool.util.formatUtil;


import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.Calendar;
import java.util.Date;


/**
 * @author lwh
 * @description: 数字时间格式化工具类
 * @date: 2023/6/29 15:01
 */
public class FormatUtil {
    public static void main(String[] args) {
    }


    /***
     * @author lwh
     * function: 将数字转化为yyyy年MM月dd日格式和yyyy-MM-dd
     * @createDate 2023-6-29 下午15:18:12
     * @param time 日期
     * @return 转换后的yyyy年MM月dd日格式
     */

    public static String toUpper(String time,String type) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dTime = new SimpleDateFormat("yyyy年MM月dd日");
        SimpleDateFormat dTimes = new SimpleDateFormat("yyyy-MM-dd");
        String format = null;
        if (time != null && StringUtils.isNotBlank(time)) {
            Date parse = null;
            try {
                parse = df.parse(time);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if (type == FormatEnum.DATETYPE1.name()){
                format = dTimes.format(parse);
            }else {
                format = dTime.format(parse);
            }
        }
        return format;
    }

    /***
     * @author lwh
     * function: 将数字转化为中文大写日期格式和年份中文格式返回
     * @createDate 2023-6-29 下午15:33:12
     * @param time 日期
     * @return 转换后的中文大写日期格式
     */
    public static String toCnUpper(String time) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String timeFormat = null;
        if (time != null && StringUtils.isNotBlank(time)) {
            Date format = null;
            try {
                format = df.parse(time);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            //时间转大写
            timeFormat = dataToUpper(format);
        }
        return timeFormat;
    }

    /***
     * @author lwh
     * function: 将日期按类型返回 年 月 日 (数字与中文)
     * @createDate 2023-7-3 上午9:44
     * @param time 日期
     * @return 将日期按类型返回【int】
     */
    public static Object toFormatSpecificDate(String time,String type){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        if (time != null && StringUtils.isNotBlank(time)) {
            try {
               Date format = df.parse(time);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(format);
                // 获取年份、月份和日期
                if (type.equals(FormatEnum.DATEYEAR.name())){
                    return calendar.get(Calendar.YEAR);
                }else if (type.equals(FormatEnum.DATEMONTH.name())){
                    return calendar.get(Calendar.MONTH)+1;
                }else if (type.equals(FormatEnum.DATEDAY.name())){
                    return calendar.get(Calendar.DAY_OF_MONTH);
                }else if (type.equals(FormatEnum.DATEYEAR_CN.name())){
                    return numToUpper(calendar.get(Calendar.YEAR));
                } else if (type.equals(FormatEnum.DATEMONTH_CN.name())){
                    return monthToUppder(calendar.get(Calendar.MONTH)+1);
                }else if (type.equals(FormatEnum.DATEDAY_CN.name())){
                    return dayToUppder(calendar.get(Calendar.DAY_OF_MONTH));
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /***
     * @author lwh
     * function: 将数字按类型返回中文 中文数字,格式:贰零零染
     * @createDate 2023-7-3 上午10:44
     * @param num 数字
     * @return 将日期按类型返回【string】
     */
    public static String toCnUpperNum(int num,String type){
        if (type.equals(FormatEnum.NUMBERCN2.getValue())){
            String toUpperNum = numCnToUpper(num);
            return toUpperNum;
        }else if (type.equals(FormatEnum.NUMBERCN.getValue())){
            String convert = getNumberStr(num);
            return convert;
        }
        return null;
    }

    /***
     * @author lwh
     * function: 将数字按类型返回中文 中文数字,格式:贰仟零柒圆整
     * @createDate 2023-7-4 下午16:52
     * @param num 数字
     * @return 将日期按类型返回【string】
     */
    public static String toCnUpperNum(String num){
            BigDecimal bigDecimal = new BigDecimal(num);
            String convert = convert(bigDecimal);
            return convert;
    }




    //转中文金额 begin ====================================================================================================

    private static final String[] CN_NUMERIC = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
    private static final String[] CN_UNIT = {"圆", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿"};

    public static String convert(BigDecimal amount) {
        if (amount.compareTo(BigDecimal.ZERO) == 0) {
            return "零元整";
        }

        StringBuilder result = new StringBuilder();
        // 转换为字符串,并去除小数点后多余的0
        String strAmount = amount.stripTrailingZeros().toPlainString();
        int dotIndex = strAmount.indexOf(".");
        // 整数部分
        String integerPart = "";
        if (dotIndex > -1) {
            integerPart = strAmount.substring(0, dotIndex);
        } else {
            integerPart = strAmount;
        }
        int length = integerPart.length();
        // 是否遇到连续的0
        boolean isZero = false;
        for (int i = 0; i < length; i++) {
            // 获取当前数字的值
            int digit = Integer.parseInt(integerPart.substring(i, i + 1));
            int unitIndex = length - i - 1; // 数字所在的单位位置
            boolean isLastUnit = unitIndex == 0; // 是否为最后一个单位

            // 处理连续的0
            if (digit == 0) {
                isZero = true;
                // 若当前数字是最后一个单位对应的数字,并且前面还有非0数字,则追加单位
                if (isLastUnit && !result.toString().endsWith("零")) {
                    result.append(CN_UNIT[unitIndex]);
                }
            } else {
                // 处理非0数字
                if (isZero) {
                    result.append("零");
                    isZero = false;
                }
                result.append(CN_NUMERIC[digit]).append(CN_UNIT[unitIndex]);
            }
        }

        // 处理小数部分
        if (dotIndex > -1) {
            String decimalPart = strAmount.substring(dotIndex + 1);
            int decLength = decimalPart.length();
            if (decLength == 1) {
                int digit = Integer.parseInt(decimalPart);
                if (digit != 0) {
                    result.append(CN_NUMERIC[digit]).append("角");
                }
            } else if (decLength == 2) {
                int digit1 = Integer.parseInt(decimalPart.substring(0, 1));
                int digit2 = Integer.parseInt(decimalPart.substring(1, 2));
                if (digit1 != 0) {
                    result.append(CN_NUMERIC[digit1]).append("角");
                }
                if (digit2 != 0) {
                    result.append(CN_NUMERIC[digit2]).append("分");
                }
            }
        }

        return result.append("整").toString();
    }

    //转中文金额 end ====================================================================================================


  //日期转化为大小写 begin ====================================================================================================

    public static String dataToUpper(Date date) {

        Calendar ca = Calendar.getInstance();

        ca.setTime(date);

        int year = ca.get(Calendar.YEAR);

        int month = ca.get(Calendar.MONTH) + 1;

        int day = ca.get(Calendar.DAY_OF_MONTH);

        return numToUpper(year) + "年" + monthToUppder(month) + "月" + dayToUppder(day) + "日";

    }


    /***

     * function: 月转化为大写

     * @createDate 2010-5-27 上午10:41:42

     * @param month 月份

     * @return 返回转换后大写月份

     */

    public static String monthToUppder(int month) {

        if (month < 10) {

            return numToUpper(month);

        } else if (month == 10) {

            return "十";

        } else {

            return "十" + numToUpper(month - 10);

        }

    }

    /***

     * function: 日转化为大写

     * @createDate 2010-5-27 上午10:43:32

     * @param day 日期

     * @return 转换大写的日期格式

     */

    public static String dayToUppder(int day) {

        if (day < 20) {

            return monthToUppder(day);

        } else {

            char[] str = String.valueOf(day).toCharArray();

            if (str[1] == '0') {

                return numToUpper(Integer.parseInt(str[0] + "")) + "十";

            } else {

                return numToUpper(Integer.parseInt(str[0] + "")) + "十" + numToUpper(Integer.parseInt(str[1] + ""));

            }

        }

    }

    //日期转化为大小写 end ====================================================================================================




   //转中文数字 begin ====================================================================================================

    /***

     * function: 将数字转化为大写

     * @createDate 2010-5-27 上午10:28:12

     * @param num 数字

     * @return 转换后的大写数字

     */

    public static String numToUpper(int num) {

        // String u[] = {"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};

        // String u[] = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};

        String u[] = {"○", "一", "二", "三", "四", "五", "六", "七", "八", "九"};

        char[] str = String.valueOf(num).toCharArray();

        String rstr = "";

        for (int i = 0; i < str.length; i++) {

            rstr = rstr + u[Integer.parseInt(str[i] + "")];

        }

        return rstr;

    }



    /***

     * function: 将数字转化为大写

     * @createDate 2010-5-27 上午10:28:12

     * @param num 数字

     * @return 转换后的大写数字

     */

    public static String numCnToUpper(int num) {

        String u[] = {"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};

        char[] str = String.valueOf(num).toCharArray();

        String rstr = "";

        for (int i = 0; i < str.length; i++) {

            rstr = rstr + u[Integer.parseInt(str[i] + "")];

        }

        return rstr;

    }

    private static String[] NUMBER1 = {"零", "一", "两", "三", "四", "五", "六", "七", "八", "九"};
    private static String[] NUMBER2 = {"零", "十", "百", "千", "万", "亿"};

    /**
     * @param num
     * @return
     * @Author:lwh
     * @Description:将数字转化为大写
     */
    public static String getNumberStr(int num) {
        if (num < 0) {
            return "";
        }
        if (num == 0) {
            return NUMBER1[0];
        }
        int split = 10000;
        int y = num / (split * split);
        int w = (num / split) % split;
        int g = num % split;
        StringBuffer sb = new StringBuffer();
        //亿
        if (y > 0) {
            sb.append(getNumberStr1000(y));
            sb.append(NUMBER2[5]);
        }
        //万
        if (w > 999) {
            sb.append(getNumberStr1000(w));
            sb.append(NUMBER2[4]);
        } else {
            if (w > 0) {
                if (y != 0) {
                    sb.append(NUMBER2[0]);
                }
                sb.append(getNumberStr1000(w));
                sb.append(NUMBER2[4]);
            }
        }
        //万以下
        if (g > 0) {
            if (w != 0) {
                if (g > 999) {
                    sb.append(getNumberStr1000(g));
                } else {
                    sb.append(NUMBER2[0]);
                    sb.append(getNumberStr1000(g));
                }

            } else {
                if (y != 0) {
                    sb.append(NUMBER2[0]);
                }
                sb.append(getNumberStr1000(g));
            }
        }
        return sb.toString();
    }

    /**
     * @param num
     * @return
     * @Description:对万以下的数字进行大小写转化
     */
    private static String getNumberStr1000 (int num) {
        if (num > 9999 || num < 0) {
            return "";
        }
        int q = num / 1000;
        int b = (num / 100) % 10;
        int s = (num / 10) % 10;
        int g = num % 10;
        StringBuffer sb = new StringBuffer();
        //千
        if (q > 0) {
            sb.append(NUMBER1[q]);
            sb.append(NUMBER2[3]);
        }
        //百
        if (b > 0) {
            sb.append(NUMBER1[b]);
            sb.append(NUMBER2[2]);
        } else {
            if (q != 0) {
                sb.append(NUMBER2[0]);
            }
        }
        //十
        if (s > 0) {
            sb.append(NUMBER1[s]);
            sb.append(NUMBER2[1]);
        } else {
            if (b != 0) {
                sb.append(NUMBER2[0]);
            }
        }
        //个
        if (g > 0) {
            sb.append(NUMBER1[g]);
        }
        return sb.toString();
    }

    //转中文数字 end ====================================================================================================


}

你可能感兴趣的:(java)