一、需求:
我們在使用富文本編輯器來編輯文本的時候,文本會自帶HTML的標簽比如<p> <a>等來修飾字體樣式。
比如ueditor、kindeditor等富文本編輯器。
那么,我們如何將富文本編輯器里的內容導出到word文檔里?
二、思路:
word文檔是可以識別完整的html頁面的,所以我們需要將首尾缺失的標簽補齊。
1.首先我們需要建立一個word導出的工具類:
/**
* html 導出 word 工具類
* @author zhangxiang
*
*/
public class WordUtil {
????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();
????}
}
然后將富文本的內容拼接成一個HTML頁面:
StringBuffer sbf = new StringBuffer();
sbf.append("<html><body>");? ? //缺失的首標簽
sbf.append(content);? ? //富文本內容
sbf.append("</body></html>");???//缺失的尾標簽
WordUtil.exportWord(request,response,sbf.toString(),wordName);
===========================
以上便是本文的全部內容了,不知道對你有沒有幫助呢。
我會認真寫好每一篇文章,一直努力下去~
===========================