Spring Boot集成Spire.doc实现对word的操作

news2024/9/20 19:09:09

1.什么是spire.doc?

Spire.Doc for Java 是一款专业的 Java Word 组件,开发人员使用它可以轻松地将 Word 文档创建、读取、编辑、转换和打印等功能集成到自己的 Java 应用程序中。作为一款完全独立的组件,Spire.Doc for Java 的运行环境无需安装 Microsoft Office。同时兼容大部分国产操作系统,能够在中标麒麟和中科方德等国产操作系统中正常运行。Spire.Doc for Java 支持 WPS 生成的 Word 格式文档(.wps, .wpt)。 Spire.Doc for Java 能执行多种 Word 文档处理任务,包括生成、读取、转换和打印 Word 文档,插入图片,添加页眉和页脚,创建表格,添加表单域和邮件合并域,添加书签,添加文本和图片水印,设置背景颜色和背景图片,添加脚注和尾注,添加超链接、数字签名,加密和解密 Word 文档,添加批注,添加形状等。

2.代码工程

实验目的

  • 实现创建word
  • word添加页
  • 读取word内容

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springboot-demo</artifactId>
        <groupId>com.et</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>spire-doc</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>e-iceblue</groupId>
            <artifactId>spire.doc</artifactId>
            <version>12.7.6</version>
        </dependency>
    </dependencies>
    <repositories>
        <repository>
            <id>com.e-iceblue</id>
            <name>e-iceblue</name>
            <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
        </repository>
    </repositories>
</project>

 

创建word

The following are the steps to create a simple Word document containing several paragraphs by using Spire.Doc for Java.

  • Create a Document object.
  • Add a section using Document.addSection() method.
  • Set the page margins using Section.getPageSetup().setMargins() method.
  • Add several paragraphs to the section using Section.addParagraph() method.
  • Add text to the paragraphs using Paragraph.appendText() method.
  • Create ParagraphStyle objects, and apply them to separate paragraphs using Paragraph.applyStyle() method.
  • Save the document to a Word file using Document.saveToFile() method.
package com.et.spire.doc;

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.HorizontalAlignment;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.ParagraphStyle;

import java.awt.*;

public class CreateWordDocument {

    public static void main(String[] args) {

        //Create a Document object
        Document doc = new Document();

        //Add a section
        Section section = doc.addSection();

        //Set the page margins
        section.getPageSetup().getMargins().setAll(40f);

        //Add a paragraph as title
        Paragraph titleParagraph = section.addParagraph();
        titleParagraph.appendText("Introduction of Spire.Doc for Java");

        //Add two paragraphs as body
        Paragraph bodyParagraph_1 = section.addParagraph();
        bodyParagraph_1.appendText("Spire.Doc for Java is a professional Word API that empowers Java applications to " +
                "create, convert, manipulate and print Word documents without dependency on Microsoft Word.");

        Paragraph bodyParagraph_2 = section.addParagraph();
        bodyParagraph_2.appendText("By using this multifunctional library, developers are able to process copious tasks " +
                "effortlessly, such as inserting image, hyperlink, digital signature, bookmark and watermark, setting " +
                "header and footer, creating table, setting background image, and adding footnote and endnote.");

        //Create and apply a style for title paragraph
        ParagraphStyle style1 = new ParagraphStyle(doc);
        style1.setName("titleStyle");
        style1.getCharacterFormat().setBold(true);;
        style1.getCharacterFormat().setTextColor(Color.BLUE);
        style1.getCharacterFormat().setFontName("Times New Roman");
        style1.getCharacterFormat().setFontSize(12f);
        doc.getStyles().add(style1);
        titleParagraph.applyStyle("titleStyle");

        //Create and apply a style for body paragraphs
        ParagraphStyle style2 = new ParagraphStyle(doc);
        style2.setName("paraStyle");
        style2.getCharacterFormat().setFontName("Times New Roman");
        style2.getCharacterFormat().setFontSize(12);
        doc.getStyles().add(style2);
        bodyParagraph_1.applyStyle("paraStyle");
        bodyParagraph_2.applyStyle("paraStyle");

        //Set the horizontal alignment of paragraphs
        titleParagraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
        bodyParagraph_1.getFormat().setHorizontalAlignment(HorizontalAlignment.Justify);
        bodyParagraph_2.getFormat().setHorizontalAlignment(HorizontalAlignment.Justify);

        //Set the first line indent
        bodyParagraph_1.getFormat().setFirstLineIndent(30) ;
        bodyParagraph_2.getFormat().setFirstLineIndent(30);

        //Set the after spacing
        titleParagraph.getFormat().setAfterSpacing(10);
        bodyParagraph_1.getFormat().setAfterSpacing(10);

        //Save to file
        doc.saveToFile("/Users/liuhaihua/tmp/WordDocument.docx", FileFormat.Docx_2013);
        doc.close();
    }
}

