Java将doc文件转成docx文件,并将两个文件合并在一起

private String downloadDailyInspectionDocByTemplate(List<WorkOrderWorkloadTableDownloadTemplate> itemList, String fileName) {
    //日常巡检登记表2024-11.14-11.20
    //20241212_20241218工作量
    String date = fileName.substring(0, fileName.indexOf("工"));
    String startYear = date.substring(0, 4);
    String startMonth = date.substring(4, 6);
    String startDay = date.substring(6, 8);

    String endYear = date.substring(9, 13);
    String endMonth = date.substring(13, 15);
    String endDay = date.substring(15, 17);

    String docName = "日常巡检登记表" + startYear + "-" + startMonth + "." + startDay + "-" + endMonth + "." + endDay + ".doc";
    String docPath = System.getProperty("user.dir") + File.separator;
    File docFile = new File(docPath + docName);
    String templateFilePath = this.getClass().getClassLoader().getResource("").getPath() + "template/DailyInspectionTemplate.ftl";
    String path = templateFilePath.substring(0, templateFilePath.lastIndexOf("/"));
    String templateName = templateFilePath.substring(templateFilePath.lastIndexOf("/") + 1);
    List<File> fileArrayList = new ArrayList<>();
    try (FileOutputStream out = new FileOutputStream(docFile);
         Writer writer = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8))) {
        Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        configuration.setDefaultEncoding("utf-8");
        //除了ClassForTemplateLoading外,另一种模板加载方式DirectoryForTemplateLoading,也可用
        configuration.setDirectoryForTemplateLoading(new File(path));
        //加载模板
        Template template = configuration.getTemplate(templateName);
        //渲染模板
        if (itemList.isEmpty()) {
            template.process(new WorkOrderWorkloadTableDownloadTemplate(), writer);
            List<InputStream> inputStreams = getInputStreams(docFile, docPath, docName, fileArrayList);
            wordUtil.wordMergeRetPath(inputStreams, docPath, docName);
            fileArrayList.add(docFile);
        } else {
            List<File> fileList = new ArrayList<>();
            List<File> fileLisTempList = new ArrayList<>();
            Map<String, List<WorkOrderWorkloadTableDownloadTemplate>> collect = itemList.stream()
                    .collect(Collectors.groupingBy(WorkOrderWorkloadTableDownloadTemplate::getDate));
            collect.forEach((key, value) -> {
                //字段拼接
                StringBuilder sb = new StringBuilder();
                for (WorkOrderWorkloadTableDownloadTemplate workOrderWorkloadTableDownloadTemplate : value) {
                    String installationAddress = workOrderWorkloadTableDownloadTemplate.getInstallationAddress();
                    String problemDescription = workOrderWorkloadTableDownloadTemplate.getProblemDescription();
                    String repairReason = (StrUtil.isNotEmpty(installationAddress) ? installationAddress + "," : "")
                            + (StrUtil.isNotEmpty(problemDescription) ? problemDescription : "") + "已修复。<br />";
                    sb.append(repairReason);
                }
                String name = "日常巡检登记表" + key + ".doc";
                File file = new File(docPath + name);
                try (FileOutputStream out1 = new FileOutputStream(file);
                     Writer writer1 = new BufferedWriter(new OutputStreamWriter(out1, StandardCharsets.UTF_8));
                ) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("date", startYear + "." + key.replace("-", "."));
                    map.put("repairReason", sb.toString());
                    template.process(map, writer1);
                    fileLisTempList.add(file);

                    FileInputStream fis = new FileInputStream(file);
                    Document document = new Document(fis);
                    File file1 = new File(docPath + name.substring(0, name.indexOf(".")) + ".docx");
                    FileOutputStream fos = new FileOutputStream(file1);
                    document.save(fos, SaveFormat.DOCX);
                    fileList.add(file1);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

            });
            List<InputStream> inputStreams = new ArrayList<>();
            fileList.sort(Comparator.comparing(File::getName));
            for (File fileOne : fileList) {
                FileInputStream fileInputStream = new FileInputStream(fileOne);
                inputStreams.add(fileInputStream);
            }
            wordUtil.wordMergeRetPath(inputStreams, docPath, docName);
            fileArrayList.addAll(fileLisTempList);
            fileArrayList.addAll(fileList);
        }
        writer.flush();
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        ScheduledExecutorService scheduledExecutorService = ThreadPoolUtil.instance.getScheduledExecutorService();
        // 获取延迟线程池
        fileArrayList.forEach(file -> scheduledExecutorService.schedule(file::delete, 10, SECONDS));
    }
    return docFile.getPath();
}







