获取模板导出文档工具类,将工作遇到的知识点记个笔记,方便查阅

获取模板导出文档工具类

导出时,模板需要修改的位置设置成#{Java对象属性名} 。例如:

模块: 姓名:#{name}

代码也包含文档需要根据java信息来给方框打√,或者对错,包含续页文档等等

代码包含将java对象里面为null转换为空字符串方法,文字全角转半角,半角转全角

package com.jqkj.sjgpt.module.manage.controller.admin.sheet.wordUtils.wordExport;

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import lombok.extern.slf4j.Slf4j;
import org.apache.tika.utils.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 导出Word文件
 * 模板放在Resources文件夹templatefile里面
 *
 */
@Slf4j
public class WordUtils<T> {

    public static final String BASEPATH = "templatefile";


    private Document reportDoc;//spire.doc的word文档对象
    private T formClass;//导出所需实体类
    private String reportFileName;//导出文件的名称


    public WordUtils(T formClass, String reportFileName) {

        this.formClass = formClass;
        this.reportFileName = reportFileName;
    }

    /**
     * 开启导出文档
     */
    public WordUtils exportWord(HttpServletResponse response) throws Exception {
        //1. 设置相应参数
        response.reset();
        response.setContentType("application/octet-stream; charset=utf-8");

        // 设置文件名
        String headerValue = "attachment; filename=" + URLEncoder.encode(reportFileName, "UTF-8");
        response.setHeader("Content-Disposition", headerValue);
        response.setCharacterEncoding("utf-8");
//        2. 获取模板word文件,并复制模板word文件到资源目录
//        copyTemplateToReport(ReportTemplateFileEnum.get(formClass.getClass().getSimpleName()).getName(), reportFileName);
//        3. 根据java对象信息对模板文件进行写入
        log.info("开始写入报告内容");
        try {
            writeInfo(response.getOutputStream());
        } catch (Exception e) {
            log.error("写入报告内容出错了:" + e.getMessage());
            log.error(e.toString());
        }
        log.info("写入报告完成");
        return this;
    }

    /**
     * 把Java对象信息写入到报告中
     */
    private void writeInfo(OutputStream os) throws Exception {
        reportDoc = new Document();

        //获取Resources/templatefile文件夹的模板
        String templateFileName = ReportTemplateFileEnum.get(formClass.getClass().getSimpleName()).getName();
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(BASEPATH + templateFileName);
        reportDoc.loadFromStream(resourceAsStream, FileFormat.Docx);
        log.info("文档已加载");

        //读取类的字段,并替换
        log.info("开始读取类的字段");
        Field[] fields = formClass.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            log.info("读取到字段:{},字段值:{}", field.getName(), field.get(formClass));
            reportDoc.replace(genPattenToReplace(field.getName()), field.get(formClass).toString(), false, true);
        }
        log.info("填充争议调处情况完成");
        //保存到文件
        //Document reportDoc.saveToFile(targetFilePath);
        //输出到http reponse stream
        reportDoc.saveToStream(os, FileFormat.Auto);
    }

    /**
     * 生成替换的占位符
     */
    private String genPattenToReplace(String field) {
        return "#{" + field + "}";
    }

    /**
     * 清理临时文件
     */
    public WordUtils dispose() {
        //1. 释放资源
        reportDoc.dispose();
        return this;
    }


