Skip to content Skip to sidebar Skip to footer

How To Export Data To Excel Using React Libraries

I am using react-html-to-excel to convert my table to excel but what I want is to not to export the first column to excel i.e the first column should not exported to excel i have

Solution 1:

I can propose the following two modules since I have already used them successfully in production (with custom columns also):

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

And a third one, after a quick search, which looks promising (I haven't used it though)

  1. react-export-excel --> It does not support TypeScript

The library that you are currently using does not support the removal of columns in the excel file according to this issue, which also proposes a fourth option:

  1. react-csv-creator

EDIT: Ok, I have created two examples. The first can be found here and uses my 2 proposal, react-csv

The second is the following, which uses my 3 proposal, react-export-excel

2 EDIT: I have updated both examples, the columns now are defined from your object's structure, and two ways of removing the unwanted column are proposed (by key-value firstname or by index - the 1 one).

Please take into account that the above methods will work successfully if the objects' structure is consistent in your data (each entry should have the same columns).

The camelCase method that I have used in both examples was taken from here.

importReactfrom"react";
importReactDOM from"react-dom";
import"./styles.css";
importReactExportfrom"react-export-excel";
constExcelFile = ReactExport.ExcelFile;
constExcelSheet = ReactExport.ExcelFile.ExcelSheet;
constExcelColumn = ReactExport.ExcelFile.ExcelColumn;

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

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

    constfilterColumns = (data) => {
        // Get column namesconst 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 (
        <divclassName="App"><ExcelFilefilename="test"><ExcelSheetdata={data}name="Test">
                    {
                        filterColumns(data).map((col)=> {
                            return <ExcelColumnlabel={camelCase(col)}value={col}/>
                        })
                    }
                </ExcelSheet></ExcelFile><tableid="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);

Solution 2:

You can create a simple hack to manipulate the table HTML code by overriding the ReactHTMLTableToExcel.format function which gets the table HTML to format the XLS document.

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

    // Create a DOMParser objectconst parser = newDOMParser();

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

    // Get all table rowsconst 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]);
};

And you've got the table HTML filtered and with the first column removed.

You can check this working in this Stackblitz project.

Post a Comment for "How To Export Data To Excel Using React Libraries"