下面介绍一下Java中用POI生成Word文档,Java使用模板生成Word。
前期准备工作(包括相关工具或所使用的原料等)Eclipse 详细的操作方法或具体步骤
导入两个必须的Jar包:poi-3.10.1.jar和poi-scratchpad-3.10.1.jar

如果报filesystem错误,应该是引用的这两个包的版本不一样,所以一定要保持版本一致。
直接将内容导出成DOC文件:
/** * 导出Word文件
* @param destFile 目标文件路径
* @param fileContent 要导出的文件内容
*/public static int exportDoc(String destFile,String fileContent){
try {
ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(fileContent.getBytes("UTF-8"));
POIFSFileSystem fileSystem=new POIFSFileSystem();
DirectoryEntry directory=fileSystem.getRoot();
directory.createDocument("WordDocument", byteArrayInputStream);
FileOutputStream fileOutputStream=new FileOutputStream(destFile);
fileSystem.writeFilesystem(fileOutputStream);
byteArrayInputStream.close();
fileOutputStream.close();
return 1;
} catch (IOException e) {return 0;
}
}
这个导出只是对文字Word做的导出。
用法:
exportDoc("C:\\12.doc", "exportDoc导出Word");

使用模板导出Doc的话需要先定义好模板内容。
例如模板内容如下图所示。

/** * 读取word模板并替换变量
* @param templatePath 模板路径
* @param contentMap 要替换的内容
* @return word的Document
*/
public static HWPFDocument replaceDoc(String templatePath, Map
try {
// 读取模板
FileInputStream tempFileInputStream=new FileInputStream(new File(templatePath));
HWPFDocument document=new HWPFDocument(tempFileInputStream);
// 读取文本内容
Range bodyRange=document.getRange();
// 替换内容
for (Map.Entry
bodyRange.replaceText("${" + entry.getKey() + "}", entry.getValue());
}
return document;
} catch (Exception e) {
return null;
}
}

调用方法如下:
Map
contentMap.put("name", "飞翔家族");
contentMap.put("age", "123");
contentMap.put("email", "1231231231@123.com");
HWPFDocument document=replaceDoc("C:\\template.doc", contentMap);
if(document !=null){
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
try {
document.write(byteArrayOutputStream);
OutputStream outputStream=new FileOutputStream(destFile);
outputStream.write(byteArrayOutputStream.toByteArray());
outputStream.close();
} catch (IOException e) { }
}
使用模板导出DOC文件我们还可以使用其他的方法。
我们还是先需要制作好DOC模板文件,然后另存为XML文件。
使用velocity,将数据填充,导出成DOC文件。
这里介绍的都是最简单的方法,直接导出文本Word,如果要导出复杂一点的Word,请再查阅。
经验内容仅供参考,如果您需解决具体问题(尤其法律、医学等领域),建议您详细咨询相关领域专业人士。作者声明:本教程系本人依照真实经历原创,未经许可,谢绝转载。- 评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
-
