在公司做开发的时候,遇见了一个难题,就是将一份本地的指定内容给隐藏掉。不说废话,直接上代码
/**
* Info 将docx的文档的内容把指定的内容替换掉
* Modification History:
* Date Author Version Description
* -----------------------------------------------------------------
* 2018-1-5 ywl v1.0.0 create
* -----------------------------------------------------------------
* @param srcPath 原路径
* @param destPath 保存路径
* @map key为需要替换的 value为替换的内容
*/
public static void searchAndReplace(String srcPath, String destPath,Map<String, String> map) {
FileOutputStream outStream = null;
InputStream is = null;
try {
URL url = new URL(srcPath);
is = url.openStream();
XWPFDocument document = new XWPFDocument(is);
/**
* 替换段落中的指定文字
*/
Iterator<XWPFParagraph> itPara = document.getParagraphsIterator();
while (itPara.hasNext()) {
XWPFParagraph paragraph = (XWPFParagraph) itPara.next();
Set<String> set = map.keySet();
Iterator<String> iterator = set.iterator();
while (iterator.hasNext()) {
String key = iterator.next();
List<XWPFRun> run=paragraph.getRuns();
for(int i=0;i<run.size();i++)
{
if(run.get(i).getText(run.get(i).getTextPosition())!=null &&
run.get(i).getText(run.get(i).getTextPosition()).contains(key))
{
/**
* 参数0表示生成的文字是要从哪一个地方开始放置,设置文字从位置0开始
* 就可以把原来的文字全部替换掉了
*/
String text = run.get(i).getText(run.get(i).getTextPosition());
text = text.replaceAll(key,map.get(key));
run.get(i).setText(text,0);
}
}
}
}
/**
* 替换表格中的指定文字
*/
Iterator<XWPFTable> itTable = document.getTablesIterator();
while (itTable.hasNext()) {
XWPFTable table = (XWPFTable) itTable.next();
int count = table.getNumberOfRows();
for (int i = 0; i < count; i++) {
XWPFTableRow row = table.getRow(i);
List<XWPFTableCell> cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
for (Map.Entry<String, String> e : map.entrySet()) {
if (cell.getText().equals(e.getKey())) {
cell.removeParagraph(0);
cell.setText(e.getValue());
}
}
}
}
}
outStream = new FileOutputStream(destPath);
document.write(outStream);
// URLConnection conn = url.openConnection();
// conn.setDoOutput(true);
// outStream = conn.getOutputStream();
// document.write(outStream);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(null != is){
is.close();
}
if(null != outStream){
outStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
代码很简单,直接拿去用就行了。原路径是远程的路径,如果是本地的路径,只需要
URL url = new URL(srcPath);
is = url.openStream();
is = new FileInputStream(new File(srcPath));
第一个路径是打开的url,第二个是打开的本地的,感觉不难,如果不会的,在留言板留言。
如果你觉得我写的还可以,请关注我的公众号,为我加油喝彩