html 保存成word (富文本编辑器导出内容成word)

这几天项目里有个需求,用到富文本编辑器,然后导出word。

富文本编辑器,网上很多,使用夜很简单,我们使用的是kindEditor。百度的ueditor很好,而且文档很全。阿里的kissy 感觉比较复杂,咱们写博客的这个,好像是wangEditor。一般用起来都很简单。

这里重点说一下导出。如何将编辑器的内容保存到word文档里去。

大体思路是这样的,(1)获取编辑器的内容,要是带html标签的,(2)获取编辑器所用到的css。(3)将这些内容已标准html的形式写到word里去,生成临时文件。(4)导出

我们在实际使用的时候,先生成一个临时文件,然后读取这个临时文件导出就可以了。导出的功能网上也很多。

demo主要是展示如何生成导出的临时文件,导出的代码可以网上找找。需要注意的是,临时文件是要删除的,否则占用空间。删除的时候 file.delete()这个方法,要在流都关闭后再调用,否则删不掉的。因为文件被流共享了。

demo中的css换一下,文本内容换成你的编辑器传过来的就可以了。

demo代码如下:

import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * Created by weiyuan on 2018/2/10/010.
 */
public class Editor {
    public static void main(String[] args) {
    Editor editor=new Editor();
        try {
            editor.docFile();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    public  void docFile() throws Exception {
        InputStream bodyIs = new FileInputStream("f:\\2.html");
        InputStream cssIs2 = new FileInputStream("f:\\ueditor.css");
        InputStream cssIs1 = new FileInputStream("f:\\codemirror.css");
        String body = this.getContent(bodyIs);
        String css1 = this.getContent(cssIs1);
        String css2 = this.getContent(cssIs2);
        //拼一个标准的HTML格式文档
String content = "<html><head><style>" + css1+"\\n" +css2 + "</style></head><body>" + body + "</body></html>";
        InputStream is = new ByteArrayInputStream(content.getBytes("GBK"));
        OutputStream os = new FileOutputStream("f:\\2.doc");
        this.inputStreamToWord(is, os);
    }

    /**
     * is写入到对应的word输出流os* 不考虑异常的捕获,直接抛出
* @param is
* @param os
* @throws IOException
     */
private void inputStreamToWord(InputStream is, OutputStream os) throws IOException {

        POIFSFileSystem fs = new POIFSFileSystem();
        //对应于org.apache.poi.hdf.extractor.WordDocument
fs.createDocument(is, "WordDocument");
        fs.writeFilesystem(os);
        os.close();
        is.close();
    }

    /**
     * 把输入流里面的内容以UTF-8编码当文本取出。
* 不考虑异常,直接抛出
* @param ises
* @return
* @throws IOException
     */
private String getContent(InputStream... ises) throws IOException {
        if (ises != null) {
            StringBuilder result = new StringBuilder();
            BufferedReader br;
            String line;
            for (InputStream is : ises) {
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                while ((line=br.readLine()) != null) {
                    result.append(line);
                }
            }
            return result.toString();
        }
        return null;
    }
}


猜你喜欢

转载自blog.csdn.net/liyuan0323/article/details/79436743