使用poi实现html字符串生成word文档,和导出word文档,

优点:对于html不需要特殊处理,直接带完整样式生成到word文档中

引入依赖

                <exclusion>
                    <groupId>org.apache.poi</groupId>
                    <artifactId&gt;poi</artifactId&gt;
                </exclusion&gt;
                <exclusion&gt;
                    <groupId&gt;org.apache.poi</groupId&gt;
                    <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)) {
                // 生成临时文件(doctry {
                    // 生成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文件。

原文地址:https://blog.csdn.net/weixin_41765715/article/details/132846632

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_34184.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注