0

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>
  );
}
2
  • Yes you can write to files using JS
    – innocent
    Commented Dec 25, 2022 at 20:05
  • Let me explain. When the app run. the user upload csv file and read data, and then user have to update the csv by writing data into it. When file upload, the createObjectURL is saved and used it when writing data. but its not working.
    – Hamid Shah
    Commented Dec 26, 2022 at 7:24

1 Answer 1

2

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
};
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.