SheetJS Uncaught Error: Cannot access file

SheetJS Uncaught Error: Cannot access file

我正在尝试读取 XLSX 文件的一个单元格数据。但是我得到一个错误 "Uncaught Error: Cannot access file"

Uncaught Error: Cannot access file Hinnapakkumine.xlsx
at V (xlsx.full.min.js:12)
at qv (xlsx.full.min.js:22)
at Object.eg (xlsx.full.min.js:22)
at HTMLButtonElement.document.getElementById.onclick (Javascript.js:28)

我的最终目标是将一个单元格值替换为变量 hind,这段代码的重点是在单击按钮后获取联系表数据并编辑 excel 包含该数据的文件。为什么会出现此错误以及如何解决?

document.getElementById("saatmisnuppKontakt").onclick = function() {
    var laius = document.getElementById("laiusKontakt").value;
    var pikkus = document.getElementById("pikkusKontakt").value;
    var kõrgus = document.getElementById("korgusKontakt").value;
    var hind = 0;
    if (pikkus * laius >= 100){
        hind = pikkus * laius * 85;
    }else if (100 < pikkus * laius <= 200 ){
        hind = pikkus * laius * 77;
    }else if (200 < pikkus * laius <= 1000 ){
        hind = pikkus * laius * 75;
    }else if (1000 < pikkus * laius <= 2000 ){
        hind = pikkus * laius * 80;
    }else if (2000 < pikkus * laius <= 4000) {
        hind = pikkus * laius * 85;
    }
    if (3 <= kõrgus <= 6){
        hind *= 1;
    }else if(kõrgus == 7){
        hind *= 1.1;
    }else if (kõrgus == 8){
        hind *= 1.2;
    }else if (kõrgus == 9) {
        hind *= 1.3;
}

    var workbook = XLSX.readFile('Hinnapakkumine.xlsx');
    /* DO SOMETHING WITH workbook HERE */
    var first_sheet_name = workbook.SheetNames[0];
    var address_of_cell = 'G18';

    /* Get worksheet */
    var worksheet = workbook.Sheets[first_sheet_name];

    /* Find desired cell */
    var desired_cell = worksheet[address_of_cell];

    /* Get the value */
    var desired_value = (desired_cell ? desired_cell.v : undefined);
    window.alert(desired_value);

};

很遗憾,您不能在浏览器中使用 readFile:

readFile 仅在服务器环境中可用。浏览器无法 API 读取给定路径的任意文件,因此必须使用另一种策略。

为了扩充@Sstenn 的回答,您需要对服务器上托管的文件执行类似的操作。

// Optionally await on all of these asynchronous calls
// These promises resolve to the workbook or undefined
// Fetch the file from a server via a url
const workbook = await fetch(fileURL)
    // Take the response and turn the data into an array buffer
    .then(resp => resp.arrayBuffer())
    // User XLSX's read method to ingest the buffer and return the workbook
    .then(buff => XLSX.read(buff))
    // Be good and handle errors better than this
    // Or at least handle them in the downstream logic
    .catch(err => console.error(err))

对于本地文件,您需要使用“文件”类型的输入并使用文件 API。