本文使用maven, java jdk8, poi4.1.2版本来操作docx的页眉里面的表格信息。如下图:
1、引入maven依赖包:
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.2.3</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-excelant</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-examples</artifactId>
<version>4.1.2</version>
</dependency>
2、创建WordUntil.java
package com.zy.ssm.ssms.common.until;
import cn.hutool.core.util.StrUtil;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.util.StringUtil;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class WordReporter {
private String tempLocalPath;
private XWPFDocument xwpfDocument = null;
private HWPFDocument hwpfDocument = null;
private FileInputStream inputStream = null;
private OutputStream outputStream = null;
public WordReporter(){
}
public WordReporter(String tempLocalPath){
this.tempLocalPath = tempLocalPath;
}
/**
* 设置模板路径
* @param tempLocalPath
*/
public void setTempLocalPath(String tempLocalPath) {
this.tempLocalPath = tempLocalPath;
}
/**
* 初始化
* @throws IOException
*/
public void init() throws IOException{
inputStream = new FileInputStream(new File(this.tempLocalPath));
xwpfDocument = new XWPFDocument(inputStream);
}
/**
* 导出方法
* @param textMap 需替换的文本的数据入参
* @return
* @throws Exception
*/
public boolean export(Map<String,String> textMap) throws Exception{
replaceHeaderTable(xwpfDocument,textMap);
return true;
}
/**
*
* @Author CL
* @Description 替换页眉相关数据
* @Date 17:47 2022/3/9
* @Param [xwpfDocument, textMap]
* @return void
**/
public void replcateHeader(XWPFDocument xwpfDocument,Map<String,String> textMap) {
List<XWPFParagraph> paras= xwpfDocument.getHeaderFooterPolicy().getDefaultHeader().getParagraphs();
Set<String> keySet=textMap.keySet();
for (XWPFParagraph para : paras) {
//当前段落的属性
System.out.println("打印获取到的段落的每一行数据++++++++>>>>>>>"+ para.getText());
String str=para.getText();
System.out.println("========================>>>>>>"+ para.getParagraphText());
List<XWPFRun> list=para.getRuns();
for(XWPFRun run:list){
System.out.println("run: ----------------------->>" + run.text());
for(String key:keySet){
if(key.equals(run.text())){
run.setText(textMap.get(key),0);
}
}
}
}
}
/**
*
* @Author CL
* @Description 替换页眉里面表格的相关数据相关数据
* @Date 17:47 2022/3/9
* @Param [xwpfDocument, textMap]
* @return void
**/
public void replaceHeaderTable(XWPFDocument xwpfDocument,Map<String,String> textMap) {
List<XWPFHeader> hearders = xwpfDocument.getHeaderList();
for (XWPFHeader getHeader: hearders) {
List<XWPFTable> tables= getHeader.getTables();
System.out.println(tables.size());
Set<String> keySet=textMap.keySet();
for (XWPFTable tableObj: tables) {
List<XWPFTableRow> rows= tableObj.getRows();
for (int i = 0; i < rows.size(); i++) {
XWPFTableRow row = rows.get(i);
//读取每一列数据
List<XWPFTableCell> cells = row.getTableCells();
for (int j = 0; j < cells.size(); j++) {
XWPFTableCell cell=cells.get(j);
// cell.getXWPFDocument().getParagraphs()
List<XWPFParagraph> paras=cell.getParagraphs();
for (XWPFParagraph para : paras) {
//当前段落的属性
System.out.println("打印获取到的段落的每一行数据++++++++~~~~~>>>>>>>"+para.getText());
String str=para.getText();
System.out.println("========================~~~~~~~~~~>>>>>>"+para.getParagraphText());
List<XWPFRun> list=para.getRuns();
for(XWPFRun run:list){
System.out.println("run: -----------~~~~~~~~~~->>" + run.text());
for(String key:keySet){
if(key.equals(run.text())){
System.out.println(key + "~" + run.text() + "~~~" + key.equals(run.text()));
run.setText(textMap.get(key),0);
}
}
}
}
//输出当前的单元格的数据
System.out.println("获取的内容为: ====>>>>>" + cell.getText() + "------" + paras.size());
}
}
}
}
}
/**
* 关闭输入流
* @param is
*/
private void close(InputStream is) {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 关闭输出流
* @param os
*/
private void close(OutputStream os) {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 收尾方法
* @param outDocPath
* @return
* @throws IOException
*/
public boolean generate(String outDocPath,String fileName) throws IOException{
File file =new File(outDocPath);
//如果文件夹不存在则创建
if(!file.exists() && !file.isDirectory()){
file.mkdirs();
}
outputStream = new FileOutputStream(outDocPath + fileName);
xwpfDocument.write(outputStream);
this.close(outputStream);
this.close(inputStream);
return true;
}
}
3、添加测试类方法
@Test
public void wordReadTest() throws Exception {
Map<String,String> textMap=new HashMap<>();
textMap.put("${stationName}", "需要替换的名称");
// 模板文件输入输出地址
String filePath = "H:/tmp/office/bbb.docx";
String outPath = "h:/tmp/office/bbb1.docx";
WordReporter wordReporter = new WordReporter();
wordReporter.setTempLocalPath(filePath); //设置模板的路径
wordReporter.init(); //初始化工具类
wordReporter.export(textMap); //写入相关数据
wordReporter.generate(outPath); //导出到目标文档
}