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模型实现…...
浅谈 React Hooks
React Hooks 是 React 16.8 引入的一组 API,用于在函数组件中使用 state 和其他 React 特性(例如生命周期方法、context 等)。Hooks 通过简洁的函数接口,解决了状态与 UI 的高度解耦,通过函数式编程范式实现更灵活 Rea…...
简易版抽奖活动的设计技术方案
1.前言 本技术方案旨在设计一套完整且可靠的抽奖活动逻辑,确保抽奖活动能够公平、公正、公开地进行,同时满足高并发访问、数据安全存储与高效处理等需求,为用户提供流畅的抽奖体验,助力业务顺利开展。本方案将涵盖抽奖活动的整体架构设计、核心流程逻辑、关键功能实现以及…...
基于服务器使用 apt 安装、配置 Nginx
🧾 一、查看可安装的 Nginx 版本 首先,你可以运行以下命令查看可用版本: apt-cache madison nginx-core输出示例: nginx-core | 1.18.0-6ubuntu14.6 | http://archive.ubuntu.com/ubuntu focal-updates/main amd64 Packages ng…...
C++.OpenGL (10/64)基础光照(Basic Lighting)
基础光照(Basic Lighting) 冯氏光照模型(Phong Lighting Model) #mermaid-svg-GLdskXwWINxNGHso {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-GLdskXwWINxNGHso .error-icon{fill:#552222;}#mermaid-svg-GLd…...
Caliper 负载(Workload)详细解析
Caliper 负载(Workload)详细解析 负载(Workload)是 Caliper 性能测试的核心部分,它定义了测试期间要执行的具体合约调用行为和交易模式。下面我将全面深入地讲解负载的各个方面。 一、负载模块基本结构 一个典型的负载模块(如 workload.js)包含以下基本结构: use strict;/…...
Leetcode33( 搜索旋转排序数组)
题目表述 整数数组 nums 按升序排列,数组中的值 互不相同 。 在传递给函数之前,nums 在预先未知的某个下标 k(0 < k < nums.length)上进行了 旋转,使数组变为 [nums[k], nums[k1], …, nums[n-1], nums[0], nu…...
规则与人性的天平——由高考迟到事件引发的思考
当那位身着校服的考生在考场关闭1分钟后狂奔而至,他涨红的脸上写满绝望。铁门内秒针划过的弧度,成为改变人生的残酷抛物线。家长声嘶力竭的哀求与考务人员机械的"这是规定",构成当代中国教育最尖锐的隐喻。 一、刚性规则的必要性 …...
高分辨率图像合成归一化流扩展
大家读完觉得有帮助记得关注和点赞!!! 1 摘要 我们提出了STARFlow,一种基于归一化流的可扩展生成模型,它在高分辨率图像合成方面取得了强大的性能。STARFlow的主要构建块是Transformer自回归流(TARFlow&am…...
高抗扰度汽车光耦合器的特性
晶台光电推出的125℃光耦合器系列产品(包括KL357NU、KL3H7U和KL817U),专为高温环境下的汽车应用设计,具备以下核心优势和技术特点: 一、技术特性分析 高温稳定性 采用先进的LED技术和优化的IC设计,确保在…...
Axure零基础跟我学:展开与收回
亲爱的小伙伴,如有帮助请订阅专栏!跟着老师每课一练,系统学习Axure交互设计课程! Axure产品经理精品视频课https://edu.csdn.net/course/detail/40420 课程主题:Axure菜单展开与收回 课程视频:...
