Java 读取 wps 文档

Java 读取 wps 文档可以通过 成都冰蓝科技有限公司 开发的 类库来实现

Word 类库工具

官网地址: Free Spire.Doc for JAVA | 下载

通过 Maven 仓库安装 :

通过 Maven 仓库安装 :

在 pom.xml 文件中配置 Maven 仓库路径。

<repositories>
        <repository>
            <id>com.e-iceblue</id>
            <name>e-iceblue</name>
            <url>https://repo.e-iceblue.cn/repository/maven-public/</url>
        </repository>
</repositories>

pom依赖如下:
<dependency>
    <groupId>e-iceblue</groupId>
    <artifactId>spire.doc.free</artifactId>
    <version>5.3.2</version>
</dependency>

Demo 样例

import com.spire.doc.*;
import com.spire.doc.documents.HorizontalAlignment;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.TextSelection;
import com.spire.doc.documents.TextWrappingStyle;
import com.spire.doc.fields.DocPicture;

import java.awt.*;
import java.io.*;

public class OperateWPS_Word {
 public static void main(String[] args)throws IOException {
        //通过流加载WPS文字文档
        FileInputStream inputStream = new FileInputStream(new File("test.wps"));
        Document document = new Document();
        document.loadFromStream(inputStream, FileFormat.Doc);

        //查找所有“北京冬奥会”文本
        TextSelection[] textSelections = document.findAllString("北京冬奥会", false, false);
        //设置文本高亮色、加粗
        for (TextSelection selection : textSelections)
        {
            selection.getAsOneRange().getCharacterFormat().setHighlightColor(Color.YELLOW);
            selection.getAsOneRange().getCharacterFormat().setBold(true);
        }

        //获取文档的第一个节
        Section section = document.getSections().get(0);

        //获取第2段,设置段落背景色
        Paragraph paragraph1 = section.getParagraphs().get(1);
        paragraph1.getFormat().setBackColor(new Color(176,224,230));
        paragraph1.getStyle().getParagraphFormat().setHorizontalAlignment(HorizontalAlignment.Center);

        //获取第3段,添加图片到段落
        Paragraph paragraph2 = section.getParagraphs().get(2);
        DocPicture picture = paragraph2.appendPicture("img.png");
        picture.setWidth(200f);
        picture.setHeight(250f);
        picture.setTextWrappingStyle(TextWrappingStyle.Through);

        //将结果文档保存到流
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        document.saveToStream(bos, FileFormat.Doc);
        //将流写入WPS文档
        FileOutputStream fos = new FileOutputStream("Output.wps");
        fos.write(bos.toByteArray());
        //关闭流
        bos.close();
        fos.close();
    }
}

测试前的 WPS 文字文档:

完成操作后的 WPS 文字文档:

  • Java

    Java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由 Sun Microsystems 公司于 1995 年 5 月推出的。Java 技术具有卓越的通用性、高效性、平台移植性和安全性。

    3206 引用 • 8217 回帖
  • WPS
    3 引用 • 21 回帖

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...