Word文件导出
XWPFTemplate模板生成Word文件导出
//添加poi的相关依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>ooxml-schemas</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.9.1</version>
</dependency>
//java部分
//参数1:数据,参数2:模板文件名称
public String exportWord(Map data, String docName, HttpServletResponse response) {
HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();
Configure config = Configure.builder()
.bind("firstClass", policy)
.bind("trainCyszList", policy)
.build();
InputStream ins = this.getClass().getClassLoader().getResourceAsStream("Template/" + docName);
XWPFTemplate template = XWPFTemplate.compile(ins, config).render(data);
OutputStream os= null;
BufferedInputStream bis = null;
Calendar now = Calendar.getInstance();
String name = now.get(Calendar.YEAR) + "年" + (now.get(Calendar.MONTH) + 1) + "月" + now.get(Calendar.DAY_OF_MONTH) + "日"
+ now.get(Calendar.HOUR_OF_DAY) + "时" + now.get(Calendar.MINUTE) + "分" + now.get(Calendar.SECOND) + "秒";
try {
File file = new File("D:/ABD");
//如果文件夹不存在则创建
if (!file.exists() && !file.isDirectory()) {
file.mkdir();
}
name = name + ".docx";
//定义导出的路径
FileOutputStream out = new FileOutputStream("D:/ABD/" + name);
template.write(out);
out.flush();
out.close();
NiceXWPFDocument xwpfDocument = template.getXWPFDocument();
xwpfDocument.enforceFillingFormsProtection("123456", HashAlgorithm.md5);
name = name + ".docx";
response.setHeader("content-type", "text/html;charset=UTF-8");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=" + name);
os = response.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(os);
template.write(bos);
bos.flush();
template.close();
os.flush();
PoitlIOUtils.closeQuietlyMulti(template, bos, os);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return name;
}
nginx配置:
server {
listen 10010;
server_name localhost;
charset utf-8;
location / {
root D://ABD;
try_files $uri $uri/ /index.html;
index index.html index.htm;
}
模板文件格式【实体以及集合】
总结:导入依赖,复制代码,配上模板路径,配置Nginx,亲测可用!
注意!!!
问题1:导出到项目目录,打成jar包后导出有问题。
(问题:FileOutputStream无法获取jar包文件目录的文件,一直报错找不到文件路径,暂未找到问题的原因。自然打成war包便没有这个问题)
问题2:导入到本地目录,通过nginx下载本地目录的文件,但是只会生成到该服务器目录,局域网内访问该主机电脑,点击导出,无法打开,原因是未下载到本机。
()
大部分导出,还是选择将文件下载到阿里云等服务器上!一些小项目或成本低的项目也没办法