打开word模板,通过设置标签的方式占位

2024-09-19T08:57:59.png

编写Java代码实现替换word模板中的占位

    public void exportChangeDesignRecords(HttpServletResponse response, HttpServletRequest request, String id) {
        ChangeDesignRecord changeDesignRecord = changeDesignRecordRepository.findById(id).get();
        response.setHeader("Cache-Control", "public, max-age=604800");
        String fileName= "审批(审核)表.docx";
        try(InputStream inputStream = FileUtil.getAsposeTempFileStream(request,fileName,"")) {
            AsposeUtil.judgeLicense("word");
            Document nodes = new Document(inputStream);
//            nodes.getRange().getBookmarks().get("changeCode").setText(changeDesignRecord.getChangeCode());
            nodes.getRange().getBookmarks().get("changeType").setText(changeDesignRecord.getChangeType());
            nodes.getRange().getBookmarks().get("contractAmount").setText(changeDesignRecord.getContractAmount().toString());
            nodes.getRange().getBookmarks().get("changeAmount").setText(changeDesignRecord.getChangeAmount().toString());
            nodes.getRange().getBookmarks().get("changeDescription").setText(changeDesignRecord.getChangeDescription());

            nodes.save(response.getOutputStream(), SaveFormat.DOCX);
            response.getOutputStream().flush();
        } catch (Exception e) {
            log.error("导出{}失败:{}", changeDesignRecord, e);
        }
    }

FileUtil

    /**
     * 获取aspose模板文件流
     * @param fileName 文件名
     * @param directory 模板目录 为空则默认模板路径
     * @return
     * @throws UnsupportedEncodingException
     */
    public static InputStream getAsposeTempFileStream(HttpServletRequest request, String fileName, String directory) throws IOException {
        /** 获取模板文件位置**/
        String fileDirectory = directory;
        if (StringUtils.isEmpty(fileDirectory)) {
            fileDirectory = "templates/import/";//读取classes目录下文件
        }
        fileDirectory = fileDirectory.replaceAll("\\\\","/");
        fileDirectory = URLDecoder.decode(fileDirectory, "utf-8");
        if(fileDirectory.lastIndexOf("/") != fileDirectory.length() - 1){
            fileDirectory += "/";
        }

        InputStream inputStream = FileUtil.class.getClassLoader().getResourceAsStream(fileDirectory + fileName);

        return inputStream;
    }
最后修改:2024 年 09 月 19 日
如果觉得我的文章对你有用,请随意赞赏