word添加新页

The steps to add a new page at the end of a Word document include locating the last section, and then inserting a page break at the end of that section's last paragraph. This way ensures that any content added subsequently will start displaying on a new page, maintaining the clarity and coherence of the document structure. The detailed steps are as follows:

  • Create a Document object.
  • Load a Word document using the Document.loadFromFile() method.
  • Get the body of the last section of the document using Document.getLastSection().getBody().
  • Add a page break by calling Paragraph.appendBreak(BreakType.Page_Break) method.
  • Create a new paragraph style ParagraphStyle object.
  • Add the new paragraph style to the document's style collection using Document.getStyles().add(paragraphStyle) method.
  • Create a new paragraph Paragraph object and set the text content.
  • Apply the previously created paragraph style to the new paragraph using Paragraph.applyStyle(paragraphStyle.getName()) method.
  • Add the new paragraph to the document using Body.getChildObjects().add(paragraph) method.
  • Save the resulting document using the Document.saveToFile() method.
package com.et.spire.doc;

import com.spire.doc.*;
import com.spire.doc.documents.*;

public class AddOnePage {
    public static void main(String[] args) {
        // Create a new document object
        Document document = new Document();

        // Load a sample document from a file
        document.loadFromFile("/Users/liuhaihua/tmp/WordDocument.docx");

        // Get the body of the last section of the document
        Body body = document.getLastSection().getBody();

        // Insert a page break after the last paragraph in the body
        body.getLastParagraph().appendBreak(BreakType.Page_Break);

        // Create a new paragraph style
        ParagraphStyle paragraphStyle = new ParagraphStyle(document);
        paragraphStyle.setName("CustomParagraphStyle1");
        paragraphStyle.getParagraphFormat().setLineSpacing(12);
        paragraphStyle.getParagraphFormat().setAfterSpacing(8);
        paragraphStyle.getCharacterFormat().setFontName("Microsoft YaHei");
        paragraphStyle.getCharacterFormat().setFontSize(12);

        // Add the paragraph style to the document's style collection
        document.getStyles().add(paragraphStyle);

        // Create a new paragraph and set the text content
        Paragraph paragraph = new Paragraph(document);
        paragraph.appendText("Thank you for using our Spire.Doc for Java product. The trial version will add a red watermark to the generated result document and only supports converting the first 10 pages to other formats. Upon purchasing and applying a license, these watermarks will be removed, and the functionality restrictions will be lifted.");

        // Apply the paragraph style
        paragraph.applyStyle(paragraphStyle.getName());

        // Add the paragraph to the body's content collection
        body.getChildObjects().add(paragraph);

        // Create another new paragraph and set the text content
        paragraph = new Paragraph(document);
        paragraph.appendText("To fully experience our product, we provide a one-month temporary license for each of our customers for free. Please send an email to sales@e-iceblue.com, and we will send the license to you within one working day.");

        // Apply the paragraph style
        paragraph.applyStyle(paragraphStyle.getName());

        // Add the paragraph to the body's content collection
        body.getChildObjects().add(paragraph);

        // Save the document to a specified path
        document.saveToFile("/Users/liuhaihua/tmp/Add a Page.docx", FileFormat.Docx);

        // Close the document
        document.close();

        // Dispose of the document object's resources
        document.dispose();
    }
}

读取word内容

Using the FixedLayoutDocument class and FixedLayoutPage class makes it easy to extract content from a specified page. To facilitate viewing the extracted content, the following example code saves the extracted content to a new Word document. The detailed steps are as follows:

  • Create a Document object.
  • Load a Word document using the Document.loadFromFile() method.
  • Create a FixedLayoutDocument object.
  • Obtain a FixedLayoutPage object for a page in the document.
  • Use the FixedLayoutPage.getSection() method to get the section where the page is located.
  • Get the index position of the first paragraph on the page within the section.
  • Get the index position of the last paragraph on the page within the section.
  • Create another Document object.
  • Add a new section using Document.addSection().
  • Clone the properties of the original section to the new section using Section.cloneSectionPropertiesTo(newSection) method.
  • Copy the content of the page from the original document to the new document.
  • Save the resulting document using the Document.saveToFile() method.
package com.et.spire.doc;

import com.spire.doc.*;
import com.spire.doc.pages.*;
import com.spire.doc.documents.*;

