本文讲解在springboot环境下,将ueditor保存到数据库中的html内容使用poi导出为word文件,亲测导出的文件在word和wps上打开均正常显示。
首先,在pom.xml文件中引入poi包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
然后在Service层中Impl下写导出函数
public void exportWord(HttpServletRequest request, HttpServletResponse response, String title, String text) {
try {
//word内容
String content="<html><body>" +
"<p style=\"text-align: center;\"><span style=\"font-family: 黑体, SimHei; font-size: 24px;\">"
+ title + "</span></p>" + text + "</body></html>";
byte b[] = content.getBytes("GBK"); //这里是必须要设置编码的,不然导出中文就会乱码。
ByteArrayInputStream bais = new ByteArrayInputStream(b);//将字节数组包装到流中
/*
* 关键地方
* 生成word格式 */
POIFSFileSystem poifs = new POIFSFileSystem();
DirectoryEntry directory = poifs.getRoot();
DocumentEntry documentEntry = directory.createDocument("WordDocument", bais);
//输出文件
request.setCharacterEncoding("utf-8");
response.setContentType("application/msword");//导出word格式
response.addHeader("Content-Disposition", "attachment;filename=" +
new String(title.getBytes("GB2312"),"iso8859-1") + ".doc");
ServletOutputStream ostream = response.getOutputStream();
poifs.writeFilesystem(ostream);
bais.close();
ostream.close();
poifs.close();
}catch(Exception e){
e.printStackTrace();
}
}
需要注意的地方是编码问题,错误的编码通常导致word不能正常导出。参数我设置了四个,title和text分别代表标题和内容,如果标题和内容在数据库中放在一起的话就只设置一个。
然后就可以在controller中引入函数进行导出了,亲测有效。