一、依赖添加
建议使用本小编的依赖,下载地址方式见请点击这里,手动添加到本地依赖
<dependency>
<groupId> e-iceblue </groupId>
<artifactId>spire.doc</artifactId>
<version>3.2.3</version>
</dependency>
倘若你使用官网其他版本的话你需要加上maven库,以访问下载
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
二、替换标签类
本小编将替换文本和图片的分成了两个方法,以及替换表格的替换的。可以参考本博进行代码修改一块保存。其中filepath是存储路径,docurl是文本路径,map是存的标签和要插入的内容,filename是与保存文件名称
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Table;
import com.spire.doc.TableRow;
import com.spire.doc.documents.*;
import com.spire.doc.fields.TextRange;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class WordUtil {
//图片替换文档内标签
public String ReplaceBookmarkWithImg (String filePath, String docUrl, Map<String,String> con, String fileName) {
//加载包含书签的文档
Document doc = new Document();
doc.loadFromFile(docUrl);
Iterator iter = con.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String lable = entry.getKey().toString();
String content = entry.getValue().toString();
//定位到指定书签位置
BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(doc);
bookmarksNavigator.moveToBookmark(lable, true, true);
//添加图片,替换原有书签内容
Paragraph para = new Paragraph(doc);
para.appendPicture(content);
TextBodyPart bodyPart = new TextBodyPart(doc);
bodyPart.getBodyItems().add(para);
bookmarksNavigator.replaceBookmarkContent(bodyPart);
}
//保存文档
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String nowDate = format.format(new Date());
String docInfo = filePath+"/"+ fileName + ".docx";
String pdfInfo = filePath+"/"+ fileName+"123" + ".pdf";
String pdfName = fileName + ".pdf";
//保存doc文档
doc.saveToFile(docInfo, FileFormat.Docx_2013);
//保存pdf文档__需要花钱
doc.saveToFile(pdfInfo, FileFormat.PDF);
//word转pdf
//WordToPdf wordToPdf = new WordToPdf();
//wordToPdf.changeType(docInfo,pdfInfo);
doc.dispose();
return pdfName;
}
//文字替换标签
public String ReplaceBookmarkContentWithNewContent(String filePath, String docUrl, Map<String,String> con){
System.out.println("进入文字替换方法");
//创建文档对象
Document doc = new Document();
//加载包含书签的Word文档
doc.loadFromFile(docUrl);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String nowDate = format.format(new Date());
String docInfo = filePath+"/"+nowDate + ".docx";
Iterator iter = con.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String lable = entry.getKey().toString();
String content = entry.getValue().toString();
//定位到指定书签位置
BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(doc);
bookmarksNavigator.moveToBookmark(lable);
//用文本内容替换原有书签位置的文本,新替换的内容与原文格式一致
bookmarksNavigator.replaceBookmarkContent(content, true);
}
//保存文档
doc.saveToFile(docInfo,FileFormat.Docx_2013);
doc.dispose();
return docInfo;
}
//延伸方法:在标签处插入表格
/**
*
* @param docUrl 文件路径
* @param bookmark 预插入表格书签
* @param data 数据结构
* @param filePath 目标文件存储路径
* @return
*/
public String ReplaceBookmarkContentWithTable(String docUrl,String bookmark,String[][]data,String filePath) {
//加载包含书签的Word文档
Document doc = new Document();
doc.loadFromFile(docUrl);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String nowDate = format.format(new Date());
String docInfo = filePath+"/"+nowDate + ".docx";
/***************-表格生成-*****************/
//创建表格
int rowNum = data.length;
int columnsNum = data[0].length;
Table table = new Table(doc, true);
table.resetCells(rowNum, columnsNum);
for (int i = 0; i < data.length; i++) {
TableRow dataRow = table.getRows().get(i);
int len = data[i].length;
for (int j = 0; j < data[i].length; j++) {
TextRange range = dataRow.getCells().get(j).addParagraph().appendText(data[i][j]);
range.getOwnerParagraph().getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
range.getCharacterFormat().setFontName("楷体");
dataRow.getRowFormat().setHorizontalAlignment(RowAlignment.Center);
dataRow.getCells().get(j).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
}
}
//创建TextBodyPart对象
TextBodyPart bodyPart= new TextBodyPart(doc);
bodyPart.getBodyItems().add(table);
//定位到指定书签位置
BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(doc);
bookmarkNavigator.moveToBookmark(bookmark);
//使用表格替换原书签的内容
bookmarkNavigator.replaceBookmarkContent(bodyPart);
//保存文档
doc.saveToFile(docInfo, FileFormat.Docx);
doc.dispose();
return docInfo;
}
//在标签处插入表格
public void ReplaceBookmarkContentWithTableCompany(String docUrl, Map<String,List<List<String>>> tableListMap) {
//加载包含书签的Word文档
Document doc = new Document();
doc.loadFromFile(docUrl);
for(String key : tableListMap.keySet()){
List<List<String>> tableList = tableListMap.get(key);
//创建表格
Table table = new Table(doc, true);
table.resetCells(tableList.size(), tableList.get(0).size());
for (int i = 0; i < tableList.size(); i++) {
TableRow dataRow = table.getRows().get(i);
for (int j = 0; j < tableList.get(i).size(); j++) {
TextRange range = dataRow.getCells().get(j).addParagraph().appendText(tableList.get(i).get(j));
range.getOwnerParagraph().getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
range.getCharacterFormat().setFontName("楷体");
dataRow.getRowFormat().setHorizontalAlignment(RowAlignment.Center);
dataRow.getCells().get(j).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
}
}
//创建TextBodyPart对象
TextBodyPart bodyPart= new TextBodyPart(doc);
bodyPart.getBodyItems().add(table);
//定位到指定书签位置
BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(doc);
bookmarkNavigator.moveToBookmark(key);
//使用表格替换原书签的内容
bookmarkNavigator.replaceBookmarkContent(bodyPart);
}
doc.saveToFile(docUrl, FileFormat.Docx);
doc.dispose();
}
}
【tips】要点总结
1、在使用插入表格的时候因为格式问题,至于具体格式自己可以打debug查看,调用插入表的方法时需要对数组进行格式化,可以采用以下方法格式化后调用(其中的对象名称可根据自己的需要进行调整):
public String GoalFunction(String docUrl,String filePath,String params){
//查询数据
List<Map<String,String>> dataList = service.getDataList(params);
//组合数据
int datalen = dataList.size();
String [][] data = new String[datalen+1][];
data[0]= new String[]{"序号", "标题", "内容1"};
//标题
String titleName = "";
//内容
String content = "";
//数据链判空逻辑
boolean checkVal = service.checkLength(dataList);
if(checkVal){
for(int i = 0;i<datalen;i++){
Map<String,String> rowVal = dataList.get(i);
//序号
String num = String.valueOf(i+1);
//标题
titleName = rowVal.get("titleName");
//内容
content = rowVal.get("content");
data[i+1]= new String[]{num, titleName , content};
}
}else{
data[1]= new String[]{"", titleName, content};
}
//调用操作
String info = wordUtil.ReplaceBookmarkContentWithTable(docUrl,"标签名",data,filePath);
return info;
}