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™

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

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

相关文章

【stm32项目】基于stm32智能宠物喂养(完整工程资料源码)

基于STM32宠物喂养系统 前言&#xff1a; 随着人们生活幸福指数的提高&#xff0c;越来越多的家庭选择养宠物来为生活增添乐趣。然而&#xff0c;由于工作等原因&#xff0c;许多主人无法及时为宠物提供充足的食物与水。为了解决这一问题&#xff0c;我设计了一款便捷的宠物喂…

【Linux】centos7安装php7.4

环境说明 本文档在服务器不能连接互联网的情况下&#xff0c;进行安装php7.4及其扩展。 操作系统&#xff1a;centos7.6 架构&#xff1a;X86_64 一、安装依赖&#xff08;可选&#xff09; 说明&#xff1a;服务器能联网就可以通过 yum install 命令下载对应php需要的依赖…

设计模式之策略模式_入门

前言 最近接触了优惠券相关的业务&#xff0c;如果是以前&#xff0c;我第一时间想到的就是if_else开始套&#xff0c;这样的话耦合度太高了&#xff0c;如果后期添加或者删除优惠券&#xff0c;必须直接修改业务代码&#xff0c;不符合开闭原则&#xff0c;这时候就可以选择我…

【TypeScript 一点点教程】

文章目录 一、开发环境搭建二、基本类型2.1 类型声明2.2 基本类型 三、编译3.1 tsc命令3.2 tsconfig.json3.2.1 基本配置项includeexcludeextendsfiles 3.2.2 compilerOptions编译器的配置项 四、面向对象4.1 类4.2 继承4.3 抽象类4.4 接口 一、开发环境搭建 下载Node.js《Nod…

usb pd message结构解析

usb pd 3.1规范定义了三种类型的消息: •简短的控制消息&#xff0c;用于管理端口伙伴之间的消息流或交换不需要额外数据的消息。控制消息的长度为16位。 •用于在一对端口伙伴之间交换信息的数据消息。数据报文的长度范围是48 ~ 240位。 有三种类型的数据消息: ▪那些用于暴露…

【区块链+绿色低碳】双碳数字化管控平台 | FISCO BCOS应用案例

地方政府、园区及企业实现“双碳”目标过程中存在一些挑战与难点&#xff1a; 1. 管理者难以掌握完整、准确、全面的碳排放数据进行科学决策&#xff1a;由于碳排放核算需要对数据的来源、核算方法 的规范性和采集方法的科学性有严格要求&#xff0c;当前面临碳排放数据数据采…

中国一汽发布“一汽●北斗云工作台” 意在推动企业数智化转型

“一汽●北斗云工作台”已经实现100%自主可控&#xff0c;覆盖企业全价值链、全体系、全过程、全岗位的工作需求。目前一汽2.3万个业务单元实现线上作业&#xff0c;产品开发效率提升30%&#xff0c;订单交付周期缩短25%以上。”7月17日&#xff0c;中国第一汽车集团有限公司&a…

electron 网页TodoList工具打包成win桌面应用exe

参考&#xff1a; electron安装&#xff08;支持win、mac、linux桌面应用&#xff09; https://blog.csdn.net/weixin_42357472/article/details/140643624 TodoList工具 https://blog.csdn.net/weixin_42357472/article/details/140618446 electron打包过程&#xff1a; 要将…

【吊打面试官系列-ZooKeeper面试题】Zookeeper 的典型应用场景

​大家好&#xff0c;我是锋哥。今天分享关于 【Zookeeper 的典型应用场景 】面试题&#xff0c;希望对大家有帮助&#xff1b; Zookeeper 的典型应用场景 Zookeeper 是一个典型的发布/订阅模式的分布式数据管理与协调框架&#xff0c;开发人员可以使用它来进行分布式数据的发布…

学习React(状态管理)

随着你的应用不断变大&#xff0c;更有意识的去关注应用状态如何组织&#xff0c;以及数据如何在组件之间流动会对你很有帮助。冗余或重复的状态往往是缺陷的根源。在本节中&#xff0c;你将学习如何组织好状态&#xff0c;如何保持状态更新逻辑的可维护性&#xff0c;以及如何…

