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 object Document doc = new Document();
//Add a section Section section = doc.addSection();
//Set the page margins section.getPageSetup().getMargins().setAll(40f);
//Add a paragraph as title Paragraph titleParagraph = section.addParagraph(); titleParagraph.appendText("Introduction of Spire.Doc for Java");
//Add two paragraphs as body Paragraph 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 paragraph ParagraphStyle 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 paragraphs ParagraphStyle 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 paragraphs titleParagraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); bodyParagraph_1.getFormat().setHorizontalAlignment(HorizontalAlignment.Justify); bodyParagraph_2.getFormat().setHorizontalAlignment(HorizontalAlignment.Justify);
//Set the first line indent bodyParagraph_1.getFormat().setFirstLineIndent(30) ; bodyParagraph_2.getFormat().setFirstLineIndent(30);
//Set the after spacing titleParagraph.getFormat().setAfterSpacing(10); bodyParagraph_1.getFormat().setAfterSpacing(10);
//Save to file doc.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 object Document document = new Document();
// Load a sample document from a file document.loadFromFile("/Users/liuhaihua/tmp/WordDocument.docx");
// Get the body of the last section of the document Body body = document.getLastSection().getBody();
// Insert a page break after the last paragraph in the body body.getLastParagraph().appendBreak(BreakType.Page_Break);
// Create a new paragraph style ParagraphStyle 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 collection document.getStyles().add(paragraphStyle);
// Create a new paragraph and set the text content Paragraph 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 style paragraph.applyStyle(paragraphStyle.getName());
// Add the paragraph to the body's content collection body.getChildObjects().add(paragraph);
// Create another new paragraph and set the text content paragraph = 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 style paragraph.applyStyle(paragraphStyle.getName());
// Add the paragraph to the body's content collection body.getChildObjects().add(paragraph);
// Save the document to a specified path document.saveToFile("/Users/liuhaihua/tmp/Add a Page.docx", FileFormat.Docx);
// Close the document document.close();
// Dispose of the document object's resources document.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 object Document document = new Document();
// Load document content from the specified file document.loadFromFile("/Users/liuhaihua/tmp/WordDocument.docx");
// Create a fixed layout document object FixedLayoutDocument layoutDoc = new FixedLayoutDocument(document);
// Get the first page FixedLayoutPage page = layoutDoc.getPages().get(0);
// Get the section where the page is located Section section = page.getSection();
// Get the first paragraph of the page Paragraph paragraphStart = page.getColumns().get(0).getLines().getFirst().getParagraph(); int startIndex = 0; if (paragraphStart != null) { // Get the index of the paragraph in the section startIndex = section.getBody().getChildObjects().indexOf(paragraphStart); }
// Get the last paragraph of the page Paragraph paragraphEnd = page.getColumns().get(0).getLines().getLast().getParagraph();
int endIndex = 0; if (paragraphEnd != null) { // Get the index of the paragraph in the section endIndex = section.getBody().getChildObjects().indexOf(paragraphEnd); }
// Create a new document object Document newdoc = new Document();
// Add a new section Section newSection = newdoc.addSection();
// Clone the properties of the original section to the new section section.cloneSectionPropertiesTo(newSection);
// Copy the content of the original document's page to the new document for (int i = startIndex; i <=endIndex; i++) { newSection.getBody().getChildObjects().add(section.getBody().getChildObjects().get(i).deepClone()); }
// Save the new document to the specified file newdoc.saveToFile("/Users/liuhaihua/tmp/Content of One Page.docx", FileFormat.Docx);
// Close and release the new document newdoc.close(); newdoc.dispose();
// Close and release the original document document.close(); document.dispose(); }}

以上只是一些关键代码,所有代码请参见下面代码仓库

代码仓库

  • https://github.com/Harries/springboot-demo(spire-doc)

3.测试

运行上述java类的main方法,会生成3个文件在对应的目录下

4.引用

  • https://www.e-iceblue.com/Tutorials/Java/Spire.Doc-for-Java/Program-Guide/Document-Operation/Create-Word-Document-in-Java.html

  • http://www.liuhaihua.cn/archives/710952.html

相关推荐

  • 不会?到底上OPC UA还是MODBUS???
  • 2K Star牛牛牛!!!全球频道,一键直达,探索IPTV新天地
  • 损失函数(Loss Function)
  • 2个月暴增10k star,新一代高颜值、现代化的 Git 可视化工具
  • 最有用的25个 Matplotlib图(含Python代码模板)
  • 吴恩达团队新作!
  • Python 面试时千万别这样命名函数,因为这个被淘汰可太不值了
  • 阿里这款多级缓存框架一定要掌握,非常不错!
  • AI替代职业,最高和最低Top25
  • 一文带你了解 Chrome AI
  • 苹果开源7B大模型,训练过程数据集一口气全给了,网友:开放得不像苹果
  • 当小说续写结合AI RPG,AI陪伴的新玩法现状如何?|专访彩云小梦
  • 快手可灵团队最新开源项目火了:大叔实时变身少女,GitHub狂揽7.5K星
  • 英特尔CPU疯狂崩溃,测评大佬揭露工艺缺陷,官方回应:修复补丁下月上线
  • 马斯克狂揽10万块H100,自建世界最强AI超算,下一代模型训练开始
  • 几何朗兰兹猜想被解决!历时30年、证明论文达800余页,中国学者陈麟系主要作者
  • 轻松、有趣的掌握梯度下降!
  • “所有为政府开发的软件,都必须开源!”瑞士新规引争议:里程碑 or 鸡肋?
  • 智能进化:具身智能系统基础模型的技术路线 | 新程序员
  • 不装了!4 年推迟两次后,谷歌摊牌:我们不会弃用第三方 Cookie