当前位置: 首页 > news >正文

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

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 objectDocument doc = new Document();//Add a sectionSection section = doc.addSection();//Set the page marginssection.getPageSetup().getMargins().setAll(40f);//Add a paragraph as titleParagraph titleParagraph = section.addParagraph();titleParagraph.appendText("Introduction of Spire.Doc for Java");//Add two paragraphs as bodyParagraph 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 paragraphParagraphStyle 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 paragraphsParagraphStyle 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 paragraphstitleParagraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);bodyParagraph_1.getFormat().setHorizontalAlignment(HorizontalAlignment.Justify);bodyParagraph_2.getFormat().setHorizontalAlignment(HorizontalAlignment.Justify);//Set the first line indentbodyParagraph_1.getFormat().setFirstLineIndent(30) ;bodyParagraph_2.getFormat().setFirstLineIndent(30);//Set the after spacingtitleParagraph.getFormat().setAfterSpacing(10);bodyParagraph_1.getFormat().setAfterSpacing(10);//Save to filedoc.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 objectDocument document = new Document();// Load a sample document from a filedocument.loadFromFile("/Users/liuhaihua/tmp/WordDocument.docx");// Get the body of the last section of the documentBody body = document.getLastSection().getBody();// Insert a page break after the last paragraph in the bodybody.getLastParagraph().appendBreak(BreakType.Page_Break);// Create a new paragraph styleParagraphStyle 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 collectiondocument.getStyles().add(paragraphStyle);// Create a new paragraph and set the text contentParagraph 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 styleparagraph.applyStyle(paragraphStyle.getName());// Add the paragraph to the body's content collectionbody.getChildObjects().add(paragraph);// Create another new paragraph and set the text contentparagraph = 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 styleparagraph.applyStyle(paragraphStyle.getName());// Add the paragraph to the body's content collectionbody.getChildObjects().add(paragraph);// Save the document to a specified pathdocument.saveToFile("/Users/liuhaihua/tmp/Add a Page.docx", FileFormat.Docx);// Close the documentdocument.close();// Dispose of the document object's resourcesdocument.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 objectDocument document = new Document();// Load document content from the specified filedocument.loadFromFile("/Users/liuhaihua/tmp/WordDocument.docx");// Create a fixed layout document objectFixedLayoutDocument layoutDoc = new FixedLayoutDocument(document);// Get the first pageFixedLayoutPage page = layoutDoc.getPages().get(0);// Get the section where the page is locatedSection section = page.getSection();// Get the first paragraph of the pageParagraph paragraphStart = page.getColumns().get(0).getLines().getFirst().getParagraph();int startIndex = 0;if (paragraphStart != null) {// Get the index of the paragraph in the sectionstartIndex = section.getBody().getChildObjects().indexOf(paragraphStart);}// Get the last paragraph of the pageParagraph paragraphEnd = page.getColumns().get(0).getLines().getLast().getParagraph();int endIndex = 0;if (paragraphEnd != null) {// Get the index of the paragraph in the sectionendIndex = section.getBody().getChildObjects().indexOf(paragraphEnd);}// Create a new document objectDocument newdoc = new Document();// Add a new sectionSection newSection = newdoc.addSection();// Clone the properties of the original section to the new sectionsection.cloneSectionPropertiesTo(newSection);// Copy the content of the original document's page to the new documentfor (int i = startIndex; i <=endIndex; i++){newSection.getBody().getChildObjects().add(section.getBody().getChildObjects().get(i).deepClone());}// Save the new document to the specified filenewdoc.saveToFile("/Users/liuhaihua/tmp/Content of One Page.docx", FileFormat.Docx);// Close and release the new documentnewdoc.close();newdoc.dispose();// Close and release the original documentdocument.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™

相关文章:

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

1.什么是spire.doc? Spire.Doc for Java 是一款专业的 Java Word 组件&#xff0c;开发人员使用它可以轻松地将 Word 文档创建、读取、编辑、转换和打印等功能集成到自己的 Java 应用程序中。作为一款完全独立的组件&#xff0c;Spire.Doc for Java 的运行环境无需安装 Micro…...

