【问题标题】:How to export data to excel using react libraries如何使用 React 库将数据导出到 Excel
【发布时间】:2022-01-20 03:43:05
【问题描述】:

我正在使用 react-html-to-excel 将我的表格转换为 excel,但我想要的是不要将第一列导出到 excel 即第一列不应该导出到 excel 我已经阅读了 this library i am using 的文档但没有'没有找到任何东西

我的代码

 <div className="App">
      <ReactHTMLTableToExcel
        id="test-table-xls-button"
        className="download-table-xls-button"
        table="table-to-xls"
        filename="test"
        sheet="tablexls"
        buttonText="Download as XLS"
      />
      <table id="table-to-xls">
        <thead>
          <tr>
            <th>Firstname</th>
            <th>Lastname</th>
            <th>Age</th>
          </tr>
        </thead>
        <tbody>
          {data.map(item => (
            <tr>
              <td>{item.firstname}</td>
              <td>{item.lastname}</td>
              <td>{item.age}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>

Link of codesand box full code

如果这个库不支持它,那么我愿意使用任何其他做这些事情的库。

【问题讨论】:

  • 第一列是名字或吉尔
  • @MohammadAliRony 第一列表示整个第一列,例如她的名字、吉尔、大卫、尼克,我不想导出该列

标签: javascript excel reactjs


【解决方案1】:

我可以提出以下两个模块,因为我已经在生产中成功使用了它们(还有自定义列):

  1. react-data-export
  2. react-csv

第三个,经过快速搜索,看起来很有希望(虽然我没有用过)

  1. react-export-excel --> 它确实支持 TypeScript

你当前使用的库不支持根据这个issue删除excel文件中的列,这里也提出了第四个选项:

  1. react-csv-creator

编辑:好的,我创建了两个示例。 第一个可以在here 找到并使用我的第二个nd 提案react-csv

下面是第二个,它使用了我的第三个rd提案,react-export-excel

2nd 编辑:我已经更新了这两个示例,列现在是从您的对象的结构中定义的,并且提出了两种删除不需要的列的方法(按键-value firstname 或按索引 - 第一个st)。

请注意,如果对象的结构在您的数据中是一致的(每个条目应具有相同的列),上述方法将成功运行。

我在两个示例中使用的 camelCase 方法取自 here

import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
import ReactExport from "react-export-excel";
const ExcelFile = ReactExport.ExcelFile;
const ExcelSheet = ReactExport.ExcelFile.ExcelSheet;
const ExcelColumn = ReactExport.ExcelFile.ExcelColumn;

function App () {
    
    const data = [
        { firstname: "jill", lastname: "smith", age: 22 },
        { firstname: "david", lastname: "warner", age: 23 },
        { firstname: "nick", lastname: "james", age: 26 }
    ];

    const camelCase = (str) =>  {
        return str.substring(0, 1).toUpperCase() + str.substring(1);
    };

    const filterColumns = (data) => {
        // Get column names
        const columns = Object.keys(data[0]);

        // Remove by key (firstname)
        const filterColsByKey = columns.filter(c => c !== 'firstname');

        // OR use the below line instead of the above if you want to filter by index
        // columns.shift()

        return filterColsByKey // OR return columns
    };

    return (
        <div className="App">
            <ExcelFile filename="test">
                <ExcelSheet data={data} name="Test">
                    {
                        filterColumns(data).map((col)=> {
                            return <ExcelColumn label={camelCase(col)} value={col}/>
                        })
                    }
                </ExcelSheet>
            </ExcelFile>
            <table id="table-to-xls">
                <thead>
                <tr>
                    <th>Firstname</th>
                    <th>Lastname</th>
                    <th>Age</th>
                </tr>
                </thead>
                <tbody>
                {data.map(item => {
                    return (
                        <tr>
                            <td>{item.firstname}</td>
                            <td>{item.lastname}</td>
                            <td>{item.age}</td>
                        </tr>
                    );
                })}
                </tbody>
            </table>
        </div>
    );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

【讨论】:

  • 你能帮我举一个例子,它可以在导出时隐藏行,就像我不想导出第一列'
  • @manishthakur 我已经用示例更新了我的答案,希望对您有所帮助!
  • 嘿,您的两个示例都很好,但是存在问题,问题是数据是动态的,有时我可以有 5 列我可能有 8 列,并且在您的代码中定义要导出的列是手动,例如 react-csv 中的 { label: "Lastname", key: "lastname" }, { label: "Age", key: "age" } ]; 和示例 2 中的 &lt;ExcelFile&gt; &lt;ExcelSheet data={data} name="test"&gt; &lt;ExcelColumn label="Lastname" value="lastname" /&gt; &lt;ExcelColumn label="Age" value="age" /&gt; &lt;/ExcelSheet&gt; &lt;/ExcelFile&gt;react-export-excel
  • @manishthakur 我再次更新了我的答案(两个示例),现在列由数据定义并按选择过滤(提到了两种过滤方法)。
  • react export excel 不支持打字稿
【解决方案2】:

您可以创建一个简单的hack,通过覆盖获取表格 HTML 以格式化 XLS 文档的 ReactHTMLTableToExcel.format 函数来操作表格 HTML 代码。

ReactHTMLTableToExcel.format = (s, c) => {
  // If there is a table in the data object
  if (c && c['table']) {
    // Get the table HTML
    const html = c.table;

    // Create a DOMParser object
    const parser = new DOMParser();

    // Parse the table HTML and create a text/html document
    const doc = parser.parseFromString(html, 'text/html');

    // Get all table rows
    const rows = doc.querySelectorAll('tr');

    // For each table row remove the first child (th or td)
    for (const row of rows) row.removeChild(row.firstChild);

    // Save the manipulated HTML table code
    c.table = doc.querySelector('table').outerHTML;
  }

  return s.replace(/{(\w+)}/g, (m, p) => c[p]);
};

您已经过滤了表格 HTML 并删除了第一列。

您可以在Stackblitz project 中检查此工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-02
    • 1970-01-01
    • 2015-12-20
    • 1970-01-01
    • 1970-01-01
    • 2022-07-03
    • 1970-01-01
    相关资源
    最近更新 更多