一、引入依赖
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.office</artifactId>
<version>7.5.4</version>
</dependency>
二、word操作
1、合并word文档
import com.spire.doc.Document;
import com.spire.doc.DocumentObject;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
/**
* 合并Word文档
*
* @Description
* @Author ROC_WL
* @Date 2024/3/8
**/
public class MergerDocxTest {
public static void main(String[] args) {
//创建document对象
Document document = new Document("D:\\temp\\document-blank.docx");//读取一个空的Word文档
//加载一个需要写入的Word文档
Document doc1 = new Document("D:\\temp\\document1.docx");
for (int i = 0; i < doc1.getSections().getCount(); i++) {
Section s = doc1.getSections().get(i);
for (int j = 0; j < s.getBody().getChildObjects().getCount(); j++) {
//获取文档中的段落和表格
DocumentObject obj = s.getBody().getChildObjects().get(j);
//将文档中的段落和表格插入到新的文档中
document.getLastSection().getBody().getChildObjects().add(obj.deepClone());
}
}
//循环写入
for (int x = 0; x < 2; x++) {
Document doc2 = new Document("D:\\temp\\document2.docx");
for (int i = 0; i < doc2.getSections().getCount(); i++) {
Section s = doc2.getSections().get(i);
for (int j = 0; j < s.getBody().getChildObjects().getCount(); j++) {
DocumentObject obj = s.getBody().getChildObjects().get(j);
document.getLastSection().getBody().getChildObjects().add(obj.deepClone());
}
}
}
//保存文档
document.saveToFile("D:\\temp\\mergerDocx.docx", FileFormat.Docx_2013);
}
}
2、插入文字、图片、表格、富文本
import com.example.utils.DocxUtil;
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.DocPicture;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
/**
* TODO
*
* @Description
* @Author WL
* @Date 2024/2/28
**/
public class DocxAddParagraphTest {
public static void main(String[] args) {
//创建document对象
Document document = new Document("D:\\temp\\document-blank.docx");
//获取最后一个section
Section newSec = document.getLastSection();
//添加文本
Paragraph textParagtaph = newSec.addParagraph();
//设置文本格式
ParagraphStyle styleContent = new ParagraphStyle(document);
styleContent.setName("codeStyle");
styleContent.getCharacterFormat().setFontName("宋体");
styleContent.getCharacterFormat().setFontSize(10f);
styleContent.getParagraphFormat().setHorizontalAlignment(HorizontalAlignment.Left);
document.getStyles().add(styleContent);
textParagtaph.applyStyle("codeStyle");
textParagtaph.appendText("第01号");
Paragraph text1Paragtaph = newSec.addParagraph();
//设置文本格式
ParagraphStyle styleTitle = new ParagraphStyle(document);
//设置样式名称
styleTitle.setName("titleStyle");
//设置字体
styleTitle.getCharacterFormat().setFontName("宋体");
//设置字体大小
styleTitle.getCharacterFormat().setFontSize(20f);
//设置文本颜色
styleTitle.getCharacterFormat().setTextColor(Color.CYAN);
//设置文本居中
styleTitle.getParagraphFormat().setHorizontalAlignment(HorizontalAlignment.Center);
//添加样式到文档
document.getStyles().add(styleTitle);
//应用样式
text1Paragtaph.applyStyle("titleStyle");
//添加文本
text1Paragtaph.appendText("关于******公告");
//添加文本
Paragraph textPeoParagtaph = newSec.addParagraph();
//设置文本格式
ParagraphStyle stylePeoContent = new ParagraphStyle(document);
stylePeoContent.setName("peoStyle");
stylePeoContent.getCharacterFormat().setFontName("宋体");
stylePeoContent.getCharacterFormat().setFontSize(12f);
stylePeoContent.getParagraphFormat().setHorizontalAlignment(HorizontalAlignment.Left);
document.getStyles().add(stylePeoContent);
textPeoParagtaph.applyStyle("peoStyle");
textPeoParagtaph.appendText("姓名:姜XX\t\t\t手机号码:13866669999");
//添加文本
Paragraph textAddParagtaph = newSec.addParagraph();
//设置文本格式
ParagraphStyle styleAddContent = new ParagraphStyle(document);
styleAddContent.setName("addStyle");
styleAddContent.getCharacterFormat().setFontName("宋体");
styleAddContent.getCharacterFormat().setFontSize(12f);
styleAddContent.getParagraphFormat().setHorizontalAlignment(HorizontalAlignment.Left);
document.getStyles().add(styleAddContent);
textAddParagtaph.applyStyle("addStyle");
textAddParagtaph.getFormat().setFirstLineIndent(30f);
textAddParagtaph.appendText("联系地址:湖北武汉");
//添加表格
List<String> headerList = new ArrayList<>();
headerList.add("姓名");
headerList.add("电话");
headerList.add("地址");
List<List<Object>> dataList = new ArrayList<>();
List<Object> data1 = new ArrayList<>();
data1.add("姜XX");
data1.add("18899996666");
data1.add("浙江");
dataList.add(data1);
List<Object> data2 = new ArrayList<>();
data2.add("tj");
data2.add("15549490011");
data2.add("杭州");
dataList.add(data2);
List<Object> data3 = new ArrayList<>();
data3.add("赵XX");
data3.add("135****713");
data3.add("武汉");
dataList.add(data3);
String tableTitle = "表格标题";
DocxUtil.createTable(newSec, headerList, dataList, tableTitle);
//添加图片
// 创建 DocPicture 类的对象
DocPicture picture = new DocPicture(document);
// 从磁盘加载图片
String images = "D:\\temp\\123.jpg";
picture.loadImage(images);
// 设置图片大小
picture.setWidth(180); //示例:80
picture.setHeight(180);//示例:50
picture.setHorizontalPosition(110); //示例:110.0F 水平位置
picture.setVerticalPosition(220); //示例:110.0F 垂直位置
Paragraph picParagraph = newSec.addParagraph();
picParagraph.getChildObjects().add(picture);
//添加图片
// 创建 DocPicture 类的对象
DocPicture picture1 = new DocPicture(document);
// 从磁盘加载图片
String images1 = "D:\\temp\\321.jpg";
picture1.loadImage(images1);
// 设置图片大小
picture1.setWidth(500); //示例:80
picture1.setHeight(180);//示例:50
picture1.setHorizontalPosition(110); //示例:110.0F 水平位置
picture1.setVerticalPosition(220); //示例:110.0F 垂直位置
Paragraph picParagraph1 = newSec.addParagraph();
picParagraph1.getChildObjects().add(picture1);
//添加富文本
Paragraph tempSectionContentParagraph = newSec.addParagraph();
String htmlContent = "<p>Spire.Doc for Java 是一款专业的 Java Word 组件,开发人员使用它可以轻松地将 Word 文档创建、读取、编辑、转换和打印等功能集成到自己的 Java 应用程序中。作为一款完全独立的组件,Spire.Doc for Java 的运行环境无需安装 Microsoft Office。</p>
<p>Spire.Doc for Java 能执行多种 Word 文档处理任务,包括生成、读取、转换和打印 Word 文档,插入图片,添加页眉和页脚,创建表格,添加表单域和邮件合并域,添加书签,添加文本和图片水印,设置背景颜色和背景图片,添加脚注和尾注,添加超链接,加密和解密 Word 文档,添加批注,添加形状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j1rfs+ebbfs5XM4Dzwv01iotOidaqBaRH1Jw+Lj49G1cuEsXsMcFG0krDqqwakFaxLxKAWLHzoUyc3//g0O/FdFkneEBmuhmqi2Zn6FV0Mc52zGTH6JoN5ulrQjzzP21ahVfAdXS7ymbvwR7lm5gcQHXQuK2GAncGpszMk5KtSzZoZ6n4NqlW5jhPRbtBfqU1gch2h0bPTm6q+NjIr1rFp1ottBERynRqy1ESg6JgYL2ItuCbrvuHutgrBEoXYFOlcmric2l80vbN7v5j33WoVgxWLGUZzar3UzIqc2rNGp1aVQ4dWN7qOW4dZ7+CPp0whuoJ6PQwonxlR9vwM2sOg81pCvW+WwhD/S/tEHuz4btKxy/fh9G8Kw7our7+b6Eydt4FP1Ax2wYQCbShdKp2StCg1D2aTdqtewJL5ZobttiXxKUvrZHW8OvuMMFrZKgHdtj+Gl45tBvwbg5iEUsDhj0xmrNOVmcuNxfEVyAe/jTm481qrtUAxDg7ProgXLaEVziupCAQvNyqzKMlpRDkK6sMASMksiWw6scF4RYcfBEikqKI2GJUFWw9KwJAhISHXP0rAkCEhIdc/SsCQISEh1z9KwJAhISD33LHxisCbRXiikqp49w8I/YrNCQUDGhKJnz7B6YvjSbYd9VD17hrVvofQXPumkP4vriA95Jc8qZj3DokZj27YfwydSrj8hqRgLJAY9Ol4Vk/sCa/j6vzeBG2151CtVN3p0vEoF3RP7AovSZQrFj/A9k0nsYev30odky/FkTN71qO7JN1hkgcxEo5E0/nuUTxHaNZwfbqtb8xbptE2vHKAX8uQVlDc3OloT0AQ0AU1AE+gWAncAtcuNfiX0sWkAAAAASUVORK5CYII=" alt="" width="75" height="75" /></p>";
htmlContent=htmlContent+"<p> </p>";
tempSectionContentParagraph.appendHTML(htmlContent);
//添加文本
Paragraph text3Paragtaph = newSec.addParagraph();
ParagraphStyle styleContent3 = new ParagraphStyle(document);
styleContent3.setName("codeStyle3");
styleContent3.getCharacterFormat().setFontName("宋体");
styleContent3.getCharacterFormat().setFontSize(15f);
document.getStyles().add(styleContent3);
text3Paragtaph.applyStyle("codeStyle3");
text3Paragtaph.appendText("第02号");
Paragraph text4Paragtaph = newSec.addParagraph();
//设置文本格式
ParagraphStyle styleTitle4 = new ParagraphStyle(document);
styleTitle4.setName("titleStyle4");
styleTitle4.getCharacterFormat().setFontName("宋体");
styleTitle4.getCharacterFormat().setFontSize(25f);
styleTitle4.getCharacterFormat().setTextColor(Color.ORANGE);
styleTitle4.getParagraphFormat().setHorizontalAlignment(HorizontalAlignment.Center);
document.getStyles().add(styleTitle4);
text4Paragtaph.applyStyle("titleStyle4");
text4Paragtaph.appendText("关于***************************Text");
DocxUtil.insertHeaderAndFooter(newSec);
document.saveToFile("D:\\temp\\documentNew.docx", FileFormat.Docx_2013);
}
}
使用到的工具
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.TextRange;
import java.awt.*;
import java.security.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* TODO
*
* @Description
* @Author WL
* @Date 2024/2/28
**/
public class DocxUtil {
// 动态创建表格
public static void createTable(Section section, List<String> header, List<List<Object>> data, String title) {
//添加表格
Table table = section.addTable(true);
//设置表格的行数和列数
table.resetCells(data.size()+ 2, header.size());
//设置第一行作为表格的表头并添加数据
TableRow row = table.getRows().get(1);
row.isHeader(true);
row.setHeight(40);
row.setHeightType(TableRowHeightType.Exactly);
TableRow row3 = table.getRows().get(0);
row3.isHeader(true);
row3.setHeight(60);
row3.setHeightType(TableRowHeightType.Exactly);
row3.getCells().get(0).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
table.applyHorizontalMerge(0, 0, header.size() - 1);
Paragraph p1 = row3.getCells().get(0).addParagraph();
p1.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
TextRange range3 = p1.appendText(title);
range3.getCharacterFormat().setFontName("仿宋_GB2312");
range3.getCharacterFormat().setFontSize(12f);
range3.getCharacterFormat().setTextColor(Color.black);
range3.getCharacterFormat().setBold(true);
for (int i = 0; i < header.size(); i++) {
row.getCells().get(i).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
Paragraph p = row.getCells().get(i).addParagraph();
p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
TextRange range1 = p.appendText(header.get(i));
range1.getCharacterFormat().setTextColor(Color.black);
range1.getCharacterFormat().setFontName("仿宋_GB2312");
range1.getCharacterFormat().setFontSize(12f);
range1.getCharacterFormat().setBold(true);
}
//添加数据到剩余行
try{
for (int r = 0; r < data.size(); r++) {
TableRow dataRow = table.getRows().get(r + 2);
dataRow.setHeight(25);
dataRow.setHeightType(TableRowHeightType.Exactly);
dataRow.getRowFormat().setBackColor(Color.white);
for (int c = 0; c < data.get(r).size(); c++) {
dataRow.getCells().get(c).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
String s = "";
if (data.get(r).get(c) instanceof Timestamp) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//定义格式,不显示毫秒
s = df.format((Timestamp) (data.get(r).get(c)));
} else if (data.get(r).get(c) instanceof Date) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//定义格式,不显示毫秒
s = df.format((Date) (data.get(r).get(c)));
} else if (data.get(r).get(c) == null) {
s = "";
} else {
s = data.get(r).get(c).toString();
}
TextRange range2 = dataRow.getCells().get(c).addParagraph().appendText(s);
range2.getCharacterFormat().setFontName("仿宋_GB2312");
range2.getCharacterFormat().setFontSize(10f);
}
}
}catch (Exception e){
e.getMessage();
// log.info("插入数据有异常");
}
section.addParagraph();
}
//生成页眉和页脚
public static void insertHeaderAndFooter(Section section) {
//分别获取section的页眉页脚
HeaderFooter header = section.getHeadersFooters().getHeader();
HeaderFooter footer = section.getHeadersFooters().getFooter();
//添加段落到页眉
Paragraph headerParagraph = header.addParagraph();
//添加文字到页眉的段落
TextRange text = headerParagraph.appendText("页眉测试");
text.getCharacterFormat().setFontName("仿宋_GB2312");
text.getCharacterFormat().setFontSize(10);
text.getCharacterFormat().setItalic(true);
headerParagraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Left);
//设置页眉段落的底部边线样式
headerParagraph.getFormat().getBorders().getBottom().setBorderType(BorderStyle.Single);
headerParagraph.getFormat().getBorders().getBottom().setLineWidth(1f);
//添加段落到页脚
Paragraph footerParagraph = footer.addParagraph();
//添加Field_Page和Field_Num_Pages域到页脚段落,用于显示当前页码和总页数
footerParagraph.appendField("page number", FieldType.Field_Page);
footerParagraph.appendText("/");
footerParagraph.appendField("number of pages", FieldType.Field_Num_Pages);
footerParagraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Right);
//设置页脚段落的顶部边线样式
footerParagraph.getFormat().getBorders().getTop().setBorderType(BorderStyle.Single);
footerParagraph.getFormat().getBorders().getTop().setLineWidth(1f);
}
}