在Spring Boot中优化if-else语句

在Spring Boot中&#xff0c;优化if-else语句是提升代码质量、增强可读性和可维护性的重要手段。过多的if-else语句不仅会使代码变得复杂难懂&#xff0c;还可能导致代码难以扩展和维护。以下将介绍七种在Spring Boot中优化if-else语句的实战方法&#xff0c;每种方法都将结合示…...

【Django】开源前端库bootstrap,常用

文章目录 下载bootstrap源文件到本地项目引入bootstrap文件 官网&#xff1a;https://www.bootcss.com/V4版本入口&#xff1a;https://v4.bootcss.com/V5版本入口&#xff1a;https://v5.bootcss.com/ 这里使用成熟的V4版本&#xff0c;中文文档地址&#xff1a;https://v4.b…...

2024后端开发面试题总结

一、前言 上一篇离职贴发布之后仿佛登上了热门&#xff0c;就连曾经阿里的师兄都看到了我的分享&#xff0c;这波流量真是受宠若惊&#xff01; 回到正题&#xff0c;文章火之后&#xff0c;一些同学急切想要让我分享一下面试内容&#xff0c;回忆了几个晚上顺便总结一下&#…...

opencascade AIS_Manipulator源码学习

前言 AIS_Manipulator 是 OpenCASCADE 库中的一个类&#xff0c;用于在3D空间中对其他交互对象或一组对象进行局部变换。该类提供了直观的操控方式&#xff0c;使用户可以通过鼠标进行平移、缩放和旋转等操作。 详细功能 交互对象类&#xff0c;通过鼠标操控另一个交互对象…...

Hadoop、Hive、HBase、数据集成、Scala阶段测试

姓名&#xff1a; 总分&#xff1a;Hadoop、Hive、HBase、数据集成、Scala阶段测试 一、选择题&#xff08;共20道&#xff0c;每道0.5分&#xff09; 1、下面哪个程序负责HDFS数据存储&#xff08; C &#xff09; A. NameNode B. Jobtracher C. DataNode D. Sec…...

go语言day19 使用git上传包文件到github Gin框架入门

git分布式版本控制系统_git切换head指针-CSDN博客 获取请求参数并和struct结构体绑定_哔哩哔哩_bilibili &#xff08;gin框架&#xff09; GO: 引入GIn框架_go 引入 gin-CSDN博客 使用git上传包文件 1&#xff09;创建一个github账户&#xff0c;进入Repositories个人仓…...

Ubuntu升级软件或系统

Ubuntu升级软件或系统 升级Ubuntu系统通常是一个相对简单的过程&#xff0c;但在进行操作之前&#xff0c;请务必备份重要数据以防万一。下面是升级Ubuntu系统的一般步骤&#xff1a; 使用软件更新工具升级系统 打开终端&#xff1a; 按下 Ctrl Alt T 组合键打开终端。 更…...

【Redis】Centos7 安装 redis(详细教程)

查看当前 Redis 版本&#xff1a; 当前的 redis 版本太老了&#xff0c;选择安装 Redis5。 一、使用 yum 安装 1、首先安装 scl 源 yum install centos-release-scl-rh 由于我之前已经安装过了&#xff0c;所以加载速度比较快&#xff0c;且显示已经安装成功&#xff0c;是最…...

Hakuin:一款自动化SQL盲注(BSQLI)安全检测工具

关于Hakuin Hakuin是一款功能强大的SQL盲注漏洞安全检测工具&#xff0c;该工具专门针对BSQLi设计&#xff0c;可以帮助广大研究人员优化BSQLi测试用例&#xff0c;并以自动化的形式完成针对目标Web应用程序的漏洞扫描与检测任务。 该工具允许用户以轻松高效的形式对目标Web应…...

在 Postman 中设置全局 token

目录 问题描述解决方案 问题描述 在使用 Postman 进行接口测试时&#xff0c;经常会遇到在 Header 中添加 token 的情况。当接口数量较多时&#xff0c;需要为每个接口进行设置&#xff0c;而且当 token 失效时需要重新获取并设置&#xff0c;这样一来效率较低。 解决方案 下…...

