700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > java poi修改word_java poi 替换word中的指定文本

java poi修改word_java poi 替换word中的指定文本

时间:2022-06-12 03:49:15

相关推荐

java poi修改word_java poi 替换word中的指定文本

开头贴出参考文章地址:

/s/blog_885585cb0101gnz7.html

/dreammyle/p/5159267.html

效果图:原docx文件

效果图:替换后的docx文件

maven依赖:

org.apache.poi

poi

3.16

org.apache.poi

poi-scratchpad

3.16

org.apache.poi

poi-ooxml

3.16

java代码:

package com.smh.test;

import org.apache.poi.xwpf.usermodel.*;

import java.io.*;

import java.util.*;

import java.util.Map.Entry;

public class WordUtil {

public static void main(String[] args) throws IOException {

String srcPath = "D:\\a.docx";

String destPath = "D:\\a-" + System.currentTimeMillis() + ".docx";

InputStream in = new FileInputStream(srcPath);

FileOutputStream out = new FileOutputStream(destPath);

Map map = new HashMap<>();

map.put("${AGE}", "10777");

map.put("${NAME}", "99999");

replaceText(in, out, map);

in.close();

out.close();

}

public static void replaceText(InputStream inputStream, OutputStream outputStream, Map map) {

try {

XWPFDocument document;//= new XWPFDocument(POIXMLDocument.openPackage(srcPath));

document = new XWPFDocument(inputStream);

//1. 替换段落中的指定文字

Iterator itPara = document.getParagraphsIterator();

String text;

Set set;

XWPFParagraph paragraph;

List run;

String key;

while (itPara.hasNext()) {

paragraph = itPara.next();

set = map.keySet();

Iterator iterator = set.iterator();

while (iterator.hasNext()) {

key = iterator.next();

run = paragraph.getRuns();

for (int i = 0, runSie = run.size(); i < runSie; i++) {

text = run.get(i).getText(run.get(i).getTextPosition());

if (text != null && text.equals(key)) {

run.get(i).setText(map.get(key), 0);

}

}

}

}

//2. 替换表格中的指定文字

Iterator itTable = document.getTablesIterator();

XWPFTable table;

int rowsCount;

while (itTable.hasNext()) {

table = itTable.next();

rowsCount = table.getNumberOfRows();

for (int i = 0; i < rowsCount; i++) {

XWPFTableRow row = table.getRow(i);

List cells = row.getTableCells();

for (XWPFTableCell cell : cells) {

for (Entry e : map.entrySet()) {

if (cell.getText().equals(e.getKey())) {

cell.removeParagraph(0);

cell.setText(e.getValue());

}

}

}

}

}

//3.输出流

document.write(outputStream);

} catch (Exception e) {

e.printStackTrace();

}

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。