记录一次poi-tl使用,把多个word合成一个word

官方地址

  • maven
 			<poi-tl-version>1.12.1</poi-tl-version>
 			
            <dependency>
                <groupId>com.deepoove</groupId>
                <artifactId>poi-tl</artifactId>
                <version>${poi-tl-version}</version>
            </dependency>
  • 把多个word合成一个word核心代码
        NiceXWPFDocument document = docList.get(0);
        docList.remove(document);
        NiceXWPFDocument combine = document.merge(docList, document.getXWPFDocument().createParagraph().createRun());
        docList.forEach(doc-> {
            try {
                doc.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
        
        response.setContentType("application/octet-stream");
        String format = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        response.setHeader("Content-disposition","attachment;filename=\""+"apiDocument" + format + ".docx"+"\"");

        OutputStream out = response.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(out);
        combine.write(bos);
        bos.flush();
        out.flush();
        PoitlIOUtils.closeQuietlyMulti(combine, bos, out);
  • 业务代码
    public Integer downloadDocument(DownloadDocumentDTO parameter, HttpServletResponse response) throws Exception {
        long tenantId = parameter.getTenantId();
        String parameterApiNoList = parameter.getApiNoList();
        String[] split = parameterApiNoList.split(",");
        List<String> strings = Arrays.asList(split);
        List<Long> apiNoList = strings.stream().map(Long::valueOf).collect(Collectors.toList());
        User user = UserContextHolder.getContext().getUser();
        // 下载人
        String accountName = user.getAccountName();
        if (StringUtils.isEmpty(accountName)) {
            accountName = user.getDisplayName();
        }
        List<NiceXWPFDocument> docList = new ArrayList();
        // 添加说明文档
        ClassPathResource classPathResource = new ClassPathResource("/java_sdk/xx/xx/xxx-zh.docx");
        InputStream resourceInputStream = classPathResource.getInputStream();
        XWPFTemplate xwpfTemplate = XWPFTemplate.compile(resourceInputStream);
        docList.add(xwpfTemplate.getXWPFDocument());
        // 公共请求参数
        List<Parameter> commonRequestList = getCommonRequestList();
        // 查询API信息
        List<DownloadDocumentBO> downloadDocumentBOList = dataApiProMapper.downloadList(apiNoList, tenantId);
        List<Integer> idList = downloadDocumentBOList.stream().map(DownloadDocumentBO::getId).collect(Collectors.toList());
        int count = 0;
        for (DownloadDocumentBO apiInfo : downloadDocumentBOList) {
            apiInfo.setModelType(DataLogicUnitConstants.ModelType.get(Integer.valueOf(apiInfo.getModelTypeValue())).getDesc());
            apiInfo.setCallType(DataApiConstants.RequestMethod.getDescByCode(apiInfo.getCallTypeValue()));
            String example = apiInfo.getExample();
            // 设置网关host
            apiInfo.setHost(getHost());
            // 返回示例
            String jsonString = "";
            if (!StringUtils.isEmpty(example)) {
                jsonString = JSON.toJSONString(JSONObject.parseObject(example), SerializerFeature.PrettyFormat);
            }
            // 请求参数
            List<Parameter> requestList = getParameterList(idList, DataApiParamConstants.Type.REQUEST);
            // 返回参数
            List<Parameter> responseList = getParameterList(idList, DataApiParamConstants.Type.RETURN);
            // 配置类
            ConfigureBuilder builder = Configure.builder();
            LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
            builder.bind("commonRequestList",policy)
                    .bind("requestList",policy)
                    .bind("responseList",policy);

            ClassPathResource resource = new ClassPathResource("/download/template/apiDocument.docx");
            InputStream inputStream = resource.getInputStream();
            XWPFTemplate template = XWPFTemplate.compile(inputStream,builder.build());
            count = count + 1;
            String finalAccountName = accountName;
            String finalJsonString = jsonString;
            int finalCount = count;
            template.render(
                    new HashMap<String,Object>(){{
                        put("title", finalCount + "." +  apiInfo.getApiName());
                        put("downloader", finalAccountName);
                        put("downloadTime", DateTime.now());
                        put("apiInfo",apiInfo);
                        put("commonRequestList",commonRequestList);
                        put("requestList",requestList);
                        put("responseList",responseList);
                        put("responseExample", finalJsonString);
                    }}
            );
            docList.add(template.getXWPFDocument());
        };

        NiceXWPFDocument document = docList.get(0);
        docList.remove(document);
        NiceXWPFDocument combine = document.merge(docList, document.getXWPFDocument().createParagraph().createRun());
        docList.forEach(doc-> {
            try {
                doc.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
        response.setContentType("application/octet-stream");
        String format = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        response.setHeader("Content-disposition","attachment;filename=\""+"apiDocument" + format + ".docx"+"\"");

        OutputStream out = response.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(out);
        combine.write(bos);
        bos.flush();
        out.flush();
        PoitlIOUtils.closeQuietlyMulti(combine, bos, out);

//        combine.write(new FileOutputStream(new File("/Users/cengwei/Downloads/test5.docx")));
//        combine.close();
//        document.close();
        return 1;
    }

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
合并多个 Word 文件,你可以使用 poi-tl 提供的方法来实现。以下是一个简单的示例: ```java import org.apache.poi.xwpf.usermodel.*; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import java.io.*; import java.util.List; public class WordMergeExample { public static void main(String[] args) { try { // 创建一个新的空白文档 XWPFDocument mergedDocument = new XWPFDocument(); // 读取第一个 Word 文件 XWPFDocument doc1 = new XWPFDocument(new FileInputStream("file1.docx")); // 复制第一个 Word 文件的内容合并文档中 copyContent(doc1, mergedDocument); // 读取第二个 Word 文件 XWPFDocument doc2 = new XWPFDocument(new FileInputStream("file2.docx")); // 复制第二个 Word 文件的内容合并文档中 copyContent(doc2, mergedDocument); // 保存合并后的文档 FileOutputStream outputStream = new FileOutputStream("merged.docx"); mergedDocument.write(outputStream); outputStream.close(); System.out.println("合并完成!"); } catch (IOException | InvalidFormatException e) { e.printStackTrace(); } } private static void copyContent(XWPFDocument sourceDoc, XWPFDocument targetDoc) { List<XWPFParagraph> paragraphs = sourceDoc.getParagraphs(); for (XWPFParagraph paragraph : paragraphs) { targetDoc.createParagraph().createRun().setText(paragraph.getText()); } } } ``` 在上面的示例中,我们首先创建了一个空白的目标文档 `mergedDocument`,然后使用 `copyContent` 方法将每个源文档的内容复制到目标文档中。最后,将目标文档保存为一个新的合并后的 Word 文件。 你需要将示例中的 `"file1.docx"` 和 `"file2.docx"` 替换为你要合并的实际文件路径。根据你的需求,你可以调整代码来处理更多的 Word 文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值