java操作word进行页面替换(对页面进行拼接、删除、替换)

由于word是流格式(flow format),所以利用传统的api比如poi,无法直接操控页面。

经过俺的一番折腾,终于找到一个方法——利用ASPOSE.WORD这个接口。

然而,这个接口不开源,需要license。因此,建议有条件的还是支持正版。

如果需要该jar包请留下邮箱,随缘发送,某鱼也能获取。

1.导包。由于我是外部获取的第三方jar包,maven打包需要注意配置系统路径<systemPath>,记得帮第三方jar包放在工程的src/main/resources下。

        <dependency>
            <groupId>com.liam</groupId>
            <artifactId>aspose-word</artifactId>
            <!--依赖范围-->
            <scope>system</scope>
            <version>1.0-SNAPSHOT</version>
            <!--依赖所在位置-->
            <systemPath>${project.basedir}/src/main/resources/aspose-words-21.1-jdk17.jar</systemPath>
        </dependency>

 同时,springboot打包插件,也要注意配置:

<build>
        <!-- 打出来的jar包名 -->
        <finalName>Facepage-Tool</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.4.2</version>
                <configuration>
                    <!-- 主启动类全类名 -->
                    <mainClass>com.Liam.FxDemoMain</mainClass>
                    <!-- 这个配置很重要,是将外部依赖打包进来的,如果没有该配置,打出来的jar包是不包含外部jar包的 -->
                    <includeSystemScope>true</includeSystemScope>
                </configuration>
                <executions>
                    <execution>
                        <!--自定义 id -->
                        <id>repackage</id>
                        <!--插件目标 -->
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

 以下是主要代码,实现“封面多文件替换”:

思路:
1.将一个.docx的文件封面提取
2.对被需要替换的多个.docx文件的第一页删除
3.将两个文件拼接

#注意,Document类用的是aspose的,别用成w3c的或者poi的

package com.Liam;
//关键Jar包
import com.aspose.words.Document;
import com.aspose.words.ImportFormatMode;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;

//该代码主要实现封面的替换
//1.将一个.docx的文件封面提取
//2.对待替换的多个.docx文件的第一页删除
//3.将两个文件拼接
public class AsposeDemo {
    public static  HashSet<String> errorMsg = new HashSet<>();
    public static HashSet<String> infoMsg = new LinkedHashSet<>();
    private File faceFile;
    private List<File> tagetFiles=new ArrayList<>();

    public static void main(String[] args) throws Exception {
        String path = "C:\\Users\\kl\\Desktop\\20240412 wordTool\\srcMulti";
        new AsposeDemo().replaceFacePage(path);

    }

    public void replaceFacePage(String path) throws Exception {
        //collect files
        collectFiles(path);

        //replacing start
        replaceFaceHandle(path);
    }

    public void replaceFaceHandle(String path) throws Exception {
        infoMsg.add("start replacing...");
        for (int i=0;i<tagetFiles.size();i++){
            File targetFile = tagetFiles.get(i);
            //get Face
            Document facePageDoc = new Document(faceFile.getAbsolutePath());
            Document facePage = facePageDoc.extractPages(0, 1);
            int pageCount1 = facePage.getPageCount();

            //peel target face
            Document target = new Document(targetFile.getAbsolutePath());
            int pageCount = target.getPageCount();
            Document tailPages = target.extractPages(1,pageCount-1);

            //merge
            File outputDir = new File(path+"\\Output Files");
            if (!outputDir.exists())outputDir.mkdir();
            facePage.appendDocument(tailPages , ImportFormatMode.KEEP_DIFFERENT_STYLES);
            facePage.save(outputDir.getAbsolutePath()+"\\"+targetFile.getName());

            // msg
            infoMsg.add("meger success:"+targetFile.getName());

        }
    }

    private void collectFiles(String path) {
        File file = new File(path);
        for (File dir : file.listFiles()) {
            if(dir.isDirectory()){
                String dirName = dir.getName();
                infoMsg.add("start collecting...");
                for (File taget : dir.listFiles()) {
                    String filename = taget.getName();
                    if (filename.endsWith(".docx")||filename.endsWith(".doc")){
                        if ("Face-page file".equals(dirName)){
                            faceFile = taget;
                            infoMsg.add("Face page is:"+faceFile.getName());
                        }else if("Taget-page files".equals(dirName)){
                            tagetFiles.add(taget);
                            infoMsg.add("target file is:"+taget.getName());
                        }
                    }
                }
            }
        }
        infoMsg.add("collecting finished...\r\n");
    }
}

最终,还做了个基于javaFX的UI,需要的话可以去git上参考:github

  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
使用Java的POI库可以拼接Word文档。POI是Apache开发的用于操作Office文档的Java库,可以通过POI的XWPF模块来处理Word文档。 首先,我们需要创建一个XWPFDocument对象,该对象代表了一个空白的Word文档。然后我们可以像操作文本一样,通过调用XWPFDocument的方法来添加文本、表格、图片等内容到文档中。 例如,我们可以通过调用XWPFDocument的createParagraph()方法来创建一个段落,然后再调用段落对象的createRun()方法来创建一个文本运行,最后调用文本运行对象的setText()方法来设置文本内容。 如果想要添加表格,可以通过调用XWPFDocument的createTable()方法来创建一个表格对象,然后再通过调用表格对象的createRow()方法来创建行对象,并调用行对象的createCell()方法来创建单元格对象,最后通过调用单元格对象的setText()方法来设置单元格内容。 在将多个Word文档拼接为一个文件时,我们可以创建多个XWPFDocument对象,然后通过调用XWPFDocument的merge()方法来将它们合并成一个文档。合并后的文档可以保存到本地文件或者输出到流中。 最后,记得在使用完毕后关闭XWPFDocument对象,以释放资源。 总结来说,使用Java的POI库实现拼接Word文档的流程大致如上所述。通过调用XWPFDocument的各种方法来操作文档对象,最后合并文档并保存。这样就可以实现使用Java拼接Word文档的功能了。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值