Java web 富文本内容生成转为word格式并导出下载
最近思路,按标签逐一解析,实现复杂一点但是完美解决问题:
https://blog.csdn.net/a2272062968/article/details/126227076
思路:Word是完全支持html标签的,但是富文本内容并不是完整的html代码,需要先补全html标签,然后转码输出
问题:虽然导出word doc但是事件内容流还是htm,只不过word帮忙解析展示了,再进行word读取的二次处理就出现问题
依赖包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
上代码
/**
* 导出 word 文档
*
* @param id
* @return
*/
@GetMapping(value = "/download/{id}")
public Result download(@PathVariable Long id, HttpServletResponse response, HttpServletRequest request) throws Exception {
String content = "你的富文本内容"
StringBuilder sbf = new StringBuilder();
sbf.append("<html><body>");
sbf.append(content);
sbf.append("</body></html");
exportWord(request, response, String.valueOf(sbf), "要导出的文件名");
return Result.succeed("导出成功"); //Result是我的通用响应返回对象,换成你自己的
}
/**
*
* @param request
* @param response
* @param content 富文本内容
* @param fileName 导出 word 文件名
* @throws IOException
*/
public void exportWord(HttpServletRequest request, HttpServletResponse response, String content, String fileName) throws IOException {
//这里是必须要设置编码的,不然导出中文就会乱码。
byte b[] = content.getBytes("utf-8");
//将字节数组包装到流中
ByteArrayInputStream bais = new ByteArrayInputStream(b);
POIFSFileSystem poifs = new POIFSFileSystem();
DirectoryEntry directory = poifs.getRoot();
//该步骤不可省略,否则会出现乱码
DocumentEntry documentEntry = directory.createDocument("WordDocument", bais);
//输出文件
request.setCharacterEncoding("utf-8");
//导出word格式
response.setContentType("application/msword");
response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("GB2312"), "iso8859-1") + ".doc");
ServletOutputStream ostream = response.getOutputStream();
poifs.writeFilesystem(ostream);
bais.close();
ostream.close();
poifs.close();
}