基于自组织映射的检索增强生成

大量数据用于训练大型语言模型 (LLM)&#xff0c;该模型包含数百万和数十亿个模型参数&#xff0c;目的是生成文本&#xff0c;例如文本补全、文本摘要、语言翻译和回答问题。虽然 LLM 从训练数据源中开发知识库&#xff0c;但总有一个训练截止日期&#xff0c;在此日期之后 LL…

java jts 针对shp含洞多边形进行三角剖分切分成可行区域

前言 java jts 提供了Delaunay三角剖分的相关方法,但是该方法不考虑含洞的多边形的。虽然 jts 的 ConformingDelaunayTriangulationBuilder 类可以通过提供线段约束的方式防止切割到洞内&#xff0c;但是仅支持最多99条线段&#xff0c;虽然可以通过重写破除99条线段的约束&am…

Java——————接口(interface) <详解>

1.1 接口的概念 在现实生活中&#xff0c;接口的例子比比皆是&#xff0c;比如&#xff1a;笔记本电脑上的USB接口&#xff0c;电源插座等。 电脑的USB口上&#xff0c;可以插&#xff1a;U盘、鼠标、键盘...所有符合USB协议的设备 电源插座插孔上&#xff0c;可以插&#xff…

OS Copilot初体验的感受与心得

本文介绍体验操作系统智能助手OS Copilot后&#xff0c;个人的一些收获、体验等。 最近&#xff0c;抽空体验了阿里云的操作系统智能助手OS Copilot&#xff0c;在这里记录一下心得与收获。总体观之&#xff0c;从个人角度来说&#xff0c;感觉这个OS Copilot确实抓住了不少开发…

EasyMedia转码rtsp视频流flv格式,hls格式,H5页面播放flv流视频

EasyMedia转码rtsp视频流flv格式&#xff0c;hls格式 H5页面播放flv流视频 文章最后有源码地址 解决海康视频播放视频流&#xff0c;先转码后自定义页面播放flv视频流 先看效果&#xff0c;1&#xff0c;EasyMedia自带的页面&#xff0c;这个页面二次开发改动页面比较麻烦 …

张高兴的 MicroPython 入门指南:(三)使用串口通信

目录 什么是串口使用方法使用板载串口相互通信 硬件需求电路代码使用板载的 USB 串口参考 什么是串口 串口是串行接口的简称&#xff0c;这是一个非常大的概念&#xff0c;在嵌入式中串口通常指 UART(Universal Asynchronous Receiver/Transmitter&#xff0c;通用异步收发器)。…

初识c++(string和模拟实现string)

一、标准库中的string类 string类的文档介绍&#xff1a;cplusplus.com/reference/string/string/?kwstring 1、auto和范围for auto&#xff1a; 在早期C/C中auto的含义是&#xff1a;使用auto修饰的变量&#xff0c;是具有自动存储器的局部变量&#xff0c;后来这个 不重…

Cannot perform upm operation: connect ETIMEDOUT 34.36.199.114:443 [NotFound]

版本&#xff1a;Unity 2018 Windows 问题&#xff1a;打开 Package Manager&#xff0c;加载报错 尝试解决&#xff1a; 删除项目文件里的Packages下的mainfest.json文件&#xff0c;然后重新打开项目&#xff08;X&#xff09;重新登录 Unity 账号&#xff08;X&#xff09…

Kotlin 协程 — 基础

Kotlin 协程 — 基础 协程已经存在一段时间了&#xff0c;关于它的各种文章也很多。但我发现想要了解它还比较费时&#xff0c;所以我花了一段时间才真正理解了协程的基础知识以及它的工作原理。因此&#xff0c;我想分享一些我理解到的内容。 什么是协程&#xff1f; 协程代表…

vue项目实战速查记录

1.图片下载到本地 2.本地静态文件访问 3.元素大小相同,相互覆盖 1.图片下载到本地 实现原理:创建a标签,利用a标签下载属性. download(){const link document.createElement(a);link.href "图片地址";link.setAttribute(download, name);document.body.ap…