• Java 加载、操作和保存WPS文字文档


    本文通过Java程序代码来展示如何来加载、操作及保存WPS格式的文字文档。

    一、基本步骤加载时,通过流加载WPS文字文档,完成相关文字操作后,再将结果文档保存到流,将流写入WPS文档,关闭流。

    二、程序环境

    这里使用的是Word类库工具Free Spire.Doc for Java,可参考如下步骤手动将D:包JAVA DocSpire.Doc-FE_3.9.0libSpire.Doc.jar文件夹(该jar包需要事前下载到本地,然后解压)路径下的jar文件导入Java程序:

    完成导入,如下导入结果:

    三、Java代码

    这里对WPS文字文档的操作进行了段落背景设置、文字高亮、加粗、添加图片等简单操作。

    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如何操作Word文档的更多方法,可前往:https://www.cnblogs.com/Yesi/category/1460010.html 

    —End—

  • 相关阅读:
    nginx学习(十):nginx搭建2台tomcat集群
    IOT设备SmartConfig实现
    AIDL原理分析
    MySQL升级-CentOS6.8
    CentOS更新yum源
    .net core微服务通信——gRPC(下)
    .net core微服务通信——gRPC(上)
    实时web应用方案——SignalR(.net core)
    redis常见Bug及雪崩、穿透、击穿解析
    asp.net core托管到windows服务
  • 原文地址:https://www.cnblogs.com/Yesi/p/15061947.html
Copyright © 2020-2023  润新知