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个文件在对应的目录下
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 组件,开发人员使用它可以轻松地将 Word 文档创建、读取、编辑、转换和打印等功能集成到自己的 Java 应用程序中。作为一款完全独立的组件,Spire.Doc for Java 的运行环境无需安装 Micro…...
在Spring Boot中优化if-else语句
在Spring Boot中,优化if-else语句是提升代码质量、增强可读性和可维护性的重要手段。过多的if-else语句不仅会使代码变得复杂难懂,还可能导致代码难以扩展和维护。以下将介绍七种在Spring Boot中优化if-else语句的实战方法,每种方法都将结合示…...

【Django】开源前端库bootstrap,常用
文章目录 下载bootstrap源文件到本地项目引入bootstrap文件 官网:https://www.bootcss.com/V4版本入口:https://v4.bootcss.com/V5版本入口:https://v5.bootcss.com/ 这里使用成熟的V4版本,中文文档地址:https://v4.b…...

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

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

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

go语言day19 使用git上传包文件到github Gin框架入门
git分布式版本控制系统_git切换head指针-CSDN博客 获取请求参数并和struct结构体绑定_哔哩哔哩_bilibili (gin框架) GO: 引入GIn框架_go 引入 gin-CSDN博客 使用git上传包文件 1)创建一个github账户,进入Repositories个人仓…...
Ubuntu升级软件或系统
Ubuntu升级软件或系统 升级Ubuntu系统通常是一个相对简单的过程,但在进行操作之前,请务必备份重要数据以防万一。下面是升级Ubuntu系统的一般步骤: 使用软件更新工具升级系统 打开终端: 按下 Ctrl Alt T 组合键打开终端。 更…...

【Redis】Centos7 安装 redis(详细教程)
查看当前 Redis 版本: 当前的 redis 版本太老了,选择安装 Redis5。 一、使用 yum 安装 1、首先安装 scl 源 yum install centos-release-scl-rh 由于我之前已经安装过了,所以加载速度比较快,且显示已经安装成功,是最…...

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

在 Postman 中设置全局 token
目录 问题描述解决方案 问题描述 在使用 Postman 进行接口测试时,经常会遇到在 Header 中添加 token 的情况。当接口数量较多时,需要为每个接口进行设置,而且当 token 失效时需要重新获取并设置,这样一来效率较低。 解决方案 下…...
Linux C编程:打造一个插件系统
title: ‘Linux C编程:打造一个插件系统’ date: 2017-03-07 21:16:36 tags: linux C layout: post comments: true 运行环境:linux 使用语言:c 或者c 插件,很多人用过,比如游戏插件,编辑器插件这些, 最著…...
基于毫米波生物感知雷达+STM32设计的独居老人居家监护系统(微信小程序)(192)
基于毫米波生物感知雷达设计的独居老人居家监护系统(微信小程序)(192) 文章目录 一、前言1.1 项目介绍【1】项目功能介绍【2】项目硬件模块组成1.2 设计思路【1】整体设计思路【2】60G毫米波生物感知雷达原理【3】ESP8266模块配置【4】供电方式1.3 项目开发背景【1】选题的意义…...

C++——类和对象(下)
目录 一、再探构造函数 1.基本定义以及用法 2.必须在初始化列表初始化的成员变量 3.成员变量声明位置的缺省值(C11) 4.成员变量初始化顺序 二、隐式类型转换 三、static成员 四、友元 五、内部类 六、匿名对象 七、日期类实现 一、再探构造函数…...
Android中集成前端页面探索(Capacitor 或 Cordova 插件)待完善......
探索目标:Android中集成前端页面 之前使用的webview加载html页面,使用bridge的方式进行原生安卓和html页面的通信的方式,探索capacitor-android插件是如何操作的 capacitor-android用途 Capacitor 是一个用于构建现代跨平台应用程序的开源框…...

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

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

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

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

