一、编辑模板 替换地方以变量标记如“案件编号”可写成{caseNo}
template.xml
二、准备数据 以HashMap封装数据,原理是替换模板中的变量
三、替换操作
选择输出位置:writePath
WordUtil.printWordbyXMLWithOutputPath(templateFile, writePath, filename,
dataMap);
/**
* 打印word文档(传入参数需要传入输出文件的保存路径的)
* @param templateFile
* @param writeFilePath
* @param writeFileName
* @param analysisData 要替换的数据,map的形式传递
* @throws Exception
*/
public static void printWordbyXMLWithOutputPath(String templateFile, String writeFilePath,
String writeFileName, Map<String, String> analysisData) throws Exception{
writeFilePath = makePathFile(writeFilePath);
String writeFile = "";
if(writeFilePath.endsWith("\\") || writeFilePath.endsWith("/")){
writeFile += writeFilePath + writeFileName;
}else{
writeFile = writeFilePath + FILE_SEPARATOR + writeFileName;
}
printWordByXML(templateFile, writeFile, analysisData);
}
/**
* 打印word文档(输出路径不需要单独指出,保存在writeFile中即可)
* @param templateFile
* @param writeFile
* @param analysisData
* @throws Exception
*/
public static void printWordByXML(String templateFile,
String writeFile, Map<String, String> analysisData) throws Exception{
FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader in = null;
FileOutputStream fos = null;
OutputStreamWriter osw = null;
BufferedWriter out = null;
try {
fis = new FileInputStream(templateFile);
isr = new InputStreamReader(fis, "UTF-8");
in = new BufferedReader(isr);
fos = new FileOutputStream(writeFile);
osw = new OutputStreamWriter(fos, "UTF-8");
out = new BufferedWriter(osw);
String s;
while ((s = in.readLine()) != null) {
for (String key : analysisData.keySet()) {
String value = analysisData.get(key);
if (value != null) {
s = s.replace(key, value);
} else {
s = s.replace(key, "");
}
}
out.write(s);
out.newLine();
}} catch (Exception e) {
e.printStackTrace();
} finally{
if(out != null){
out.close();
}
if(osw != null){
osw.close();
}
if(fos != null){
fos.close();
}
if(in != null){
in.close();
}
if(isr != null){
isr.close();
}
if(fis != null){
fis.close();
}// DeleteFile(templateFile);
}}
/**
* 验证目录是否存在,如果不存在,则创建对应目录。
* @param filePathName
*/
public static String makePathFile(String filePathName){
File pathFile = new File(filePathName);
if(!pathFile.exists()){
pathFile.mkdirs();
}
File childFile = new File(pathFile + "\\\\"
+ DateTools.dateToString( new Date(),"yyyyMM"));//xiexiangning
if (!childFile.exists()) {
childFile.mkdir();
}
return childFile + "\\\\";
}
使用word的xml模板生成.doc文件,布布扣,bubuko.com