//    /**
//     * 开启报告生成流程(附带子表的)
//     */
//    public <D> D WordUtils(HttpServletResponse response,List<D> childList) throws Exception {
//        //1. 设置相应参数
//        response.reset();
//        response.setContentType("application/octet-stream; charset=utf-8");
//
//        // 设置文件名
//        String headerValue = "attachment; filename=" + URLEncoder.encode(reportFileName, "UTF-8");
//        response.setHeader("Content-Disposition", headerValue);
//        response.setCharacterEncoding("utf-8");
//        //2. 获取模板word文件,并复制模板word文件到资源目录
//        copyTemplateToReport(ReportTemplateFileEnum.get(formClass.getClass().getSimpleName()).getName(), reportFileName);
//        log.info("开始写入报告内容");
//        try {
//            ServletOutputStream os = response.getOutputStream();
//            String targetFilePath = jeePlusProperites.getReportBaseDir() + reportFileName;
//            log.info("报告文档路径:" + targetFilePath);
//            //加载包含书签的文档
//            reportDoc = new Document();
//            log.info("开始加载报告文档:" + targetFilePath);
//            reportDoc.loadFromFile(targetFilePath);
//            log.info("文档已加载");
//
//            //读取类的字段,并替换
//            log.info("开始读取类的字段");
//            Field[] fields = formClass.getClass().getDeclaredFields();
//            for (Field field : fields) {
//                field.setAccessible(true);
//                log.info("读取到字段:{},字段值:{}", field.getName(), field.get(formClass));
//                reportDoc.replace(genPattenToReplace(field.getName()), field.get(formClass).toString(), false, true);
//            }
//
//            //添加子表信息
//            Table table = reportDoc.getSections().get(0).getTables().get(0);
//            for (D child : childList) {
//                List<Object> list = new ArrayList<>();
//                for (Field field : child.getClass().getDeclaredFields()) {
//                    field.setAccessible(true);
//                    list.add(field.get(child));
//                }
//                TableRow tableRow = table.addRow();
//                for (int i = 0; i < tableRow.getCells().getCount(); i++) {
//                    tableRow.getCells().get(i).addParagraph().appendText(list.get(i).toString());
//                }
//            }
//
//            log.info("填充争议调处情况完成");
//            //保存到文件
//            //Document reportDoc.saveToFile(targetFilePath);
//            //输出到http reponse stream
//            reportDoc.saveToStream(os, FileFormat.Auto);
//        } catch (Exception e) {
//            log.error("写入报告内容出错了:" + e.getMessage());
//            log.error(e.toString());
//        }
//        log.info("写入报告完成");
//        return null;
//    }
//
//    /**
//     * 开启报告生成流程 附带照片
//     */
//    public ReportFileGenerator WordUtilsWithPic(HttpServletResponse response, List<String> filePathList, int x, int y) throws Exception {
//
//        //1. 设置相应参数
//        response.reset();
//        response.setContentType("application/octet-stream; charset=utf-8");
//
//        // 设置文件名
//        String headerValue = "attachment; filename=" + URLEncoder.encode(reportFileName, "UTF-8");
//        response.setHeader("Content-Disposition", headerValue);
//        response.setCharacterEncoding("utf-8");
//        //2. 获取模板word文件,并复制模板word文件到资源目录
        copyTemplateToReport(ReportTemplateFileEnum.get(formClass.getClass().getSimpleName()).getName(), reportFileName);
//        log.info("开始写入报告内容");
//        ServletOutputStream os = response.getOutputStream();
//        try {
            String targetFilePath = jeePlusProperites.getReportBaseDir() + reportFileName;
            log.info("报告文档路径:" + targetFilePath);
//            //加载包含书签的文档
//            reportDoc = new Document();
            log.info("开始加载报告文档:" + targetFilePath);
            reportDoc.loadFromFile(targetFilePath);
