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模型实现…...

System类
System类常见方法 ① exit 退出当前程序 public static void main(String[] args) {System.out.println("ok1");//0表示状态,即正常退出System.exit(0);System.out.println("ok2");} ② arraycopy 复制数组元素 复制的数组元素个数必须<原数…...

【前端 02】新浪新闻项目-初步使用CSS来排版
在今天的博文中,我们将围绕“新浪新闻”项目,深入探讨HTML和CSS在网页制作中的基础应用。通过具体实例,我们将学习如何设置图片、标题、超链接以及文本排版,同时了解CSS的引入方式和选择器优先级,以及视频和音频标签的…...

HarmonyOS和OpenHarmony区别联系
前言 相信我们在刚开始接触鸿蒙开发的时候经常看到HarmonyOS和OpenHarmony频繁的出现在文章和文档之中,那么这两个名词分别是什么意思,他们之间又有什么联系呢?本文将通过现有的文章和网站内容并与Google的AOSP和Android做对比,带…...

llama模型,nano
目录 llama模型 Llama模型性能评测 nano模型是什么 Gemini Nano模型 参数量 MMLU、GPQA、HumanEval 1. MMLU(Massive Multi-task Language Understanding) 2. GPQA(Grade School Physics Question Answering) 3. HumanEval llama模型 Large Language Model AI Ll…...

ElasticSearch的应用场景和优势
ElasticSearch是一个开源的分布式搜索和分析引擎,它以其高性能、可扩展性和实时性在多个领域得到了广泛应用。以下是ElasticSearch的主要应用场景和优势: 应用场景 实时搜索: ElasticSearch以其快速、可扩展和实时的特性,成为实…...

git 、shell脚本
git 文件版本控制 安装git yum -y install git 创建仓库 将文件提交到暂存 git add . #将暂存区域的文件提交仓库 git commit -m "说明" #推送到远程仓库 git push #获取远程仓库的更新 git pull #克隆远程仓库 git clone #分支,提高代码的灵活性 #检查分…...

阿里云服务器 篇六:GitHub镜像网站
文章目录 系列文章搭建镜像网站的2种方式使用 Web 抓取工具 (Spider 技术)使用 Web 代理服务器使用 nginx 搭建GitHub镜像网站基础环境搭建添加对 github.com 的转发配置添加对 raw.githubusercontent.com 的转发配置配置更改注意事项(可选)缓存优化为新增设的二级域名配置DN…...

强化学习学习(三)收敛性证明与DDPG
文章目录 证明收敛? Deep RL with Q-FunctionsDouble Q-Learning理论上的解法实际上的解法 DDPG: Q-Learning with continuous actionsAdvanced tips for Q-Learning 证明收敛? 对于Value迭代:不动点证明的思路 首先定义一个算子 B : B V ma…...

培养前端工程化思维,不要让一行代码毁了整个程序
看《阿丽亚娜 5 号(Ariane 5)火箭爆炸》有感。 1、动手写项目之前,先进行全局性代码逻辑思考,将该做的事情,一些细节,统一建立标准,避免为以后埋雷。 2、避免使用不必要或无意义的代码、注释。…...

电子文件怎么盖章?
电子文件怎么盖章?电子文件盖章是数字化办公中常见的操作,包括盖电子公章和电子骑缝章。以下是针对这两种情况的详细步骤: 一、盖电子公章 方法一:使用专业软件 选择软件:选择一款专业的电子签名或PDF编辑软件&…...