package com.demo.poi;
import org.apache.commons.io.output.ByteArrayOutputStream;
//import org.apache.commons.collections4.CollectionUtils;
//import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.core.io.ByteArrayResource;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 通过word模板生成新的word工具类
*
*/
public class WorderToNewWordUtils {
public static void main(String[] args) throws Exception {
byte[] content = null;
WorderToNewWordUtils ws = new WorderToNewWordUtils();
String path = "resoure\\1.docx";
InputStream in = new FileInputStream(new File(path));
Map<String, String> datas = new HashMap<String, String>();
datas.put("<number>", "100");
datas.put("<Decumber>", "12");
datas.put("<cofirm>", "确认");
datas.put("<name>", "张三");
datas.put("<age>", "26");
datas.put("<add>", "广东深圳");
XWPFDocument doc = changWordForcommon(in, datas);
ByteArrayOutputStream os = new ByteArrayOutputStream();
String wordPath = "resoure\\2.docx";
String outputName = "2.docx";
FileOutputStream out = new FileOutputStream(wordPath+outputName);
doc.write(out);
out.flush();
out.close();
// content = os.toByteArray();
in.close();
// ByteArrayResource oResource = new ByteArrayResource(content);
}
public static XWPFDocument changWordForcommon(InputStream in, Map<String, String> textMap) {
XWPFDocument document = null;
try {
// 第一步:获取docx解析对象
document = new XWPFDocument(in);
// 第二步:重构XWPFDocument中 不合格的 占位符 比如:${abcd}分开为${a,b..,cd}
refactorXWPFDocument(document);
// 第三步:解析替换文本段落对象
changeText(document, textMap);
// 第四步:解析替换表格对象
changeTableCity(document, textMap);
} catch (IOException e) {
e.printStackTrace();
}
return document;
}
/**
* 根据模板生成新word文档
POI操作word模板并生成新的word.docx <2>
最新推荐文章于 2024-07-26 18:00:04 发布
本文详细介绍了如何使用Apache POI库来操作Word模板,并生成新的docx文档。通过示例代码,展示了如何读取模板,替换占位符,以及保存为完整文档的过程。
摘要由CSDN通过智能技术生成