public volatile int bookMarkCount = 0;

public String path = null;


/**
 * 根据传入文件集合、地址、文件名称生成文件,返回文件全路径
 *
 * @param inputStreams
 * @param path
 * @param fileName
 * @throws IOException
 * @throws InvalidFormatException
 * @throws XmlException
 */
public void wordMergeRetPath(List<InputStream> inputStreams, String path, String fileName) throws IOException, InvalidFormatException, XmlException, org.apache.poi.openxml4j.exceptions.InvalidFormatException {
    if (StrUtil.isEmpty(path)) {
        path = this.path;
    }
    if (StrUtil.isEmpty(fileName)) {
        fileName = System.currentTimeMillis() + String.valueOf((int) Math.random() * 1000) + ".docx";
    }
    String fileFullPath = path + fileName;
    ByteArrayInputStream byteArrayInputStream = wordMerge(inputStreams);
    OutputStream outputStream = Files.newOutputStream(new File(fileFullPath).toPath());
    int count = byteArrayInputStream.available();
    byte[] bytes = new byte[count];
    byteArrayInputStream.read(bytes, 0, count);
    outputStream.write(bytes);
    outputStream.close();
}


/**
 * word合并,返回byte[] 字节流
 *
 * @param inputStreams
 * @return
 * @throws IOException
 * @throws XmlException
 */
protected ByteArrayInputStream wordMerge(List<InputStream> inputStreams) throws IOException, XmlException, org.apache.poi.openxml4j.exceptions.InvalidFormatException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    Map<BigInteger, BigInteger> mapTemp = new HashMap<>();
    XWPFDocument xwpfDoc = null;
    //循环处理流文件开始
    for (InputStream inputStream : inputStreams) {
        XWPFDocument xwpfDocumentOne = new XWPFDocument(inputStream);
        List<XWPFParagraph> paragra = xwpfDocumentOne.getParagraphs();
        for (XWPFParagraph xwpfParagraph : paragra) {
            List<CTBookmark> bookMarkStart = xwpfParagraph.getCTP().getBookmarkStartList();
            List<CTMarkupRange> bookMargEnd = xwpfParagraph.getCTP().getBookmarkEndList();
            for (CTBookmark ctBookmark : bookMarkStart) {
                BigInteger id = ctBookmark.getId();
                ctBookmark.setId(BigInteger.valueOf(bookMarkCount));
                mapTemp.put(id, BigInteger.valueOf(bookMarkCount));
                bookMarkCount++;
            }
            //循环技术书签
            for (CTMarkupRange ctMarkupRange : bookMargEnd) {
                ctMarkupRange.setId(mapTemp.get(ctMarkupRange.getId()));
            }
        }
        //初次进入直接复制
        if (xwpfDoc == null) {
            xwpfDoc = xwpfDocumentOne;
        } else {
            CTBody src1Body = xwpfDoc.getDocument().getBody();
            CTBody src2Body = xwpfDocumentOne.getDocument().getBody();

            XmlOptions optionsOuter = new XmlOptions();
            optionsOuter.setSaveOuter();
            String appendString = src2Body.xmlText(optionsOuter);
            String srcString = src1Body.xmlText();
            String prefix = srcString.substring(0, srcString.indexOf(">") + 1);
            String mainPart = srcString.substring(srcString.indexOf(">") + 1, srcString.lastIndexOf("<"));
            String sufix = srcString.substring(srcString.lastIndexOf("<"));
            String addPart = appendString.substring(appendString.indexOf(">") + 1, appendString.lastIndexOf("<"));

            //将两个文档的xml内容进行拼接
            CTBody makeBody = CTBody.Factory.parse(prefix + mainPart + "<w:p><w:r><w:br w:type=\"page\"/></w:r></w:p>。" + addPart + sufix);
            src1Body.set(makeBody);
        }
    }
    xwpfDoc.write(byteArrayOutputStream);
    xwpfDoc.close();
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
    return byteArrayInputStream;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值