我正在研究reactjs项目,目前由于一些限制,应用程序需要在本地运行,直到我们得到一些许可,我们才能使它存活。使用客户端我上传excel文件读取数据并存储在变量中,并在应用程序中分发数据。但我面临着关于文件写入的问题。是否有可能在客户端写文件?
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>
);
}
是。你可以。如果你正在使用sheetjs来读取文件,你也可以使用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
};