public class ReadOnePage {
    public static void main(String[] args) {
        // Create a new document object
        Document document = new Document();

        // Load document content from the specified file
        document.loadFromFile("/Users/liuhaihua/tmp/WordDocument.docx");

        // Create a fixed layout document object
        FixedLayoutDocument layoutDoc = new FixedLayoutDocument(document);

        // Get the first page
        FixedLayoutPage page = layoutDoc.getPages().get(0);

        // Get the section where the page is located
        Section section = page.getSection();

        // Get the first paragraph of the page
        Paragraph paragraphStart = page.getColumns().get(0).getLines().getFirst().getParagraph();
        int startIndex = 0;
        if (paragraphStart != null) {
            // Get the index of the paragraph in the section
            startIndex = section.getBody().getChildObjects().indexOf(paragraphStart);
        }

        // Get the last paragraph of the page
        Paragraph paragraphEnd = page.getColumns().get(0).getLines().getLast().getParagraph();

        int endIndex = 0;
        if (paragraphEnd != null) {
            // Get the index of the paragraph in the section
            endIndex = section.getBody().getChildObjects().indexOf(paragraphEnd);
        }

        // Create a new document object
        Document newdoc = new Document();

        // Add a new section
        Section newSection = newdoc.addSection();

        // Clone the properties of the original section to the new section
        section.cloneSectionPropertiesTo(newSection);

        // Copy the content of the original document's page to the new document
        for (int i = startIndex; i <=endIndex; i++)
        {
            newSection.getBody().getChildObjects().add(section.getBody().getChildObjects().get(i).deepClone());
        }

        // Save the new document to the specified file
        newdoc.saveToFile("/Users/liuhaihua/tmp/Content of One Page.docx", FileFormat.Docx);

        // Close and release the new document
        newdoc.close();
        newdoc.dispose();

        // Close and release the original document
        document.close();
        document.dispose();
    }
}

以上只是一些关键代码,所有代码请参见下面代码仓库

代码仓库

  • https://github.com/Harries/springboot-demo(spire-doc)

3.测试

运行上述java类的main方法,会生成3个文件在对应的目录下

11

4.引用

  • Java: Create a Word Document
  • Spring Boot集成Spire.doc实现对word的操作 | Harries Blog™

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1943822.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

JMeter:BeanShell到JSR223迁移中的注意事项

前言 在之前的文章JMeter&#xff1a;BeanShell向JSR223迁移过程遭遇的java标准库不可用问题-如何切换JDK版本中引用了一段使用BeanShell对入参进行加密的脚本&#xff0c;迁移到JSR223&#xff0c;虽然更换JDK后编译通过&#xff0c;看似也可以执行了&#xff0c;但是其实那段…

AI绘画入门实践 | Midjourney:画面权重控制

在 Midjourney 中&#xff0c;使用两个连续的英文冒号::来进行分割与权重控制。 作为分隔符使用 在提示词中添加双冒号::表示让 MJ 将部分提示词单独考虑 2d illustration, french fries, hot dog --v 6 2d illustration, french fries, hot:: dog --v 6 作为权重控制使用 在双…

google 浏览器插件开发简单学习案例:TodoList;打包成crx离线包

参考&#xff1a; google插件支持&#xff1a; https://blog.csdn.net/weixin_42357472/article/details/140412993 这里是把前面做的TodoList做成google插件&#xff0c;具体网页可以参考下面链接 TodoList网页&#xff1a; https://blog.csdn.net/weixin_42357472/article/de…

docker基础镜像

一、配置 docker 本地源 [docker-ce-stable] nameDocker CE Stable baseurlhttp://10.35.186.181/docker-ce-stable/ enabled1 gpgcheck0 配置阿里云Docker Yum源 yum install -y yum-utils device-mapper-persistent-data lvm2 git yum-config-manager --add-repo http://mirr…

简单修改,让UE4/5着色器编译速度变快

简单修改&#xff0c;让UE4/5着色器编译速度变快 目录 简单修改&#xff0c;让UE4/5着色器编译速度变快 一、问题描述 二、解决方法 &#xff08;一&#xff09;硬件升级 &#xff08;二&#xff09;调整相关设置和提升优先级 1.调整相关设置 &#xff08;1&#xff09…

【Android】碎片的初识

之前我们学习的是一个活动作为一个页面&#xff0c;有了平板之后&#xff0c;页面如果像手机一样设计就会浪费很多的空间&#xff0c;会有很多的空白区域&#xff0c;为了使屏幕充分利用&#xff0c;引入了碎片这样一个概念。 碎片&#xff08;Fragment&#xff09;&#xff1…

pikachu之sql lnjet 字符型注入

先测试一下闭合 注释符号&#xff1a;-- 注释符号可以忽略其后的内容&#xff0c;使得后续的原始查询内容不会影响我们注入的SQL代码。 条件测试&#xff1a;通过and 11和and 12分别测试真假条件&#xff0c;可以判断输入是否成功闭合&#xff0c;并且可以检测注入是否成功。 …

构造+位运算,CF 1901C - Add, Divide and Floor

