将html表格导出为word文件并更改文件方向

export html table as word file and change file orientation

本文关键字:文件 方向 word html 表格      更新时间:2023-10-03

我有jquery功能,可以将html表导出到word文件。函数工作得很好,但我需要将一个word文件旋转到landsacpe方向。有人能帮我吗?

这里是js函数:

    <SCRIPT type="text/javascript">
$(document).ready(function () {
    $("#btnExport").click(function () {
        var htmltable= document.getElementById('tblExport');
        var html = htmltable.outerHTML;
        window.open('data:application/msword,' + ''uFEFF' + encodeURIComponent(html));
    });
});
  Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.docx");

将HTML导出到Microsoft Word

您可以通过在导出的HTML中包含CSS来设置页面方向、纸张大小和许多其他属性。有关可用样式的列表,请参阅带有MS Office前缀的样式属性有些样式具有相关性。例如,要设置mso页面方向,还必须设置页面的大小,如下代码所示。

更新时间:
使用Word 2010-2013在FireFox、Chrome、Opera、IE10-11中进行测试。对代码进行小的更改,使其能够使用Chrome和IE10。不适用于缺少窗口的旧版浏览器(IE<10)。Blob对象。如果您收到";createObjectURL不是函数";错误:https://stackoverflow.com/a/10195751/943435

2022年更新:
修复了损坏的GitHub链接

     @page WordSection1{
         mso-page-orientation: landscape;
         size: 841.95pt 595.35pt; /* EU A4 */
         /* size:11.0in 8.5in; */ /* US Letter */
     }
     div.WordSection1 {
         page: WordSection1;
     }

要查看完整的工作演示,请参阅:https://jsfiddle.net/78xa14vz/3/

用于导出到Word:的Javascript

 function export2Word( element ) {
   var html, link, blob, url, css;
   
   css = (
     '<style>' +
     '@page WordSection1{size: 841.95pt 595.35pt;mso-page-orientation: landscape;}' +
     'div.WordSection1 {page: WordSection1;}' +
     '</style>'
   );
   
   html = element.innerHTML;
   blob = new Blob([''ufeff', css + html], {
     type: 'application/msword'
   });
   url = URL.createObjectURL(blob);
   link = document.createElement('A');
   link.href = url;
   link.download = 'Document';  // default name without extension 
   document.body.appendChild(link);
   if (navigator.msSaveOrOpenBlob ) navigator.msSaveOrOpenBlob( blob, 'Document.doc'); // IE10-11
       else link.click();  // other browsers
   document.body.removeChild(link);
 };

以及HTML:

<button onclick="export2Word(window.docx)">Export</button>
<div id="docx">
  <div class="WordSection1">
    
     <!-- The html you want to export goes here -->
  </div>
</div>