react前端導出word文檔

react項目開發中遇到需求,在前端直接將HTML報表內容導出生成word文檔,在網上查閱了相關資料,大概找到3種解決思路:css

一、使用jquery.wordexport.js插件導出(須要依賴jquery,不想在react項目中引入); 
二、使用npm包html-docx-js; 
三、使用ActiveXObject對象。
複製代碼

第3種思路因爲找到的文檔較少,優先級靠後,嘗試了一、2的方案作了些demo,發現都遇到了樣式的處理問題(導出頁面有較多的表格和紙張方向控制),搜索沒有找到很好的解決辦法,不過找到了些解決思路,一開始想嘗試去閱讀html-docx-js的源碼,發現有點吃力,加上時間緊,而後去閱讀了wordexport插件源碼基本弄清楚了其導出原理,後面經過手寫獲取dom節點內容而後本身拼裝成完整的html文檔字符串+FileSaver.js 解決問題。html

網上看到了都是些思路,並無給出很是具體的代碼實現以及導出中一些細節的處理,在此分享本身的一些實踐經驗,供參考。前端

在這裏給出jquery.wordexport.js源碼,並簡單作出分析:react

if (typeof jQuery !== "undefined" && typeof saveAs !== "undefined") {
    (function ($) {
        $.fn.wordExport = function (fileName) {
            fileName = typeof fileName !== 'undefined' ? fileName : "jQuery-Word-Export";
            // 定義文檔模板
            var statics = {
                mhtml: {
                    top: "Mime-Version: 1.0\nContent-Base: " + location.href + "\nContent-Type: Multipart/related; boundary=\"NEXT.ITEM-BOUNDARY\";type=\"text/html\"\n\n--NEXT.ITEM-BOUNDARY\nContent-Type: text/html; charset=\"utf-8\"\nContent-Location: " + location.href + "\n\n\n\n_html_",
                    head: "\n\n\n\n",

} else { if (typeof jQuery === "undefined") { console.error("jQuery Word Export: missing dependency (jQuery)"); } if (typeof saveAs === "undefined") { console.error("jQuery Word Export: missing dependency (FileSaver.js)"); }}jquery

body: "<body>_body_</body>" } }; var options = { maxWidth: 624 }; // Clone selected element before manipulating it var markup = $(this).clone(); // Remove hidden elements from the output markup.each(function () { var self = $(this); if (self.is(':hidden')) self.remove(); }); // Embed all images using Data URLs var images = Array(); var img = markup.find('img'); for (var i = 0; i < img.length; i++) { // Calculate dimensions of output image var w = Math.min(img[i].width, options.maxWidth); var h = img[i].height * (w / img[i].width); // Create canvas for converting image to data URL var canvas = document.createElement("CANVAS"); canvas.width = w; canvas.height = h; // Draw image to canvas var context = canvas.getContext('2d'); context.drawImage(img[i], 0, 0, w, h); // Get data URL encoding of image var uri = canvas.toDataURL("image/png/jpg"); $(img[i]).attr("src", img[i].src); img[i].width = w; img[i].height = h; // Save encoded image to array images[i] = { type: uri.substring(uri.indexOf(":") + 1, uri.indexOf(";")), encoding: uri.substring(uri.indexOf(";") + 1, uri.indexOf(",")), location: $(img[i]).attr("src"), data: uri.substring(uri.indexOf(",") + 1) }; } // Prepare bottom of mhtml file with image data var mhtmlBottom = "\n"; for (var i = 0; i < images.length; i++) { mhtmlBottom += "--NEXT.ITEM-BOUNDARY\n"; mhtmlBottom += "Content-Location: " + images[i].location + "\n"; mhtmlBottom += "Content-Type: " + images[i].type + "\n"; mhtmlBottom += "Content-Transfer-Encoding: " + images[i].encoding + "\n\n"; mhtmlBottom += images[i].data + "\n\n"; } mhtmlBottom += "--NEXT.ITEM-BOUNDARY--"; //TODO: load css from included stylesheet //var styles=' /* Font Definitions */@font-face{font-family:宋體;panose-1:2 1 6 0 3 1 1 1 1 1;mso-font-alt:SimSun;mso-font-charset:134;mso-generic-font-family:auto;mso-font-pitch:variable;mso-font-signature:3 680460288 22 0 262145 0;} @font-face{font-family:"Cambria Math";panose-1:2 4 5 3 5 4 6 3 2 4;mso-font-charset:1;mso-generic-font-family:roman;mso-font-format:other;mso-font-pitch:variable;mso-font-signature:0 0 0 0 0 0;} @font-face{font-family:"\@宋體";panose-1:2 1 6 0 3 1 1 1 1 1;mso-font-charset:134;mso-generic-font-family:auto;mso-font-pitch:variable;mso-font-signature:3 680460288 22 0 262145 0;}/* Style Definitions */p.MsoNormal, li.MsoNormal, div.MsoNormal{mso-style-unhide:no;mso-style-qformat:yes;mso-style-parent:"";margin:0cm;margin-bottom:.0001pt;mso-pagination:widow-orphan;font-size:14.0pt;font-family:宋體;mso-bidi-font-family:宋體;}p.MsoHeader, li.MsoHeader, div.MsoHeader{mso-style-noshow:yes;mso-style-priority:99;mso-style-link:"頁眉 Char";margin:0cm;margin-bottom:.0001pt;text-align:center;mso-pagination:widow-orphan;layout-grid-mode:char;font-size:9.0pt;font-family:宋體;mso-bidi-font-family:宋體;}p.MsoFooter, li.MsoFooter, div.MsoFooter{mso-style-noshow:yes;mso-style-priority:99;mso-style-link:"頁腳 Char";margin:0cm;margin-bottom:.0001pt;mso-pagination:widow-orphan;layout-grid-mode:char;font-size:9.0pt;font-family:宋體;mso-bidi-font-family:宋體;}p.MsoAcetate, li.MsoAcetate, div.MsoAcetate{mso-style-noshow:yes;mso-style-priority:99;mso-style-link:"批註框文本 Char";margin:0cm;margin-bottom:.0001pt;mso-pagination:widow-orphan;font-size:9.0pt;font-family:宋體;mso-bidi-font-family:宋體;}span.Char{mso-style-name:"頁眉 Char";mso-style-noshow:yes;mso-style-priority:99;mso-style-unhide:no;mso-style-locked:yes;mso-style-link:頁眉;font-family:宋體;mso-ascii-font-family:宋體;mso-fareast-font-family:宋體;mso-hansi-font-family:宋體;}span.Char0{mso-style-name:"頁腳 Char";mso-style-noshow:yes;mso-style-priority:99;mso-style-unhide:no;mso-style-locked:yes;mso-style-link:頁腳;font-family:宋體;mso-ascii-font-family:宋體;mso-fareast-font-family:宋體;mso-hansi-font-family:宋體;}span.Char1{mso-style-name:"批註框文本 Char";mso-style-noshow:yes;mso-style-priority:99;mso-style-unhide:no;mso-style-locked:yes;mso-style-link:批註框文本;font-family:宋體;mso-ascii-font-family:宋體;mso-fareast-font-family:宋體;mso-hansi-font-family:宋體;}p.msochpdefault, li.msochpdefault, div.msochpdefault{mso-style-name:msochpdefault;mso-style-unhide:no;mso-margin-top-alt:auto;margin-right:0cm;mso-margin-bottom-alt:auto;margin-left:0cm;mso-pagination:widow-orphan;font-size:10.0pt;font-family:宋體;mso-bidi-font-family:宋體;}span.msonormal0{mso-style-name:msonormal;mso-style-unhide:no;}.MsoChpDefault{mso-style-type:export-only;mso-default-props:yes;font-size:10.0pt;mso-ansi-font-size:10.0pt;mso-bidi-font-size:10.0pt;mso-ascii-font-family:"Times New Roman";mso-hansi-font-family:"Times New Roman";mso-font-kerning:0pt;}/* Page Definitions */ @page WordSection1{size:595.3pt 841.9pt;margin:72.0pt 90.0pt 72.0pt 90.0pt;mso-header-margin:42.55pt;mso-footer-margin:49.6pt;mso-paper-source:0;}div.WordSection1{page:WordSection1;}'; var styles = ""; // Aggregate parts of the file together var fileContent = statics.mhtml.top.replace("_html_", statics.mhtml.head.replace("_styles_", styles) + statics.mhtml.body.replace("_body_", markup.html())) + mhtmlBottom; // Create a Blob with the file contents var blob = new Blob([fileContent], { type: "application/msword;charset=utf-8" }); saveAs(blob, fileName + ".doc"); }; })(jQuery); 複製代碼
該插件的主要原理就是獲取dom節點內容,而後將其用模板拼接成字符串,而後生成Blob對象後使用saveAs保存。

瞭解了原理後其實咱們能夠不用這個插件本身完成導出。以下是個人項目中的實現:
<pre>
const mhtml={
top: "<!DOCTYPE html>\n<html xmlns:o=\"urn:schemas-microsoft-com:office:office\"\n" +
"      xmlns:w=\"urn:schemas-microsoft-com:office:word\"\n" +
"      xmlns:dt=\"uuid:C2F41010-65B3-11d1-A29F-00AA00C14882\"\n" +
"      xmlns=\"http://www.w3.org/TR/REC-html40\">\n_html_</html>",
head: "<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n<style>\n_styles_\n</style>\n</head>\n",
body: "<body>_body_</body>"}</pre>
複製代碼
const exportReport=(styles,html,reportName)=>{
    let fileContent = mhtml.top.replace("_html_", mhtml.head.replace("_styles_", styles)+
        mhtml.body.replace("_body_",html));
    let blob = new Blob([fileContent], { type: "application/msword;charset=utf-8" });
    saveAs(blob, reportName+".doc");
}

在此我傳入了樣式參數styles和報告名稱reportName,項目中沒有用到圖片的導出,因此此處作了簡化,導出圖片的須要能夠直接參考以上jQuery插件的實現。git

實際開發中須要注意的是,html文檔的有些樣式在word中是不能識別的,如後代元素選擇器等,我採起的作法是直接在jsx中寫行內樣式,如:github

const tdStyle={ borderTop:'solid black 1.0pt',borderLeft:'solid black 1.0pt',
    padding:'5px 0',whiteSpace: 'nowrap'};
    

報告內容一方面做爲html文檔要在web上顯示,另外一方面又須要導出,在樣式處理上我採起了一種不太合理的方式,即一樣公共的樣式我使用了兩個文件,以下圖:web

reportTpl.css for web,reportExportStyle.js for 導出

const styles=`
    @page WordSection1{
        size:595.3pt 841.9pt;
        margin:72.0pt 90.0pt 72.0pt 90.0pt;
        mso-header-margin:42.55pt;
        mso-footer-margin:49.6pt;
        mso-paper-source:0;
        layout-grid:15.6pt;
    }`

(這在維護上會有點不便,後來在網上看到是否能夠採用Juice等包實現一套樣式完成此兩種功能)npm

導出word文檔過程當中遇到的一些細節問題,我是經過直接建立word文檔,而後將其另存爲html文件去查看其html源碼而後再去嘗試完成。記錄開發中遇到的其它問題處理以下: 1.jsx換行的實現 canvas

word文件另存爲html文件換行的實現
2.table中單元格內容換行問題,使用whiteSpace: 'nowrap'屬性(這裏看着簡單,實際開發中一直沒想到,一直在嘗試調整列寬,不加此屬性table會被壓縮在紙張內(下圖紅框內)致使表格顯示很是難看,加了這個後表格會被撐開,以下圖),
3.導出word中紙張橫向的實現

@page WordSection1
{   size:595.3pt 841.9pt;
    margin:72.0pt 90.0pt 72.0pt 90.0pt;
    mso-header-margin:42.55pt;
    mso-footer-margin:49.6pt;
    mso-paper-source:0;
    layout-grid:15.6pt;
}
div.WordSection1
{page:WordSection1;}
@page WordSection2
{size:841.9pt 595.3pt;
    mso-page-orientation:landscape;
    margin:90.0pt 72.0pt 90.0pt 72.0pt;
    mso-header-margin:42.55pt;
    mso-footer-margin:49.6pt;
    mso-paper-source:0;
    layout-grid:15.6pt;}
div.WordSection2
{page:WordSection2;}

4.目前有一個問題沒有解決思路,導出的word文檔在wps上默認以web版式顯示,暫不知道如何配置實現默認以頁面視圖顯示,歡迎給出解決方案。

最後,Talk is cheap,Show me the code。附上demo地址,供參考,歡迎交流!

相關文章
相關標籤/搜索