Linux C编程:打造一个插件系统

title: ‘Linux C编程:打造一个插件系统’ date: 2017-03-07 21:16:36 tags: linux C layout: post comments: true 运行环境&#xff1a;linux 使用语言&#xff1a;c 或者c 插件&#xff0c;很多人用过&#xff0c;比如游戏插件&#xff0c;编辑器插件这些&#xff0c; 最著…...

基于毫米波生物感知雷达+STM32设计的独居老人居家监护系统(微信小程序)(192)

基于毫米波生物感知雷达设计的独居老人居家监护系统(微信小程序)(192) 文章目录 一、前言1.1 项目介绍【1】项目功能介绍【2】项目硬件模块组成1.2 设计思路【1】整体设计思路【2】60G毫米波生物感知雷达原理【3】ESP8266模块配置【4】供电方式1.3 项目开发背景【1】选题的意义…...

C++——类和对象(下)

目录 一、再探构造函数 1.基本定义以及用法 2.必须在初始化列表初始化的成员变量 3.成员变量声明位置的缺省值&#xff08;C11&#xff09; 4.成员变量初始化顺序 二、隐式类型转换 三、static成员 四、友元 五、内部类 六、匿名对象 七、日期类实现 一、再探构造函数…...

Android中集成前端页面探索(Capacitor 或 Cordova 插件)待完善......

探索目标&#xff1a;Android中集成前端页面 之前使用的webview加载html页面&#xff0c;使用bridge的方式进行原生安卓和html页面的通信的方式&#xff0c;探索capacitor-android插件是如何操作的 capacitor-android用途 Capacitor 是一个用于构建现代跨平台应用程序的开源框…...

玩转CSS:用ul li +JS 模拟select,避坑浏览器不兼容。

玩转CSS&#xff1a;用ul li JS 模拟select&#xff0c;避坑浏览器不兼容。 在前端的工作中&#xff0c;经常会遇到 selcet控件&#xff0c;但我们用css来写它的样式时候&#xff0c;总是不那么令人满意&#xff0c;各种浏览器不兼容啊有没有&#xff1f; 那么&#xff0c;我…...

介绍下PolarDB

业务中用的是阿里云自研的PolarDB&#xff0c;分析下PolarDB的架构。 认识PolarDB 介绍 PolarDB是阿里云自研的&#xff0c;兼容MySQL、PostageSQL以及支持MPP的PolarDB-X的高可用、高扩展性的数据库。 架构 部署 云起实验室 - 阿里云开发者社区 - 阿里云 (aliyun.com) 数…...

基于微信小程序+SpringBoot+Vue的儿童预防接种预约系统(带1w+文档)

基于微信小程序SpringBootVue的儿童预防接种预约系统(带1w文档) 基于微信小程序SpringBootVue的儿童预防接种预约系统(带1w文档) 开发合适的儿童预防接种预约微信小程序&#xff0c;可以方便管理人员对儿童预防接种预约微信小程序的管理&#xff0c;提高信息管理工作效率及查询…...

go语言day15 goroutine

Golang-100-Days/Day16-20(Go语言基础进阶)/day17_Go语言并发Goroutine.md at master rubyhan1314/Golang-100-Days GitHub 第2讲-调度器的由来和分析_哔哩哔哩_bilibili 一个进程最多可以创建多少个线程&#xff1f;-CSDN博客 引入协程 go语言中内置了协程goroutine&#…...

Mindspore框架循环神经网络RNN模型实现情感分类|(六)模型加载和推理(情感分类模型资源下载)

Mindspore框架循环神经网络RNN模型实现情感分类 Mindspore框架循环神经网络RNN模型实现情感分类|&#xff08;一&#xff09;IMDB影评数据集准备 Mindspore框架循环神经网络RNN模型实现情感分类|&#xff08;二&#xff09;预训练词向量 Mindspore框架循环神经网络RNN模型实现…...

基于ASP.NET+ SQL Server实现(Web)医院信息管理系统

