DEV Community

Cover image for How to create and download xlsx on the client?
Nar Zantaria
Nar Zantaria

Posted on

How to create and download xlsx on the client?

Can you please tell me if this code can be simplified, or is it done correctly:

import React, { Fragment } from 'react';
import xlsx from 'node-xlsx';
import download from 'downloadjs';

function TableDownload({ data }) {
  return (
    <Fragment>
      <button onClick={_ => {
        const qwerty = [[1, 2, 3], ['a', 'b', 'c']];
        let buffer = xlsx.build([{ name: "mySheetName", data: qwerty }]).toString('base64');
        download(atob(buffer), 'data.xlsx', { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
      }}>12345</button>
    </Fragment>
  );
}

export default TableDownload;
Enter fullscreen mode Exit fullscreen mode

Everything happens on the client side: a file is created, which is then downloaded, without reloading the page. The data is first converted to the "base64" string and then decoded. Everything works, but I want the code to be "in line with tradition", and there was nothing superfluous in it.

Regards.

Top comments (0)