一、需求:

当创建使用富文本编辑器,操作完的数据,传输到后台都是带有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.看结果:

 

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