//            reportDoc.loadFromStream(this.getClass().getClassLoader().getResourceAsStream("/" + templateName), FileFormat.Docx);
//            log.info("文档已加载");
//
//            //查找文档中的字符串并替换
//            TextSelection[] selections = reportDoc.findAllString("#{tp}", true, true);
//            //用图片替换文字
//            int index = 0;
//            TextRange range = null;
//            for (Object obj : selections) {
//                TextSelection textSelection = (TextSelection) obj;
//                range = textSelection.getAsOneRange();
//                index = range.getOwnerParagraph().getChildObjects().indexOf(range);
//                int i = 0;
//                for (String filePath : filePathList) {
//                    DocPicture pic = new DocPicture(reportDoc);
//                    String picPath = filePath;
//                    pic.loadImage(picPath);
//                    //设置居中,环绕为四周环绕
//                    pic.setVerticalAlignment(ShapeVerticalAlignment.Center);
//                    pic.setTextWrappingStyle(TextWrappingStyle.Square);
//                    pic.setTextWrappingType(TextWrappingType.Both);
//                    pic.setWidth(x);
//                    pic.setHeight(y);
//                    range.getOwnerParagraph().getChildObjects().insert(index + i, pic);
//                    i++;
//                }
//                range.getOwnerParagraph().getChildObjects().remove(range);
//            }
//
//            //读取类的字段,并替换
//            log.info("开始读取类的字段");
//            Field[] fields = formClass.getClass().getDeclaredFields();
//            for (Field field : fields) {
//                field.setAccessible(true);
//                log.info("读取到字段:{},字段值:{}", field.getName(), field.get(formClass));
//                reportDoc.replace(genPattenToReplace(field.getName()), field.get(formClass).toString(), false, true);
//            }
//            reportDoc.replace("#{tp}", "", false, true);
//            reportDoc.replace("#{zp}", "", false, true);
//
//            log.info("填充争议调处情况完成");
//            //保存到文件
//            //Document reportDoc.saveToFile(targetFilePath);
//            //输出到http reponse stream
//            reportDoc.saveToStream(os, FileFormat.Auto);
//        } catch (Exception e) {
//            log.error("写入报告内容出错了:" + e.getMessage());
//            log.error(e.toString());
//        }
//        log.info("写入报告完成");
//        return this;
//    }
//
//
//    /**
//     * 拷贝模板文件到报告目录
//     *
//     * @param templateFileName 模板文件名
//     * @param targetFileName   报告文件名
//     */
//    private void copyTemplateToReport(String templateFileName, String targetFileName) throws Exception {
//
//
//
//        File templateFile = new File(jeePlusProperites.getReportTemlateBaseDir() + templateFileName);
//        if (!templateFile.exists()) {
//            new IOException("模板文件丢失");
//            return;
//        }
//        FileUtils.copyFileCover(模板路径, 将模板拷贝一份到指定路径再编写的指定路径, true);
//    }




    /**
     *
     * 将对象内的空格/NULL属性转换为空字符串
     *
     * @param object 传入对象
     */
    public static void formatData(Object object) throws IllegalAccessException{
        Field[] fields = object.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            if (field.get(object) == null) {
                field.set(object,"  ");
            } else if (StringUtils.isBlank(field.get(object).toString())) {
                field.set(object,"  ");
            }
        }
    }
    /**
     *
     * 将旧日期格式转换为新日期格式
     *
     * @param strDate 日期字符串
     * @param oldFormat 旧格式(支持格式:yyyy-MM-dd 或 yyyy-MM-dd-HH-mm-ss)
     * @param newFormat 新格式(支持格式:yyyy年MM月dd 或 yyyy年MM月dd日HH时mm分ss秒)
     * @return  返回指定格式日期字符串
     */
    public static String formatDate(String strDate,String oldFormat,String newFormat) {
        if (StringUtils.isBlank(strDate)) {
            return "";
        }
        SimpleDateFormat orgFormat = new SimpleDateFormat(oldFormat);
        SimpleDateFormat updateFormat = new SimpleDateFormat(newFormat);
        try {
            Date old = orgFormat.parse(strDate);
            return updateFormat.format(old);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }


//    /**
//     * 开启报告生成流程(需要根据  “是” 、 “否”  划  √ (tick) 的, 在单独一个表格里面划√)
//     * @param response http响应对象
//     * @param startIndex 表格中开始划 √ 的行数 (从0开始)
//     * @param yes 表格中 “是” 划 √ 的列数 (从0开始)
//     * @param no 表格中 “否” 划 √ 的列数 (从0开始)
//     * @param params 需要判断的字段值数组
//     * @return 返回ReportFileGenerator
//     * @throws Exception 抛出异常
//     */
//    public ReportFileGenerator WordUtilsWithTick(HttpServletResponse response, int startIndex, int yes, int no, String... params) throws Exception {
//
//        //1. 设置相应参数
//        response.reset();
//        response.setContentType("application/octet-stream; charset=utf-8");
//
//        // 设置文件名
//        String headerValue = "attachment; filename=" + URLEncoder.encode(reportFileName, "UTF-8");
//        response.setHeader("Content-Disposition", headerValue);
//        response.setCharacterEncoding("utf-8");
//        //2. 获取模板word文件,并复制模板word文件到资源目录
//        copyTemplateToReport(ReportTemplateFileEnum.get(formClass.getClass().getSimpleName()).getName(), reportFileName);
//        log.info("开始写入报告内容");
//        try {
//            ServletOutputStream os = response.getOutputStream();
//            String targetFilePath = jeePlusProperites.getReportBaseDir() + reportFileName;
//            log.info("报告文档路径:" + targetFilePath);
//            //加载包含书签的文档
//            reportDoc = new Document();
//            log.info("开始加载报告文档:" + targetFilePath);
//            reportDoc.loadFromFile(targetFilePath);
//            log.info("文档已加载");
//
//            //读取类的字段,并替换
//            log.info("开始读取类的字段");
//            Field[] fields = formClass.getClass().getDeclaredFields();
//            for (Field field : fields) {
//                field.setAccessible(true);
//                log.info("读取到字段:{},字段值:{}", field.getName(), field.get(formClass));
//                reportDoc.replace(genPattenToReplace(field.getName()), field.get(formClass).toString(), false, true);
//            }
//            //对一些表格进行勾选对勾处理
//            //获取文档中的第一个节
//            Section section = reportDoc.getSections().get(0);
//            //获取表格
//            Table table = section.getTables().get(0);
//            for (String param : params) {
//                if ("是".equals(param)) {
//                    IParagraph firstParagraph = table.getRows().get(startIndex).getCells().get(yes).getFirstParagraph();
//                    firstParagraph.appendText("√");
//                    startIndex++;
//                } else if ("否".equals(param)) {
//                    IParagraph firstParagraph = table.getRows().get(startIndex).getCells().get(no).getFirstParagraph();
//                    firstParagraph.appendText("√");
//                    startIndex++;
//                } else {
//                    startIndex++;
//                }
//            }
//            log.info("填充争议调处情况完成");
//            //保存到文件
//            //Document reportDoc.saveToFile(targetFilePath);
//            //输出到http reponse stream
//            reportDoc.saveToStream(os, FileFormat.Auto);
//        } catch (Exception e) {
//            log.error("写入报告内容出错了:" + e.getMessage());
//            log.error(e.toString());
//        }
//        log.info("写入报告完成");
//        return this;
//    }
//
//    /**
//     * 开启报告生成流程(需要根据 属性值 选择性划对勾的, 在 表格中的小方块中打√)
//     * @param response http响应对象
//     * @param results 传入所有需要划对勾属性的集合
//     * @param params 所有情况的字符串
//     * @return 返回ReportFileGenerator
//     * @throws Exception 抛出异常
//     */
//    public ReportFileGenerator WordUtilsWithChoose(HttpServletResponse response, List<String> results,String... params) throws Exception {
//
//        //1. 设置相应参数
//        response.reset();
//        response.setContentType("application/octet-stream; charset=utf-8");
//
//        // 设置文件名
//        String headerValue = "attachment; filename=" + URLEncoder.encode(reportFileName, "UTF-8");
//        response.setHeader("Content-Disposition", headerValue);
//        response.setCharacterEncoding("utf-8");
//        //2. 获取模板word文件,并复制模板word文件到资源目录
//        copyTemplateToReport(ReportTemplateFileEnum.get(formClass.getClass().getSimpleName()).getName(), reportFileName);
//        log.info("开始写入报告内容");
//        try {
//            ServletOutputStream os = response.getOutputStream();
//            String targetFilePath = jeePlusProperites.getReportBaseDir() + reportFileName;
//            log.info("报告文档路径:" + targetFilePath);
//            //加载包含书签的文档
//            reportDoc = new Document();
//            log.info("开始加载报告文档:" + targetFilePath);
//            reportDoc.loadFromFile(targetFilePath);
//            log.info("文档已加载");
//
//            //读取类的字段,并替换
//            log.info("开始读取类的字段");
//            Field[] fields = formClass.getClass().getDeclaredFields();
//            for (Field field : fields) {
//                field.setAccessible(true);
//                log.info("读取到字段:{},字段值:{}", field.getName(), field.get(formClass));
//                reportDoc.replace(genPattenToReplace(field.getName()), field.get(formClass).toString(), false, true);
//            }
//            //对一些表格进行勾选对勾处理
//            for (String param : params) {
//                if (results.contains(param)) {
//                    TextSelection selection = reportDoc.findString("#{" + param + "}", true, true);
//                    selection.getAsOneRange().getCharacterFormat().setFontName("Wingdings 2");
//                    reportDoc.replace(selection.getSelectedText(), "\u0052", true, true);
//                } else {
//                    TextSelection selection = reportDoc.findString("#{" + param + "}", true, true);
//                    selection.getAsOneRange().getCharacterFormat().setFontName("Wingdings 2");
//                    reportDoc.replace(selection.getSelectedText(), "\u00A3", true, true);
//                }
//            }
//            log.info("填充争议调处情况完成");
//            //保存到文件
//            //Document reportDoc.saveToFile(targetFilePath);
//            //输出到http reponse stream
//            reportDoc.saveToStream(os, FileFormat.Auto);
//        } catch (Exception e) {
//            log.error("写入报告内容出错了:" + e.getMessage());
//            log.error(e.toString());
//        }
//        log.info("写入报告完成");
//        return this;
//    }
//
//
//    /**
//     *
//     *  导出文档,根据内容字数,判断是否使用续页(模板页数和总页数字段应为:page和totalPages)
//     *
//     * @param response 响应数据
//     * @param sySize 首页可接受文字数量
//     * @param xySize 续页可接受文字数量
//     * @param wySize 尾页可接受文字数量
//     * @param xyFileName 续页模板文件名称
//     * @param wyFileName 尾页模板文件名称
//     * @param thZd 替换字段
//     * @param thNr 替换内容
//     * @return 返回ReportFileGenerator
//     * @throws Exception 抛出异常
//     */
//    public ReportFileGenerator WordUtilsWithXy(HttpServletResponse response,int sySize,int xySize,int wySize,String xyFileName,String wyFileName,String thZd,String thNr) throws Exception {
//
//        //1. 设置相应参数
//        response.reset();
//        response.setContentType("application/octet-stream; charset=utf-8");
//
//        // 设置文件名
//        String headerValue = "attachment; filename=" + URLEncoder.encode(reportFileName, "UTF-8");
//        response.setHeader("Content-Disposition", headerValue);
//        response.setCharacterEncoding("utf-8");
//        //2. 获取模板word文件,并复制模板word文件到资源目录
//        copyTemplateToReport(ReportTemplateFileEnum.get(formClass.getClass().getSimpleName()).getName(), reportFileName);
//        log.info("开始写入报告内容");
//        try {
//            ServletOutputStream os = response.getOutputStream();
//            String targetFilePath = jeePlusProperites.getReportBaseDir() + reportFileName;
//            log.info("报告文档路径:" + targetFilePath);
//            //加载包含书签的文档
//            reportDoc = new Document();
//            log.info("开始加载报告文档:" + targetFilePath);
//            reportDoc.loadFromFile(targetFilePath);
//            log.info("文档已加载");
//
//            log.info("开始续页和尾页报告文档:");
//            Document xyDoc = new Document();
//            String xyPath = jeePlusProperites.getReportTemlateBaseDir() + xyFileName;
//            xyDoc.loadFromFile(xyPath);
//            Document wyDoc = new Document();
//            String wyPath = jeePlusProperites.getReportTemlateBaseDir() + wyFileName;
//            wyDoc.loadFromFile(wyPath);
//            log.info("续页、尾页模板已加载");
//
//            //读取类的字段,并替换
//            log.info("开始读取类的字段");
//            //判断续页是否需要添加,并根据情况来添加
//            thNr = thNr.replace(".", "");
//            int length = thNr.length();
//            int totalPages = 2;
//            if (length - (sySize+wySize) > 0) {
//                totalPages += (length - (sySize+wySize)) / xySize;
//                if ((length - (sySize+wySize)) % xySize > 0) {
//                    totalPages++;
//                }
//            }
//            thNr = toSBC(thNr);
//            if (length <= sySize) {
//                Section wySection = wyDoc.getSections().get(0);
//                Section addSection = reportDoc.addSection();
//                for( int j = 0;j< wySection.getBody().getChildObjects().getCount();j++)
//                {
//                    Object object = wySection.getBody().getChildObjects().get(j);
//                    //复制尾页文档中的正文内容添加到文档
//                    addSection.getBody().getChildObjects().add(((DocumentObject) object).deepClone());
//                }
//                reportDoc.replace("#{" + thZd + "}", thNr, false, true);
//                reportDoc.replace("#{" + thZd + "wy}", "", false, true);
//                reportDoc.replace("#{totalPages}", String.valueOf(totalPages), false, true);
//            } else if (length <= sySize+wySize) {
//                Section wySection = wyDoc.getSections().get(0);
//                Section addSection = reportDoc.addSection();
//                for( int j = 0;j< wySection.getBody().getChildObjects().getCount();j++)
//                {
//                    Object object = wySection.getBody().getChildObjects().get(j);
//                    //复制尾页文档中的正文内容添加到文档
//                    addSection.getBody().getChildObjects().add(((DocumentObject) object).deepClone());
//                }
//                reportDoc.replace("#{" + thZd + "}", thNr.substring(0, sySize), false, true);
//                reportDoc.replace("#{" + thZd + "wy}", thNr.substring(sySize), false, true);
//                reportDoc.replace("#{totalPages}", String.valueOf(totalPages), false, true);
//            }
//            else {
//                Section wySection = wyDoc.getSections().get(0);
//                Section xySection = xyDoc.getSections().get(0);
//                //写第一页
//                reportDoc.replace("#{"+thZd+"}", thNr.substring(0, sySize), false, true);
//
//                for (int i = 1; i <= totalPages-2; i++) {
//                    Section addXySection = reportDoc.addSection();
//                    for( int j = 0;j< xySection.getBody().getChildObjects().getCount();j++)
//                    {
//                        Object object = xySection.getBody().getChildObjects().get(j);
//                        //复制文档1中的正文内容添加到文档2
//                        addXySection.getBody().getChildObjects().add(((DocumentObject) object).deepClone());
//                    }
//                    //复制完成,写入数据
//                    if (sySize + xySize * i <= length) {
//                        reportDoc.replace("#{"+thZd+"xy}",
//                                thNr.substring(sySize + xySize * (i - 1), sySize + xySize * i), false, true);
//                    } else {
//                        reportDoc.replace("#{"+thZd+"xy}",
//                                thNr.substring(sySize + xySize * (i - 1)), false, true);
//                    }
//                    reportDoc.replace("#{page}", String.valueOf(i+1), false, true);
//
//                }
//                Section addWySection = reportDoc.addSection();
//                for( int j = 0;j< wySection.getBody().getChildObjects().getCount();j++)
//                {
//                    Object object = wySection.getBody().getChildObjects().get(j);
//                    //复制文档1中的正文内容添加到文档2
//                    addWySection.getBody().getChildObjects().add(((DocumentObject) object).deepClone());
//                }
//                if (sySize + xySize * (totalPages - 2) <= length) {
//                    reportDoc.replace("#{"+thZd+"wy}", thNr.substring(sySize + xySize * (totalPages - 2)),
//                            false, true);
//                } else {
//                    reportDoc.replace("#{"+thZd+"wy}", "", false, true);
//                }
//                reportDoc.replace("#{totalPages}", String.valueOf(totalPages), false, true);
//            }
//            Field[] fields = formClass.getClass().getDeclaredFields();
//            for (Field field : fields) {
//                field.setAccessible(true);
//                log.info("读取到字段:{},字段值:{}", field.getName(), field.get(formClass));
//                reportDoc.replace(genPattenToReplace(field.getName()), field.get(formClass).toString(), false, true);
//            }
//
//            log.info("填充争议调处情况完成");
//            //保存到文件
//            //Document reportDoc.saveToFile(targetFilePath);
//            //输出到http reponse stream
//            reportDoc.saveToStream(os, FileFormat.Auto);
//        } catch (Exception e) {
//            log.error("写入报告内容出错了:" + e.getMessage());
//            log.error(e.toString());
//        }
//        log.info("写入报告完成");
//        return this;
//    }



    /**
     * @param
     * @return java.lang.String
     * @author FeianLing
     * @date 2019/12/10
     * @desc 半角转全角
     */
    public static String toSBC(String val) {
        char chars[] = val.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == ' ') {
                chars[i] = '\u3000';
            } else if (chars[i] < '\177') {
                chars[i] = (char) (chars[i] + 65248);
            }
        }
        return new String(chars);
    }

    /**
     * @param
     * @param val
     * @return java.lang.String
     * @author FeianLing
     * @date 2019/12/10
     * @desc 全角转半角
     */
    public static String toDBC(String val) {
        char chars[] = val.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == '\u3000') {
                chars[i] = ' ';
            } else if (chars[i] > '\uFF00' && chars[i] < '\uFF5F') {
                chars[i] = (char) (chars[i] - 65248);
            }
        }
        return new String(chars);
    }
}

 枚举获取模板文件名

package com.jqkj.sjgpt.module.manage.controller.admin.sheet.wordUtils.wordExport;



import lombok.AllArgsConstructor;
import lombok.Getter;

import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 枚举获取导出文档的名称
 */
@Getter
@AllArgsConstructor
public enum WordUtilsEnum {
    //记录模板路径
    TEMPLATE_PATH(导出对象.class.getSimpleName(), "word模板名称 例如:word.docx"),




    ;

    /**
     * 类型
     */
    private final String id;
    /**
     * 描述
     */
    private final String name;


    /*
     * 以下变量和方法均为满足其他类中有关switch/case的常量判断
     * */

    private static final Map<String, WordUtilsEnum> lookup = new HashMap();

    public static WordUtilsEnum get(String id) {
        return lookup.get(id);
    }

    static {
        Iterator i$ = EnumSet.allOf(WordUtilsEnum.class).iterator();

        while (i$.hasNext()) {
            WordUtilsEnum c = (WordUtilsEnum) i$.next();
            lookup.put(c.id, c);
        }

    }
}
获取Resources文件夹下的模板
 InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(BASEPATH + templateFileName);

  • 10
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值