1.Spire.doc包的导入
Spire.doc比较小众,因此需要在pom.xml中导入spire.doc的仓库,导入之后直接导包
<!--导入Spire-->
<repositories>
<repository>
<id>com.e-iceblue</id>
<url>https://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
</repositories>
导入仓库后进行导包
<!--spire.doc 操作word文档-->
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc.free</artifactId>
<version>3.9.0</version>
</dependency>
2.spire.doc的使用
2.1文字替换
2.1.1模板
首先需要准备一个word模板,可以在里面进行文字替换,因为文字特别多,所以此处采用了对具有特殊符号的文字进行替换。此处采用 ${xxx}
模板如图所示:
2.1.2替换核心代码
下面代码是替换的核心代码,写了一个单独的方法
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文字替换测试代码
下面是测试代码,读取文件,进行替换
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下载代码
替换后浏览器下载,其中response是HttpServletRequest进行文件传输
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();
}
替换的结果如图所示
2.2图片替换
2.2.1图片模板
2.2.2 图片替换核心代码
图片替换更加简单,其中image与模板中的image相同
//图片保存测试
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.打印表格
2.3.1 书签设置
打印表格需设置书签
将table放入word的标签,否者会将表格自动生成在word文档最后
2.3.2 核心代码
//表格替换
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("表格打印成功!!!");