一、准备工作
- 引入依赖
- 官网下载 jar 包
- 或在 Maven 项目中添加依赖(如有对应 repository):
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>free.spire.doc</artifactId>
<version>5.2.0</version>
</dependency>
注意:免费版有页数限制,商业版无此限制。
- 导入包
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;
import java.awt.*;
二、详细开发案例
1. 创建文档并添加标题、正文
// 创建Word文档对象
Document doc = new Document();
// 添加节
Section section = doc.addSection();
// 添加标题段落
Paragraph title = section.addParagraph();
title.appendText("e-iceblue Java生成Word文档案例");
title.applyStyle(BuiltinStyle.Title);
title.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
// 添加正文段落
Paragraph para = section.addParagraph();
para.appendText("这是一个使用e-iceblue Free Spire.Doc for Java自动生成的Word文档示例,包含文本、表格和图片。");
para.getFormat().setFontName("微软雅黑");
para.getFormat().setFontSize(12f);
para.getFormat().setTextColor(Color.DARK_GRAY);
2. 添加表格
// 添加表格(3行3列)
Table table = section.addTable(true);
table.resetCells(3, 3);
// 填充表头
String[] headers = {"姓名", "性别", "分数"};
for (int i = 0; i < headers.length; i++) {
table.getRows().get(0).getCells().get(i).addParagraph().appendText(headers[i]);
}
// 填充内容
String[][] data = {
{"张三", "男", "90"},
{"李四", "女", "95"}
};
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
table.getRows().get(i + 1).getCells().get(j).addParagraph().appendText(data[i][j]);
}
}
// 设置表格样式
table.applyStyle(DefaultTableStyle.TableGrid);
3. 插入图片
// 新增图片段落
Paragraph imgPara = section.addParagraph();
imgPara.appendText("\n插入图片示例:");
// 插入图片(本地图片路径)
String imgPath = "D:/test.jpg";
DocPicture picture = imgPara.appendPicture(imgPath);
picture.setWidth(100);
picture.setHeight(100);
4. 保存文档
// 保存为docx格式
doc.saveToFile("output.docx", FileFormat.Docx_2013);
// 保存为doc格式
// doc.saveToFile("output.doc", FileFormat.Doc);
三、完整代码示例
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;
import java.awt.*;
public class SpireDocDemo {
public static void main(String[] args) {
// 创建文档对象
Document doc = new Document();
// 添加节
Section section = doc.addSection();
// 添加标题
Paragraph title = section.addParagraph();
title.appendText("e-iceblue Java生成Word文档案例");
title.applyStyle(BuiltinStyle.Title);
title.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
// 添加正文
Paragraph para = section.addParagraph();
para.appendText("这是一个使用e-iceblue Free Spire.Doc for Java自动生成的Word文档示例,包含文本、表格和图片。");
para.getFormat().setFontName("微软雅黑");
para.getFormat().setFontSize(12f);
para.getFormat().setTextColor(Color.DARK_GRAY);
// 添加表格
Table table = section.addTable(true);
table.resetCells(3, 3);
String[] headers = {"姓名", "性别", "分数"};
for (int i = 0; i < headers.length; i++) {
table.getRows().get(0).getCells().get(i).addParagraph().appendText(headers[i]);
}
String[][] data = {
{"张三", "男", "90"},
{"李四", "女", "95"}
};
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
table.getRows().get(i + 1).getCells().get(j).addParagraph().appendText(data[i][j]);
}
}
table.applyStyle(DefaultTableStyle.TableGrid);
// 插入图片
Paragraph imgPara = section.addParagraph();
imgPara.appendText("\n插入图片示例:");
String imgPath = "D:/test.jpg";
DocPicture picture = imgPara.appendPicture(imgPath);
picture.setWidth(100);
picture.setHeight(100);
// 保存文档
doc.saveToFile("output.docx", FileFormat.Docx_2013);
System.out.println("Word文档生成成功!");
}
}
四、常见扩展功能
- 段落对齐、加粗、斜体、下划线等格式设置
- 添加页眉页脚
- 插入超链接、书签、页码
- 多节、多页文档处理
- 批量生成(如循环生成多份文档)
1. 添加页眉和页脚
// 创建文档对象
Document doc = new Document();
Section section = doc.addSection();
// 添加页眉
HeaderFooter header = section.getHeadersFooters().getHeader();
Paragraph headerPara = header.addParagraph();
headerPara.appendText("公司机密 - 仅供内部使用");
headerPara.getFormat().setHorizontalAlignment(HorizontalAlignment.Right);
// 添加页脚
HeaderFooter footer = section.getHeadersFooters().getFooter();
Paragraph footerPara = footer.addParagraph();
footerPara.appendText("第 ");
footerPara.appendField("页码", FieldType.Field_Page);
footerPara.appendText(" 页,共 ");
footerPara.appendField("总页数", FieldType.Field_Num_Pages);
footerPara.appendText(" 页");
footerPara.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
// 保存文档
doc.saveToFile("headerFooter.docx", FileFormat.Docx_2013);
2. 批量生成文档(如批量生成成绩单)
String[] names = {"张三", "李四", "王五"};
int[] scores = {90, 95, 88};
for (int i = 0; i < names.length; i++) {
Document doc = new Document();
Section section = doc.addSection();
Paragraph para = section.addParagraph();
para.appendText("学生成绩单");
para.applyStyle(BuiltinStyle.Heading1);
Paragraph info = section.addParagraph();
info.appendText("姓名:" + names[i] + "\n分数:" + scores[i]);
// 保存每个学生的成绩单
doc.saveToFile(names[i] + "_成绩单.docx", FileFormat.Docx_2013);
}
3. 模板填充(替换占位符)
假设有一个模板文件 template.docx,内容如:
姓名:[Name]
成绩:[Score]
Document doc = new Document();
doc.loadFromFile("template.docx");
// 替换占位符
doc.replace("[Name]", "张三", false, true);
doc.replace("[Score]", "90", false, true);
// 保存
doc.saveToFile("filled.docx", FileFormat.Docx_2013);
4. 合并多个文档
// 主文档
Document mainDoc = new Document();
mainDoc.loadFromFile("part1.docx");
// 待合并文档
Document doc2 = new Document();
doc2.loadFromFile("part2.docx");
// 合并
for (Section sec : (Iterable<Section>) doc2.getSections()) {
mainDoc.getSections().add(sec.deepClone());
}
// 保存合并后的文档
mainDoc.saveToFile("merged.docx", FileFormat.Docx_2013);
5. 目录(Table of Contents)自动生成
Document doc = new Document();
Section section = doc.addSection();
// 插入目录域
Paragraph tocPara = section.addParagraph();
tocPara.appendTOC(1, 3); // 目录级别1-3
// 添加内容
for (int i = 1; i <= 3; i++) {
Paragraph heading = section.addParagraph();
heading.appendText("第" + i + "章 标题");
heading.applyStyle(BuiltinStyle.Heading1);
Paragraph content = section.addParagraph();
content.appendText("这是第" + i + "章的内容。");
}
// 更新目录(保存后在Word里右键更新即可)
doc.saveToFile("toc.docx", FileFormat.Docx_2013);
6. 插入超链接、书签
Document doc = new Document();
Section section = doc.addSection();
Paragraph para = section.addParagraph();
para.appendText("访问 e-iceblue 官网:");
para.appendHyperlink("https://www.e-iceblue.com/", "点击这里", HyperlinkType.WebLink);
// 插入书签
Paragraph bookmarkPara = section.addParagraph();
bookmarkPara.appendText("这是书签位置。");
bookmarkPara.appendBookmarkStart("MyBookmark");
bookmarkPara.appendText("(书签内容)");
bookmarkPara.appendBookmarkEnd("MyBookmark");
// 保存
doc.saveToFile("hyperlink_bookmark.docx", FileFormat.Docx_2013);
7. 插入分页符、分节符
Document doc = new Document();
Section section = doc.addSection();
section.addParagraph().appendText("第一页内容。");
// 插入分页符
section.addParagraph().appendBreak(BreakType.PageBreak);
section.addParagraph().appendText("第二页内容。");
// 插入分节符
section.addParagraph().appendBreak(BreakType.SectionBreak_NewPage);
// 新节
Section section2 = doc.addSection();
section2.addParagraph().appendText("新节内容。");
doc.saveToFile("breaks.docx", FileFormat.Docx_2013);
8. 自动化批量生成复杂报表(示例思路)
假如有员工数据列表,批量生成每人一份带表格和图片的报表:
class Employee {
String name;
String dept;
int score;
String photoPath;
// 构造函数省略
}
List<Employee> employees = Arrays.asList(
new Employee("张三", "销售部", 90, "photo1.jpg"),
new Employee("李四", "技术部", 95, "photo2.jpg")
);
for (Employee emp : employees) {
Document doc = new Document();
Section section = doc.addSection();
section.addParagraph().appendText(emp.name + " 报表").applyStyle(BuiltinStyle.Heading1);
Table table = section.addTable(true);
table.resetCells(2, 2);
table.getRows().get(0).getCells().get(0).addParagraph().appendText("部门");
table.getRows().get(0).getCells().get(1).addParagraph().appendText("分数");
table.getRows().get(1).getCells().get(0).addParagraph().appendText(emp.dept);
table.getRows().get(1).getCells().get(1).addParagraph().appendText(String.valueOf(emp.score));
Paragraph imgPara = section.addParagraph();
imgPara.appendText("照片:");
DocPicture pic = imgPara.appendPicture(emp.photoPath);
pic.setWidth(80);
pic.setHeight(80);
doc.saveToFile(emp.name + "_报表.docx", FileFormat.Docx_2013);
}
9. 复杂模板填充(表格动态填充 + 条件判断)
假设你的模板 template.docx 里有一个表格,第一行是表头,后续行用于填充数据。我们希望根据数据动态添加行,并实现条件判断(如分数及格/不及格显示不同颜色)。
步骤:
- 加载模板文档
- 查找目标表格
- 动态添加数据行,根据条件设置单元格样式
- 保存
代码示例
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;
import java.awt.*;
import java.util.*;
class Student {
String name;
int score;
Student(String name, int score) { this.name = name; this.score = score; }
}
public class FillTableWithCondition {
public static void main(String[] args) {
// 假设已有模板 template.docx
Document doc = new Document();
doc.loadFromFile("template.docx");
// 假设第一个表格就是我们要填充的表格
Table table = doc.getSections().get(0).getTables().get(0);
// 学生数据
List<Student> students = Arrays.asList(
new Student("张三", 90),
new Student("李四", 59),
new Student("王五", 76)
);
// 从第二行开始插入数据
for (Student stu : students) {
TableRow row = table.addRow();
row.addCell().addParagraph().appendText(stu.name);
TableCell scoreCell = row.addCell();
Paragraph scorePara = scoreCell.addParagraph().appendText(String.valueOf(stu.score));
// 条件判断:分数低于60显示红色
if (stu.score < 60) {
scorePara.getFormat().setTextColor(Color.RED);
} else {
scorePara.getFormat().setTextColor(Color.BLACK);
}
}
// 保存
doc.saveToFile("filled_table.docx", FileFormat.Docx_2013);
}
}
10. 批量导出为 PDF
e-iceblue 支持直接将 Word 文档批量导出为 PDF,非常适合批量报告、合同等场景。
代码示例
String[] docFiles = {"file1.docx", "file2.docx", "file3.docx"};
for (String file : docFiles) {
Document doc = new Document();
doc.loadFromFile(file);
String pdfName = file.replace(".docx", ".pdf");
doc.saveToFile(pdfName, FileFormat.PDF);
}
11. 生成多级目录和标题(自动化报告)
如果你有多级章节(如章、节、小节),可以通过 Heading1/Heading2/Heading3 样式生成多级目录。
代码示例
Document doc = new Document();
Section section = doc.addSection();
// 插入目录
Paragraph tocPara = section.addParagraph();
tocPara.appendTOC(1, 3); // 目录级别1-3
// 第一章
Paragraph h1 = section.addParagraph();
h1.appendText("第一章 概述");
h1.applyStyle(BuiltinStyle.Heading1);
Paragraph h2 = section.addParagraph();
h2.appendText("1.1 背景");
h2.applyStyle(BuiltinStyle.Heading2);
Paragraph h3 = section.addParagraph();
h3.appendText("1.1.1 相关工作");
h3.applyStyle(BuiltinStyle.Heading3);
// 第二章
Paragraph h1_2 = section.addParagraph();
h1_2.appendText("第二章 方法");
h1_2.applyStyle(BuiltinStyle.Heading1);
// 内容略...
// 保存
doc.saveToFile("multi_level_toc.docx", FileFormat.Docx_2013);
保存后在Word里右键目录可自动刷新。
12. 业务场景架构建议
场景一:批量生成合同/报告
- 数据层:数据库或Excel获取数据
- 模板层:Word模板,含占位符和表格
- 填充层:Java代码循环填充
- 导出层:批量导出Word/PDF
- 接口层:Web API或定时任务
场景二:复杂报表自动化
- 多级标题、目录自动生成
- 表格动态填充,支持条件样式
- 支持插入图片、页眉页脚、签名
- 可扩展为批量邮件发送、归档
场景三:合同、协议自动生成
- 支持模板填充、批量生成
- 支持水印、页码、签章
- 支持合并文档、拆分文档
13. 其他高级功能补充
插入水印
Document doc = new Document();
doc.loadFromFile("input.docx");
TextWatermark watermark = new TextWatermark();
watermark.setText("仅供内部");
watermark.setFontSize(40);
watermark.setColor(Color.LIGHT_GRAY);
doc.setWatermark(watermark);
doc.saveToFile("watermarked.docx", FileFormat.Docx_2013);
插入签名图片
Document doc = new Document();
Section section = doc.addSection();
Paragraph para = section.addParagraph();
para.appendText("签名:");
DocPicture pic = para.appendPicture("signature.png");
pic.setWidth(120);
pic.setHeight(60);
doc.saveToFile("signed.docx", FileFormat.Docx_2013);
插入页码(页脚)
Document doc = new Document();
Section section = doc.addSection();
HeaderFooter footer = section.getHeadersFooters().getFooter();
Paragraph p = footer.addParagraph();
p.appendField("页码", FieldType.Field_Page);
doc.saveToFile("page_number.docx", FileFormat.Docx_2013);
创作不易,点赞关注,感谢支持,互通有无!

408

被折叠的 条评论
为什么被折叠?



