javascriptreactjsxlsxfile-writingsheetjs

File Writing Reactjs Without server side language


I am working on reactjs project where the application, for now, need to be run locally due to some limitation we cant make it live yet until we got some permission. Using the Client side I upload the excel file read data and store in variable and distribute the data in the app. But I am facing issue regarding file writing. Is it possible to do file writing on Client side?

import "./styles.css";
import * as XLSX from "xlsx";
import { useState } from "react";

export default function App() {
  const [add, setAdd] = useState("");

  const writeData = () => {
    const f = new File(["array"], add);
    const workbook = XLSX.readFile(f);
    const sheet = workbook.Sheets[workbook.SheetNames[0]];
    sheet["H1"].v = "new value add";
    XLSX.writeFile(workbook, add);
  };

  const uploadFile = (e) => {
    let file = e.target.files[0];
    setAdd(URL.createObjectURL(file));
    const reader = new FileReader();
    reader.onload = (e) => {
      const data = e.target.result;
      const workbook = XLSX.read(data, { type: "array" });
      const patientSheet = workbook.SheetNames[0];
      const worksheet1 = workbook.Sheets[patientSheet];
      const patient = XLSX.utils.sheet_to_json(worksheet1);
      console.log(patient);
    };
    reader.readAsArrayBuffer(file);
  };

  return (
    <div className="App">
      <input type="file" accept=".csv, .xlsx" onChange={uploadFile} />
      <button onClick={writeData}>Write Data</button>
    </div>
  );
}

Solution

  • Yes. You can. You are using sheetjs for file reading, you can also write with sheetjs.

    import * as XLSX from "xlsx";
    const ExportToExcel = (yourData) => {
        const worksheet = XLSX.utils.json_to_sheet(yourData); //formate data from JSON to sheet 
        const workbook = XLSX.utils.book_new(); //create new workbook
        //append data to sheet
        const sheetData = XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet Name");
        XLSX.writeFile(workbook, "Name_of_output_file.xlsx"); //after writing file will be downloaded
    };