Tìm kiếm trên Nosomovo

Cách xuất nội dung Html ra file Word bằng Javascript

How-to-Export-HTML-to-Word-Document-with-JavaScript

Bạn có một đoạn mã html và muốn xuất nội dung html này ra file word? Nếu bạn chưa biết cách thực hiện hãy tham khảo cách sau nhé:

1. HTML

<div id="source-html">
      Đặt nội dung html cần xuất vô đây.  
</div>

2. Javascript

Đoạn script sau sẽ giúp bạn xuất nội dung html trong id source-html ở trên.

<script type="text/javascript">
    function exportHTML(){
       var header = "<html xmlns:o='urn:schemas-microsoft-com:office:office' "+
            "xmlns:w='urn:schemas-microsoft-com:office:word' "+
            "xmlns='http://www.w3.org/TR/REC-html40'>"+
            "<head><meta charset='utf-8'><title>Export HTML to Word Document with JavaScript</title></head><body>";
       var footer = "</body></html>";
       var sourceHTML = header+document.getElementById("source-html").innerHTML+footer;
       
       var source = 'data:application/vnd.ms-word;charset=utf-8,' + encodeURIComponent(sourceHTML);
       var fileDownload = document.createElement("a");
       document.body.appendChild(fileDownload);
       fileDownload.href = source;
       fileDownload.download = 'document.doc';
       fileDownload.click();
       document.body.removeChild(fileDownload);
    }
</script>

Hy vọng hữu ích với bạn!

Nosomovo

 

Thẻ: , ,
Chia sẻ:
Zalo Gọi ngay