1. Import of Spire.doc package
Spire.doc is relatively small, so you need to import the warehouse of spire.doc in pom.xml, and import the package directly after importing
<!--导入Spire-->
<repositories>
<repository>
<id>com.e-iceblue</id>
<url>https://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
</repositories>
Import the package after importing the warehouse
<!--spire.doc 操作word文档-->
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc.free</artifactId>
<version>3.9.0</version>
</dependency>
2. Use of spire.doc
2.1 Text Replacement
2.1.1 Templates
First of all, you need to prepare a word template, and you can replace text in it. Because there are so many texts, the text with special symbols is used here to replace the text. The ${xxx} template is used here
as shown in the figure:
2.1.2 Replace the core code
The following code is the core code of the replacement, and a separate method is written
public void replaceSpecialWord(Document doc, Map<String, String> map) {
// 正则表达式,匹配所有的占位符 ${}
Pattern pattern = Pattern.compile("\\$\\{.*?}");
// 根据正则表达式获取所有文本
TextSelection[] allPattern = doc.findAllPattern(pattern);
// 逐个替换占位符
for (TextSelection textSelection : allPattern) {
String tmp = map.get(textSelection.getSelectedText());
System.out.print(textSelection.getSelectedText());
int res = doc.replace(textSelection.getSelectedText(), tmp, true, true);
System.out.println(":" + res);
}
log.info("替换完成?");
}
2.1.3 Text replacement test code
The following is the test code, read the file and replace it
Document doc = new Document();
doc.loadFromFile("E:\\java\\demo\\work\\src\\main\\resources\\static\\spireTest.docx", FileFormat.Docx);
Map<String, String> map = new HashMap<>();
//普通替换
map.put("${name}", "张山");
replaceSpecialWord(doc, map);//字符替换
2.1.4 Download code
Browser download after replacement, where response is HttpServletRequest for file transfer
String fileName="spireTest_"+new Date().getTime()+".docx";
try {
response.setHeader("content-disposition","attachment;filename="+new String(fileName.getBytes(),"ISO8859-1"));
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
doc.saveToStream(response.getOutputStream(), FileFormat.Docx);
} catch (Exception e) {
e.printStackTrace();
}
The result of the replacement is shown in Fig.
2.2 Image Replacement
2.2.1 Image template
2.2.2 Image replacement core code
Image replacement is simpler, where the image is the same as the image in the template
//图片保存测试
TextSelection[] textSelection = doc.findAllString("image",true,false);
int index ;
//加载图片替换文本字符串
for (Object obj : textSelection) {
TextSelection Selection = (TextSelection)obj;
DocPicture pic = new DocPicture(doc);
pic.loadImage("E:\\java\\demo\\work\\src\\main\\resources\\static\\aaa.jpg");
TextRange range = Selection.getAsOneRange();
index = range.getOwnerParagraph().getChildObjects().indexOf(range);
range.getOwnerParagraph().getChildObjects().insert(index,pic);
range.getOwnerParagraph().getChildObjects().remove(range);
}
3. Print the form
2.3.1 Bookmark Settings
To print the form, you need to set a bookmark.
Put the table into the word label, otherwise the form will be automatically generated at the end of the word document
2.3.2 Core code
//表格替换
List<P1Domain> p1DomainList=new ArrayList<>();
P1Domain p1Domain=new P1Domain();
for(int i=0;i<10;i++){
p1Domain.setH(1.0);
p1Domain.setId(Integer.toUnsignedLong(i));
p1Domain.setPci(2.0);
p1Domain.setPd(3.0);
p1DomainList.add(p1Domain);
}
String[] header={
"h","id","pci","pd"};
Section sec = doc.addSection();
Table table=sec.addTable(true);
table.resetCells(p1DomainList.size() + 1, header.length);
TableRow row = table.getRows().get(0);
row.isHeader(true);
row.setHeight(20);
row.setHeightType(TableRowHeightType.Exactly);
row.getRowFormat().setBackColor(Color.white);
//绘制表头
for (int i = 0; i < header.length; 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[i]);
range1.getCharacterFormat().setFontName("Arial");
range1.getCharacterFormat().setFontSize(12f);
range1.getCharacterFormat().setBold(true);
range1.getCharacterFormat().setTextColor(Color.BLACK);
}
//写入剩余组内容到表格,并格式化数据
for (int r = 0; r < p1DomainList.size(); r++) {
TableRow dataRow = table.getRows().get(r + 1);
dataRow.setHeight(25);
dataRow.setHeightType(TableRowHeightType.Exactly);
dataRow.getRowFormat().setBackColor(Color.white);
for (int c = 0; c < header.length; c++) {
dataRow.getCells().get(c).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
TextRange range2 = dataRow.getCells().get(c).addParagraph().appendText(Double.toString(p1DomainList.get(r).getH()));
range2.getOwnerParagraph().getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
range2.getCharacterFormat().setFontName("Arial");
range2.getCharacterFormat().setFontSize(10f);
}
}
log.info("表格打印成功!!!");