0

I'm trying to make an Excel Sheet with a javascript function in React, but when I try to enter to the page, and the button which has the onClick is not working.


export default function DescargaExcelHTML() {
  const descargaExcel = (tableID, filename = "") => {
    console.log(tableID);
    let downloadLink;
    let datatype = "application/vnd.ms-excel";
    let tableSelect = document.getElementById(tableID);
    let tableHTML = tableSelect.outerHTML.replace(/ /g, "%20");
    filename = filename ? filename + ".xlsx" : "excel_data.xlsx";
    downloadLink = document.createElement("a");
    document.body.appendChild(downloadLink);

    if (navigator.msSaveOrOpenBlob) {
      let blob = new Blob(["\ufeff", tableHTML], { type: datatype });
      navigator.msSaveOrOpenBlob(blob, filename);
    } else {
      downloadLink.href = "data:" + datatype + "," + tableHTML;
      downloadLink.download = filename;
      downloadLink.click();
    }
  };

  return (
    <>
      <div className="overflow-x-auto">
        <table id="prueba" className="table w-full">
          <thead>
            <tr>
              <th></th>
              <th>Name</th>
              <th>Job</th>
              <th>Favorite Color</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <th>1</th>
              <td>Cy Ganderton</td>
              <td>Quality Control Specialist</td>
              <td>Blue</td>
            </tr>
          </tbody>
        </table>
      </div>
      <button
        className="btn btn-primary"
        onClick={descargaExcel("prueba", "pruebaDescarga")}
      >
        Download Excel
      </button>
    </>
  );
}

Also when I refresh the page I'm getting an outerHTML error:

Uncaught TypeError: Cannot read properties of null (reading 'outerHTML') at line let tableHTML = tableSelect.outerHTML.replace(/ /g, "%20");

  • The issue is likely that ```let tableSelect = document.getElementById(tableID);``` is not getting an html element. Can you console log after you declare this variable? – Sean May 19 '22 at 15:42
  • Yes, the function is not getting an HTML, I'm going to edit the question to add all the code – Juan Sebastian Arias Robayo May 19 '22 at 15:48
  • https://stackoverflow.com/questions/38093760/how-to-access-a-dom-element-in-react-what-is-the-equilvalent-of-document-getele – epascarello May 19 '22 at 16:10

1 Answers1

1

Try changing:
onClick={descargaExcel("prueba", "pruebaDescarga")}
By:
onClick={() => descargaExcel("prueba", "pruebaDescarga")}

efra
  • 26
  • 2