在日常的软件开发中,我们常常会遇到需要程序化生成 Word 文档的需求,例如生成报告、合同、发票或各种业务文档。传统的文档生成方式往往效率低下,难以灵活应对复杂多变的业务逻辑。那么,如何才能通过 Java 高效、灵活地生成结构复杂、内容丰富的 Word 文档呢?本教程将深入探讨如何利用 Spire.Doc for Java 这一强大库,帮助开发者掌握 Java 创建 Word 文档的核心技能,提供详细的步骤和可直接运行的代码示例。
Spire.Doc for Java 简介与安装
Spire.Doc for Java 是一个功能强大且易于使用的 Java Word API,它允许开发者在 Java 应用程序中创建、读取、写入、转换和打印 Word 文档,而无需安装 Microsoft Office。它支持 DOC、DOCX、RTF、TXT、HTML 等多种格式,并提供了丰富的 API 来处理文档内容,如文本、图片、表格、图表、页眉页脚等。要开始使用 Spire.Doc for Java,您只需将其 Maven 或 Gradle 依赖添加到您的项目中,或者手动导入 JAR 包即可。
在 Word 文档中添加标题
创建 Word 文档的第一步是构建其基本结构。这包括创建文档对象、添加章节以及插入带有不同格式的段落。下面我们来看看怎样在 Word 文档中去添加新的标题。
ini
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;
import java.awt.Color;
public class CreateSimpleDocument {
public static void main(String[] args) {
// 创建一个 Document 类的对象
Document document = new Document();
// 添加节
Section section = document.addSection();
// 设置页边距
section.getPageSetup().getMargins().setAll(60f);
// 添加文档标题段落
Paragraph title_para = section.addParagraph();
TextRange textRange = title_para.appendText("这是标题");
title_para.applyStyle(BuiltinStyle.Title);
textRange.getCharacterFormat().setFontName("FangSong");
// 添加标题段落
Paragraph heading_one = section.addParagraph();
textRange = heading_one.appendText("一级标题");
heading_one.applyStyle(BuiltinStyle.Heading_1);
textRange.getCharacterFormat().setFontName("Times New Roman");
Paragraph heading_two = section.addParagraph();
textRange = heading_two.appendText("二级标题");
heading_two.applyStyle(BuiltinStyle.Heading_2);
textRange.getCharacterFormat().setFontName("Times New Roman");
Paragraph heading_three = section.addParagraph();
textRange = heading_three.appendText("三级标题");
heading_three.applyStyle(BuiltinStyle.Heading_3);
textRange.getCharacterFormat().setFontName("Times New Roman");
Paragraph heading_four = section.addParagraph();
textRange = heading_four.appendText("四级标题");
heading_four.applyStyle(BuiltinStyle.Heading_4);
textRange.getCharacterFormat().setFontName("Times New Roman");
// 添加普通段落
Paragraph normal_para = section.addParagraph();
normal_para.appendText("这是一个样本段落");
// 创建一个段落样式
ParagraphStyle style = new ParagraphStyle(document);
style.setName("paraStyle");
style.getCharacterFormat().setFontName("Times New Roman");
style.getCharacterFormat().setFontSize(13f);
style.getCharacterFormat().setTextColor(Color.blue);
document.getStyles().add(style);
// 应用自定义样式
normal_para.applyStyle("paraStyle");
// 保存文档
document.saveToFile("E:/Administrator/Python1/output/AddText.docx", FileFormat.Docx);
document.dispose();
}
}
在 Word 文档中插入图片
图片是文档中不可或缺的元素,Spire.Doc for Java 提供了方便的方法来插入图片并设置其属性。
arduino
import com.spire.doc.*;
import com.spire.doc.documents.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class AddImage {
public static void main(String[] args) throws IOException {
// 创建一个 Document 类的对象
Document document = new Document();
// 添加节
Section section = document.addSection();
// 设置页边距
section.getPageSetup().getMargins().setAll(60f);
// 添加段落
Paragraph image_para = section.addParagraph();
// 加载图片文件
BufferedImage image = ImageIO.read(new File("F:/备用图片/Logo1.png"));
// 将图片添加到段落中
image_para.appendPicture(image);
// 保存文档
document.saveToFile("E:/Administrator/Python1/output/AddImage.docx", FileFormat.Docx);
document.dispose();
}
}
注意: 请将 "F:/备用图片/Logo1.png" 替换为你的图片文件路径。
在 Word 文档中添加表格
表格是组织结构化数据的重要工具。Spire.Doc for Java 允许我们轻松创建和定制表格。
java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;
public class AddTable {
public static void main(String[] args) {
// 创建一个 Documennt 类的实例
Document document = new Document();
// 添加一个节
Section section = document.addSection();
// Set page margins 设置页边距
section.getPageSetup().getMargins().setAll(60f);
// 定义表格数据为二维数组
String[][] data = {
{"产品", "单价", "数量", "总价"},
{"1", "¥29", "120", "¥3480"},
{"2", "¥35", "110", "¥3850"},
{"3", "¥68", "140", "¥9520"}
};
// 添加一个表格
Table table = section.addTable(true);
// 设置行数和列数
table.resetCells(data.length, data[0].length);
// 将数据写入单元格
for (int r = 0; r < data.length; r++) {
TableRow row = table.getRows().get(r);
row.setHeight(20);
row.setHeightType(TableRowHeightType.Exactly);
for (int c = 0; c < data[r].length; c++) {
TableCell cell = row.getCells().get(c); cell.getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
TextRange textRange = cell.addParagraph().appendText(data[r][c]);
textRange.getCharacterFormat().setFontName("Times New Roman");
textRange.getCharacterFormat().setFontSize(14);
}
}
// 自动调整表格列宽以适应内容
table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Contents);
// 保存文档
document.saveToFile("E:/Administrator/Python1/output/AddTable.docx", FileFormat.Docx);
document.dispose();
}
}
在 Word 文档中添加列表
列表是组织信息、提高文档可读性的有效方式,Spire.Doc for Java 支持创建有序和无序列表。
scss
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;
public class AddList {
public static void main(String[] args) {
// 创建一个 Document类的对象
Document document = new Document();
// 添加节
Section section = document.addSection();
// 设置页边距
section.getPageSetup().getMargins().setAll(60f);
// 创建带符号的列表样式
ListStyle listStyle = new ListStyle(document, ListType.Bulleted);
listStyle.setName("bulletedList");
listStyle.getLevels().get(0).setBulletCharacter("\u00B7");
listStyle.getLevels().get(0).getCharacterFormat().setFontName("Symbol");
listStyle.getLevels().get(0).setTextPosition(20);
document.getListStyles().add(listStyle);
// 添加段落
Paragraph paragraph = section.addParagraph();
TextRange textRange = paragraph.appendText("水果:");
paragraph.getFormat().setAfterSpacing(5f);
textRange.getCharacterFormat().setFontName("Times New Roman");
textRange.getCharacterFormat().setFontSize(14);
// 添加4个段落作为带符号的列表项
String[] fruits = {"苹果", "香蕉", "西瓜", "芒果"};
for (String fruit : fruits) {
paragraph = section.addParagraph();
textRange = paragraph.appendText(fruit);
paragraph.getListFormat().applyStyle(listStyle.getName());
paragraph.getListFormat().setListLevelNumber(0);
textRange.getCharacterFormat().setFontName("Times New Roman");
textRange.getCharacterFormat().setFontSize(14);
}
// 保存文档
document.saveToFile("E:/Administrator/Python1/output/AddList.docx", FileFormat.Docx);
document.dispose();
}
}
总结
通过本教程,我们深入探讨了如何利用 Java 结合 Spire.Doc for Java 库来程序化地创建 Word 文档。我们学习了文档的基本结构搭建,包括添加标题、章节和带有格式的段落,还掌握了在文档中插入图片、创建和定制表格以及生成有序和无序列表的关键技术。这些功能覆盖了绝大多数日常文档生成需求,极大地提高了开发效率和文档处理的灵活性。
程序化生成 Word 文档不仅能减少重复性工作,还能确保文档内容的一致性和准确性,是自动化办公和报告生成不可或缺的一环。希望本教程能为您在 Java 文档处理的道路上提供有价值的指导。Spire.Doc for Java 还有许多高级功能,如邮件合并、文档转换、图表插入等,鼓励读者进一步探索,以应对更复杂的文档生成场景。