【问题标题】:how can I export react to word document如何导出对 word 文档的反应
【发布时间】:2020-04-05 18:57:59
【问题描述】:

我有一个 React 应用程序,我想将一些 html 内容导出到 word 文档并下载它。 例如:

<div> Hello World!!!</div>
<input type="button" onClick={exportToWord()}/>

我搜索一个函数来处理带有文本 Hello world!!! 的 word 文档。

【问题讨论】:

    标签: reactjs ms-word export docx


    【解决方案1】:

    您可以将redocx 库用于word documentsReact 你可以通过 NPM 安装 redocx

    npm i redocx
    

    这个简单的例子将在word doc中渲染Hello World

    import React from 'react'
    import { render, Document, Text } from 'redocx'
    
    class App extends React.Component {
      render() {
        return (
          <Document>
            <Text>Hello World</Text>
          </Document>
        )
      }
    }
    
    render(<App />, `${__dirname}/example.docx`)
    

    对于演示,您可以克隆此 repo 并在本地运行

    git clone https://github.com/nitin42/redocx.git
    cd redocx
    npm install
    npm run example
    

    你可以在这里找到所有文档redocx docs

    【讨论】:

      【解决方案2】:

      您可以使用docx npm package

      这里是一个按钮的onClick回调示例:

      async function exportToWord() {
          const doc = new Document({
              sections: [{
                  properties: {},
                  children: [
                      new Paragraph({
                          children: [
                              new TextRun("Hello World")
                          ],
                       }),
                  ],
               }]
          });
          const buffer = await Packer.toBuffer(doc);
          const blob = new Blob([buffer], {type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"});
          const link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = 'my.docx';
          link.click();
      }
      

      【讨论】:

      • 这不会将 react 组件转换为 word 文档
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-21
      • 2014-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-05
      相关资源
      最近更新 更多