此核心代码只适用doc文件,代码如下
调用
public static void main(String[] arg)throws Exception {
String templatePath = "c:\\Users\\xxx\\Desktop\\template.doc";
String tempFilePate = "c:\\Users\\xxx\\Desktop\\outFile.doc";
Map<String,Object> dataMap = new HashMap<String,Object>(){
{
put("a","a");
put("b","bb");
put("c",123);
}
};
new WordUtil4DOC().makeReplace(templatePath,tempFilePate,dataMap);
}
核心逻辑
注意,模板中的关键字是<keyword>封闭,针对换行,字符串中必须是“\n”,如果需要“\r”等其它的,请自行替换
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import java.io.*;
import java.util.Map;
public class WordUtil4DOC {
public void makeReplace(String templatePath,String tempFilePath, Map<String,Object> dataMap) throws IOException {
InputStream is = new FileInputStream(templatePath);
HWPFDocument doc = new HWPFDocument(is);
Range range = doc.getRange();
for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
String key = "<" + entry.getKey() + ">";
String value = "";
if (null != entry.getValue()) {
value = String.valueOf(entry.getValue());
}
try {
if (value.substring(0,1).equalsIgnoreCase("\n")){
StringBuffer sb = new StringBuffer(value);
value = sb.replace(0,1,"").toString();
}
}catch (Exception e){
System.out.println("replace the first br is fail,do not replace it");
}
value = value.replace("\n",((char)11)+" ");
range.replaceText(key,value);
}
OutputStream os = new FileOutputStream(tempFilePath);
doc.write(os);
this.close(os);
this.close(is);
}
private void close(InputStream is) {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void close(OutputStream os) {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}