javascript - 使用 JavaScript 到 "Create"Microsoft Word 文档

标签 javascript jquery

我想使用 JavaScript 动态创建一个文档,然后在 Microsoft word 中打开该文档。这可能吗?这是我当前的代码:

<html>
  <head>
      <title></title>

       <script src="js/jquery-1.4.4.js" type="text/javascript"></script>
  </head>
  <body>

  <div id="myDiv">The quick brown fox jumped lazly over the dead log.</div>

  <script type="text/jscript">
     var printWindow = window.open("", "Print", "width=800,height=400,scrollbar=0");
     var printAreaHtml = $("#myDiv").attr("outerHTML");

     printWindow.document.open("text/html", "replace");
     printWindow.document.writeln("<html><head>")
     printWindow.document.writeln("<meta HTTP-EQUIV='Content-Type'  content='application/vnd.ms-word'>");
     printWindow.document.writeln("<meta HTTP-EQUIV='Content-Disposition' content='attachment;filename=print.doc'>");
     printWindow.document.writeln("</head>");
     printWindow.document.writeln("<body>");
     printWindow.document.write(printAreaHtml);

     printWindow.document.writeln("</body>");
     printWindow.document.writeln("</html>");
     printWindow.document.close();

     //    printWindow.print();     

  </script>

  </body>
</html>

最佳答案

我不确定你在上面的代码中到底想做什么,但这是我发现的一些关于访问 word 文档和文档中的表格的信息:

  1. Microsoft Word 对象模型

    此对象模型是 Microsoft Word(而非 Javascript)的一部分,它允许您从其他程序(不仅是网页,还包括任何计算机程序)远程“自动化”Word。

    它主要是为 Visual Basic 设计的,但可以通过网页中的 Javascript 访问 - 请参阅下面的第 2 段。

    然而,通过 Javascript 使用有点棘手,特别是因为您不能使用 visual basic 常量 - 您需要按值引用它们。如果你进一步研究这个,你很快就会明白我的意思。

    那么在哪里可以找到有关此对象模型的信息?

    如果您查找的话,在 Word 帮助文件中都可以找到。

    如果您查看 Word 帮助,在编程信息下,您会找到 Microsoft Word Visual Basic 编程引用。

    Word 对象模型,可让您执行解决问题所需的操作,例如:

    • 打开Word
    • 在 Word 中打开文档
    • 访问该 ActiveDocument 中的表集合。
    • 访问给定表格的行和单元格。
  2. 如何从 Javascript 访问它?

    我认为这可能只能通过 Internet Explorer(也许还有 Opera)来完成。

    这里你需要了解ActiveXObjects。

    ActiveXObjects(如果您不知道)是独立的计算机程序,可以启用附加功能。 Internet 上有很多 ActiveX 对象。

    当您安装 Word 时,这也会安装一个 ActiveX 对象来使 word 自动化,从而使您可以访问 Word 对象模型。

    所以在 javascript 中,让我们打开一个新的单词实例:

    var oApplication=new ActiveXObject("Word.Application");
    oApplication.Visible=true; // "Visible" is in the Word Object Model`
    

    给你。

    然后如果你想打开你的文件并获取表格:

    oApplication.Documents.Open("myfilename");
    var oDocument=oApplication.ActiveDocument;
    var oTable=oDocument.Tables(1);`
    

现在我把剩下的留给你继续做。

关于javascript - 使用 JavaScript 到 "Create"Microsoft Word 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6779926/

相关文章:

javascript - 未捕获的 TypeError : $. fn.DataTable.isDataTable 不是函数

javascript - 如何使用 CSS 制作基本形状?

javascript - Jquery - JSON.stringify,数组为空

javascript - bgStretcher 插件 - 多个实例

javascript - 移动设备上的 HTML 5 音频 .play() 延迟

javascript - jQuery:修改了带有过期 cookie 的弹出窗口,破坏了 cookie,但是在哪里?

javascript - Heroku "We' 抱歉,出了点问题。”由于 javascript_include_tag

javascript - 出现在滚动问题上

jquery - 通过 CSS 标签过滤 jQuery 结果

javascript - 如何使用 jQuery 只选择一个多个类