java使用poi导出 将html转换为word

时间:2025-03-18 17:11:07

@ 将html转换为word
这几天在一个新项目中做了一个java导出word的功能,但是使用到的内容是富文本编辑框,所以在保存的时候有保存的是html便签,包括一些文字的样式,那样需要在导出的时候按在页面显示的原样式导出,那么就用到了将html便签转换为word,具体的代码如下:

在controller中调用工具类:
(request,response,"<html><body>"+nr+"</body></html>");
在工具类中的实现方法:
public void exportWord(HttpServletRequest request, HttpServletResponse response, String content) throws Exception {
    try {
        byte b[] = ("utf-8");  //这里是必须要设置编码的,不然导出中文就会乱码。
        ByteArrayInputStream bais = new ByteArrayInputStream(b);//将字节数组包装到流中
            //生成word
        POIFSFileSystem poifs = new POIFSFileSystem();
        DirectoryEntry directory = ();
        DocumentEntry documentEntry = ("exportWord", bais);
        //输出文件
        ("utf-8");
        //设置word格式
        ("application/msword");
        ("Content-disposition", "attachment;filename=");
        OutputStream ostream = ();
        (ostream);
        ();
        ();
    }catch(Exception e){
        //异常处理
        ("文件导出错误", e);
    }
}
pom文件中关于poi的依赖
<dependency>
        <groupId></groupId>
        <artifactId>
            poi</artifactId>
        <version>3.10-beta2</version>
        <type>jar</type>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId></groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.10-beta2</version>
        <type>jar</type>
    </dependency>
    <dependency>
        <groupId></groupId>
        <artifactId>poi-ooxml-schemas</artifactId>
        <version>3.10-beta2</version>
        <type>jar</type>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId></groupId>
        <artifactId>poi-scratchpad</artifactId>
        <version>3.0.2-FINAL</version>
    </dependency>