一、题目 1、题目描述 2、输入输出 2.1输入 2.2输出 3、原题链接 1901C - Add, Divide and Floor 二、解题报告 1、思路分析 我们假设将原数组排序&#xff0c;那么每次操作不会改变数组单调性 当 最大值 调整等于 最小值时 所有数都相等&#xff0c;因为单调性不变&…

VS2022下安装和配置OpenCV环境参数+QT开发环境搭建(1)

1.工具准备 VS2022,OpenCV4.5.5版本&#xff0c;QT5.12.12 VisualStudio最新版直接官网下载&#xff0c;根据需要进行下载&#xff0c;我下载的免费社区版本。日常开发完全够用。 qt官网下载5.12版本。 OpenCVReleases - OpenCV 选择Windows版本下载并解压到本地磁盘&#xff0…

操作系统——笔记(1)

操作系统是管理计算机硬件资源&#xff0c;控制其他程序运行并为用户提供交互操作界面的系统软件的集合&#xff0c;控制和管理着整个计算机系统的硬件和软件资源&#xff0c;是最基本的系统软件。 常见的操作系统&#xff1a;ios、windows、Linux。 计算机系统的结构层次&am…

【SpringCloud】微服务远程调用OpenFeign

工作原理流程图 上代码 common中添加依赖&#xff1a; <dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <dependency><groupId>org.spri…

Android APP 音视频(01)MediaCodec解码H264码流

说明&#xff1a; 此MediaCodec解码H264实操主要针对Android12.0系统。通过读取sd卡上的H264码流Me获取视频数据&#xff0c;将数据通过mediacodec解码输出到surfaceview上。 1 H264码流和MediaCodec解码简介 1.1 H264码流简介 H.264&#xff0c;也被称为MPEG-4 AVC&#xff…

用51单片机或者stm32能否开发机器人呢?

在开始前刚好我有一些资料&#xff0c;是我根据网友给的问题精心整理了一份「单片机的资料从专业入门到高级教程」&#xff0c; 点个关注在评论区回复“888”之后私信回复“888”&#xff0c;全部无偿共享给大家&#xff01;&#xff01;&#xff01;能的。但是由于单片机和st…

记录安装android studio踩的坑 win7系统

最近在一台新电脑上安装android studio,报了很多错误&#xff0c;也是费了大劲才解决&#xff0c;发出来大家一起避免一些问题&#xff0c;找到解决方法。 安装时一定要先安装jdk&#xff0c;cmd命令行用java -version查当前的版本&#xff0c;没有的话&#xff0c;先安装jdk,g…

ARP欺骗——华为ensp

首先&#xff0c;搭建好网络拓扑。网络设备包含客户端Client1和服务端Server1&#xff0c;交换机 以及 云。 图中的 Client和Server 配置IP地址&#xff0c;要和 vm8 在相同的网段。故设置客户端ip为192.168.11.10 &#xff0c;服务端ip为&#xff1a;192.168.11.20&#xff0…

MySQL补充性文件

数据库专属单词 authentication #身份验证 delimiter #分隔符 character #字符集 collate #整理。 指定字符集的排序规则 unicode #统一码 flush #刷新 privileges #特权 string #串 set #设置 use #使用 zerofill #修饰符。0可以填补输出的值 unsigned #修饰符。无符…

STM32--HAL库--定时器篇

一&#xff1a;如何配置定时器 打开对应工程串口配置好的工程&#xff08;上一篇博客&#xff09;做如下配置&#xff1a; 定时器的中断溢出时间计算公式是&#xff1a; 由图得T100*1000/100MHz 注&#xff1a;100MHz100000000 所以溢出时间等于1ms 关于上图4的自动重装…

Robot Operating System——初探动态配置Parameters

大纲 同步模式Node内使用declare_parameter方法声明Parameters创建Parameter同步访问客户端跨Node修改Parameters跨Node查询Parameters完整代码运行结果 异步模式创建Node&#xff0c;设置Parameters创建Parameter异步访问客户端异步设置&#xff0c;同步等待异步查询&#xff…

VMware三种网络模式---巨细

文章目录 目录 ‘一.网络模式概述 二.桥接模式 二.NAT模式 三.仅主机模式 四.案例演示 防火墙配置&#xff1a; 虚拟电脑配置 前言 本文主要介绍VMware的三种网络模式 ‘一.网络模式概述 VMware中分为三种网络模式&#xff1a; 桥接模式&#xff1a;默认与宿主机VMnet0绑…

CSP-J模拟赛day1——解析+答案

题目传送门 yjq的吉祥数 题解 送分题&#xff0c;暴力枚举即可 Code #include<bits/stdc.h> using namespace std;int l,r; int num1,tmp0,q[10000],a[10000]; int k (int x){for (int j1;j<tmp;j){if (xq[j])return 0;}return 1; } int main(){while (num<100…