[英]is it physically possible to write information to a JSON file without a server side language?
[英]File Writing Reactjs Without server side language
我正在研究 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>
);
}
是的,可以使用 JavaScript 在客戶端寫入文件。一種方法是使用內置的 JavaScript function window.URL.createObjectURL()。 這個 function 創建一個 URL 可以用來下載文件。 以下是如何使用此 function 下載 CSV 文件的示例:
// Create a link element const link = document.createElement("a"); // Some data const csvData = ['a','b'] // Set the link's href to a data URI containing the CSV data link.href = window.URL.createObjectURL(new Blob([csvData], {type: 'text/csv'})); // Set the link's download attribute to the desired file name link.download = "data.csv"; // Click the link to trigger the download link.click();
此代碼將創建一個新的鏈接元素,將其 href 設置為包含 CSV 數據的數據 URI,將下載屬性設置為所需的文件名,然后單擊鏈接以觸發下載。 請注意,此解決方案僅適用於支持 Blob 和 window.URL.createObjectURL() 函數的現代瀏覽器。
是的。 你可以。 你是用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
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.