医院信息管理系统 1. 课程设计内容 在 visual studio 2017 平台上&#xff0c;开发一个“医院信息管理系统”Web 程序。 2. 课程设计目的 综合运用 c#.net 知识&#xff0c;在 vs 2017 平台上&#xff0c;进行 ASP.NET 应用程序和简易网站的开发&#xff1b;初步熟悉开发一…...

SCAU期末笔记 - 数据分析与数据挖掘题库解析

这门怎么题库答案不全啊日 来简单学一下子来 一、选择题&#xff08;可多选&#xff09; 将原始数据进行集成、变换、维度规约、数值规约是在以下哪个步骤的任务?(C) A. 频繁模式挖掘 B.分类和预测 C.数据预处理 D.数据流挖掘 A. 频繁模式挖掘&#xff1a;专注于发现数据中…...

基于数字孪生的水厂可视化平台建设:架构与实践

分享大纲&#xff1a; 1、数字孪生水厂可视化平台建设背景 2、数字孪生水厂可视化平台建设架构 3、数字孪生水厂可视化平台建设成效 近几年&#xff0c;数字孪生水厂的建设开展的如火如荼。作为提升水厂管理效率、优化资源的调度手段&#xff0c;基于数字孪生的水厂可视化平台的…...

TRS收益互换:跨境资本流动的金融创新工具与系统化解决方案

一、TRS收益互换的本质与业务逻辑 &#xff08;一&#xff09;概念解析 TRS&#xff08;Total Return Swap&#xff09;收益互换是一种金融衍生工具&#xff0c;指交易双方约定在未来一定期限内&#xff0c;基于特定资产或指数的表现进行现金流交换的协议。其核心特征包括&am…...

【RockeMQ】第2节|RocketMQ快速实战以及核⼼概念详解(二)

升级Dledger高可用集群 一、主从架构的不足与Dledger的定位 主从架构缺陷 数据备份依赖Slave节点&#xff0c;但无自动故障转移能力&#xff0c;Master宕机后需人工切换&#xff0c;期间消息可能无法读取。Slave仅存储数据&#xff0c;无法主动升级为Master响应请求&#xff…...

R语言速释制剂QBD解决方案之三

本文是《Quality by Design for ANDAs: An Example for Immediate-Release Dosage Forms》第一个处方的R语言解决方案。 第一个处方研究评估原料药粒径分布、MCC/Lactose比例、崩解剂用量对制剂CQAs的影响。 第二处方研究用于理解颗粒外加硬脂酸镁和滑石粉对片剂质量和可生产…...

多模态图像修复系统:基于深度学习的图片修复实现

多模态图像修复系统:基于深度学习的图片修复实现 1. 系统概述 本系统使用多模态大模型(Stable Diffusion Inpainting)实现图像修复功能,结合文本描述和图片输入,对指定区域进行内容修复。系统包含完整的数据处理、模型训练、推理部署流程。 import torch import numpy …...

R 语言科研绘图第 55 期 --- 网络图-聚类

在发表科研论文的过程中&#xff0c;科研绘图是必不可少的&#xff0c;一张好看的图形会是文章很大的加分项。 为了便于使用&#xff0c;本系列文章介绍的所有绘图都已收录到了 sciRplot 项目中&#xff0c;获取方式&#xff1a; R 语言科研绘图模板 --- sciRplothttps://mp.…...

阿里云Ubuntu 22.04 64位搭建Flask流程(亲测)

cd /home 进入home盘 安装虚拟环境&#xff1a; 1、安装virtualenv pip install virtualenv 2.创建新的虚拟环境&#xff1a; virtualenv myenv 3、激活虚拟环境&#xff08;激活环境可以在当前环境下安装包&#xff09; source myenv/bin/activate 此时&#xff0c;终端…...

PH热榜 | 2025-06-08

1. Thiings 标语&#xff1a;一套超过1900个免费AI生成的3D图标集合 介绍&#xff1a;Thiings是一个不断扩展的免费AI生成3D图标库&#xff0c;目前已有超过1900个图标。你可以按照主题浏览&#xff0c;生成自己的图标&#xff0c;或者下载整个图标集。所有图标都可以在个人或…...