使用poi实现html字符串生成word文档,和导出word文档,
优点:对于html不需要特殊处理,直接带完整样式生成到word文档中
引入依赖:
<exclusion>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
</exclusion>
1. 将html字符串生成doc文件
代码如下:
// 组装html(替换为自己的html)
String html = hostPatrolMessageContentToHtml2(dataVo.getReportDetail(), dataVo.getAlarmMap(), 0);
if (StringUtils.isNotEmpty(html)) {
// 生成临时文件(doc)
try {
// 生成doc格式的word文档,需要手动改为docx
byte by[] = html.getBytes("UTF-8");
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(by);
POIFSFileSystem poifsFileSystem = new POIFSFileSystem();
DirectoryEntry directoryEntry = poifsFileSystem.getRoot();
directoryEntry.createDocument("WordDocument", byteArrayInputStream);
// 临时文件夹
String sqlFilePath = Global.getProfile() + File.separator + "patrolReport" + File.separator + "temp_" + StringUtils.getUUId();
directory = new File(sqlFilePath);
if (!directory.exists()) {
directory.mkdirs();
}
// 文件路径
String fileUrl = sqlFilePath + File.separator + "主机巡检报告告警内容详情.doc";
// 保存doc文档
FileOutputStream outputStream = new FileOutputStream(fileUrl);
poifsFileSystem.writeFilesystem(outputStream);
byteArrayInputStream.close();
outputStream.close();
file = new File(fileUrl);
} catch (Exception e) {
e.printStackTrace();
}
}
例如组装的html为:
<html><body> <h3>巡检报告告警详情:</h3><ul><li>主机(zyf主机)发生<font color=#F56C6C>严重警告</font><ul><li>服务器探针(zyf主机)发生<font color=#F56C6C>严重警告</font><ul><li>指标名称(内存使用率),发生<font color=#F56C6C>严重警告</font>,阈值:> 25 %,采集值:77.84 %;</li><li>指标名称(CPU占用百分比),发生<font color=#F56C6C>严重警告</font>,阈值:> 30 %,采集值:65.64 %;</li></ul></li><li>中间件探针(tomcat测试)采集失败,返回信息:Failed to retrieve RMIServer stub: javax.naming.ServiceUnavailableException [Root exception is java.rmi.ConnectException: Connection refused to host: 122.112.174.151; nested exception is:
java.net.ConnectException: Connection timed out: connect]</li><li>数据库探针(98MySQL库)采集失败,返回信息:Failed to initialize pool: Access denied for user 'root'@'10.2.6.159' (using password: YES)</li><li>数据库探针(本地Oracle测试库19c)采集失败,返回信息:Failed to initialize pool: ORA-28001: 口令已经失效
</li><li>数据库探针(MySQL测试数据库)采集失败,返回信息:Failed to initialize pool: Access denied for user 'root'@'10.2.6.159' (using password: YES)</li></ul></li></ul></body></html
生成的doc文件:
2. 将html字符串导出word文档
代码:
/**
* @param request
* @param response
* @param content 富文本内容(html)
* @param fileName 生成word文件
* @throws Exception
*/
public static void exportWord(HttpServletRequest request, HttpServletResponse response, String content, String fileName) throws Exception {
ByteArrayInputStream byteArrayInputStream = null;
POIFSFileSystem poifsFileSystem = null;
ServletOutputStream servletOutputStream = null;
try {
byte b[] = content.getBytes("GBK"); //这里是必须要设置编码的,不然导出中文就会乱码。
byteArrayInputStream = new ByteArrayInputStream(b);//将字节数组包装到流中
poifsFileSystem = new POIFSFileSystem();
DirectoryEntry directory = poifsFileSystem.getRoot();
directory.createDocument("WordDocument", byteArrayInputStream); //该步骤不可省略,否则会出现乱码。
//输出文件
request.setCharacterEncoding("utf-8");
response.setContentType("application/msword");//导出word格式
response.addHeader("Content-Disposition", "attachment;filename=" + FileUtils.setFileDownloadHeader(request, fileName) + ".doc");
servletOutputStream = response.getOutputStream();
poifsFileSystem.writeFilesystem(servletOutputStream);
} catch (Exception e) {
throw e;
} finally {
byteArrayInputStream.close();
servletOutputStream.close();
poifsFileSystem.close();
}
}
// 适配浏览器
public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException {
String agent = request.getHeader("USER-AGENT");
String filename;
if (agent.contains("MSIE")) {
filename = URLEncoder.encode(fileName, "utf-8");
filename = filename.replace("+", " ");
} else if (agent.contains("Firefox")) {
filename = new String(fileName.getBytes(), "ISO8859-1");
} else if (agent.contains("Chrome")) {
filename = URLEncoder.encode(fileName, "utf-8");
} else {
filename = URLEncoder.encode(fileName, "utf-8");
}
return filename;
}
导出文件内容:
对于富文本插件生成的html代码也可以通过此方法生成word文件。