Java 富文本内容转化word导出

一、需求:

当创建使用富文本编辑器,操作完的数据,传输到后台都是带有html标签的。
如:<h1>标题头</h1><h2>第二个标题</h2><a href="www.baidu.com">百度搜索</a>

如果我们想把富文本数据转换为Word内容,并下载下来。

二、解决方案

Word是完全支持html标签的,但是我们获取到的富文本内容并不是完整的html代码,所有我们需要先补全html标签,然后转码,然后输出。

上代码!!!

1.先去页面创建一个图片按钮:

<div onclick="ExceltoWord()"> <img src="xxxxxx.jpg"></div>
<form style="display:none" name="frmExcel"  id="frmExcel" action="" enctype="multipart/form-data" method="post"></form>

2.然后编写JS请求:

function ExceltoWord() {
		document.getElementById("frmExcel").action = '/fileUpdate/download';  //拼接接口地址  
		document.getElementById("frmExcel").submit();
}

3.编写后台代码:

import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;


@Controller
@RequestMapping("fileUpdate")
public class SampleLibController extends BaseController {

    @ResponseBody
    @RequestMapping(value = "download")
    public int download(HttpServletResponse response, HttpServletRequest request)throws Exception {
        String content = "<h1>标题头</h1><h2>第二个标题</h2><a href=\"www.baidu.com\">百度搜索</a>";
        StringBuffer sbf = new StringBuffer();
        sbf.append("<html><body>");
        sbf.append(content);
        sbf.append("</body></html");
        exportWord(request,response,String.valueOf(sbf),"word1");
        return 1;
    }


    /**
     * 
     * @param request
     * @param response
     * @param content  富文本内容
     * @param fileName 生成word名字
     * @throws Exception
     */
     public static void exportWord(HttpServletRequest request, HttpServletResponse response, String content, String fileName) throws Exception {
        byte b[] = content.getBytes("GBK"); //这里是必须要设置编码的,不然导出中文就会乱码。
        ByteArrayInputStream bais = new ByteArrayInputStream(b);//将字节数组包装到流中
        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(fileName.getBytes("GB2312"),"iso8859-1") + ".doc");
        ServletOutputStream ostream = response.getOutputStream();
        poifs.writeFilesystem(ostream);
        bais.close();
        ostream.close();
        poifs.close();
    }


}

4.看结果:

 

  • 9
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 21
    评论
评论 21
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值