Mindspore框架循环神经网络RNN模型实现情感分类|(六)模型加载和推理(情感分类模型资源下载)
Mindspore框架循环神经网络RNN模型实现情感分类 Mindspore框架循环神经网络RNN模型实现情感分类|(一)IMDB影评数据集准备 Mindspore框架循环神经网络RNN模型实现情感分类|(二)预训练词向量 Mindspore框架循环神经网络RNN模型实现…...
java_网络服务相关_gateway_nacos_feign区别联系
1. spring-cloud-starter-gateway 作用:作为微服务架构的网关,统一入口,处理所有外部请求。 核心能力: 路由转发(基于路径、服务名等)过滤器(鉴权、限流、日志、Header 处理)支持负…...

汽车生产虚拟实训中的技能提升与生产优化
在制造业蓬勃发展的大背景下,虚拟教学实训宛如一颗璀璨的新星,正发挥着不可或缺且日益凸显的关键作用,源源不断地为企业的稳健前行与创新发展注入磅礴强大的动力。就以汽车制造企业这一极具代表性的行业主体为例,汽车生产线上各类…...
五年级数学知识边界总结思考-下册
目录 一、背景二、过程1.观察物体小学五年级下册“观察物体”知识点详解:由来、作用与意义**一、知识点核心内容****二、知识点的由来:从生活实践到数学抽象****三、知识的作用:解决实际问题的工具****四、学习的意义:培养核心素养…...
基于数字孪生的水厂可视化平台建设:架构与实践
分享大纲: 1、数字孪生水厂可视化平台建设背景 2、数字孪生水厂可视化平台建设架构 3、数字孪生水厂可视化平台建设成效 近几年,数字孪生水厂的建设开展的如火如荼。作为提升水厂管理效率、优化资源的调度手段,基于数字孪生的水厂可视化平台的…...

CocosCreator 之 JavaScript/TypeScript和Java的相互交互
引擎版本: 3.8.1 语言: JavaScript/TypeScript、C、Java 环境:Window 参考:Java原生反射机制 您好,我是鹤九日! 回顾 在上篇文章中:CocosCreator Android项目接入UnityAds 广告SDK。 我们简单讲…...
汇编常见指令
汇编常见指令 一、数据传送指令 指令功能示例说明MOV数据传送MOV EAX, 10将立即数 10 送入 EAXMOV [EBX], EAX将 EAX 值存入 EBX 指向的内存LEA加载有效地址LEA EAX, [EBX4]将 EBX4 的地址存入 EAX(不访问内存)XCHG交换数据XCHG EAX, EBX交换 EAX 和 EB…...

GC1808高性能24位立体声音频ADC芯片解析
1. 芯片概述 GC1808是一款24位立体声音频模数转换器(ADC),支持8kHz~96kHz采样率,集成Δ-Σ调制器、数字抗混叠滤波器和高通滤波器,适用于高保真音频采集场景。 2. 核心特性 高精度:24位分辨率,…...
[特殊字符] 手撸 Redis 互斥锁那些坑
📖 手撸 Redis 互斥锁那些坑 最近搞业务遇到高并发下同一个 key 的互斥操作,想实现分布式环境下的互斥锁。于是私下顺手手撸了个基于 Redis 的简单互斥锁,也顺便跟 Redisson 的 RLock 机制对比了下,记录一波,别踩我踩过…...
JavaScript 标签加载
目录 JavaScript 标签加载script 标签的 async 和 defer 属性,分别代表什么,有什么区别1. 普通 script 标签2. async 属性3. defer 属性4. type"module"5. 各种加载方式的对比6. 使用建议 JavaScript 标签加载 script 标签的 async 和 defer …...

VSCode 没有添加Windows右键菜单
关键字:VSCode;Windows右键菜单;注册表。 文章目录 前言一、工程环境二、配置流程1.右键文件打开2.右键文件夹打开3.右键空白处打开文件夹 三、测试总结 前言 安装 VSCode 时没有注意,实际使用的时候发现 VSCode 在 Windows 菜单栏…...