java导出简单的word模板
public ByteArrayOutputStream toWordStream(InputStream inputStream, Map<String, Object> map) {
try {
// 1) Load ODT file and set Velocity template engine and cache it to the registry
IXDocReport report = XDocReportRegistry.getRegistry().loadReport(inputStream, TemplateEngineKind.Velocity);
// 2) Create Java model context
IContext context = report.createContext();
Set<Entry<String, Object>> entrySet = map.entrySet();
for (Entry<String, Object> entry : entrySet) {
context.put(entry.getKey(), entry.getValue());
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
report.process(context, out);
return out;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
说明:inputstream为Word模板输入流,map中的key为Word模板中的字段,value为导出Word后所对应字段的值
获取到字节流后,再将字节流生成对应的Word文件
public File createTempFile(ByteArrayOutputStream out) {
try {
File tmp = new File(FileUtils.getTempDirectory() + "/" + UUID.randomUUID().toString() + ".tmp");
FileUtils.writeByteArrayToFile(tmp, out.toByteArray());
IOUtils.closeQuietly(out);
return tmp;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("临时文件输出异常!");
}
}
说明:其中FileUtils为commons-io.jar下的方法所依赖的jar包
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>xdocreport</artifactId>
<version>1.0.6</version>
</dependency>
<!-- 模板引擎 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>oro</groupId>
<artifactId>oro</artifactId>
<version>2.0.8</version>
</dependency>
word模板中的字段,例如 «$name»