Use js to read the data of the excel file locally from the server

now there is a requirement to read the data from the local excel file, which will be displayed on the page later.

< hr >

background:
now the project needs to write some data to serve as the data source for the front-end page display. The product hopes to use the excel table as a medium to facilitate users to enter data.

< hr >

process:
has found that the plug-in js-xlsx can be used to parse the contents of excel files, and it is no problem to use it in combination with < input type= "file" / > .

but the file needs to be operated by the user before it can be selected, which does not meet the requirements.

what you want is to go to the excel file to read the data while the page is loaded, and then do a series of subsequent operations. These are done automatically.

while using ajax to read the file, the read result cannot be converted to blob format, nor can it be converted to Blob constructor

.
var ajaxRead = function () {
  $.ajax({
    url: "http://localhost:8080/data.xls",
      method: "get",
      success: function (e) {
        // 
        // var files = new Blob(e, { type: "application/vnd.ms-excel" });
        var files = new Blob(e, { type: "text/csv,charset=UTF-8" });
    },
    error: function (e) {
      console.log(e);
    }
  });
};
    // exl
    var dealWithExl = function (files) {
        // H5FileReader
        var fileReader = new FileReader();
        fileReader.onload = function (ev) {
            try {
                var data = ev.target.result,
                    workbook = XLSX.read(data, {
                        type: "binary"
                    }), // excel
                    persons = []; // 
            } catch (e) {
                console.log("");
                return;
            }

            // 
            var fromTo = "";
            // 
            for (var sheet in workbook.Sheets) {
                if (workbook.Sheets.hasOwnProperty(sheet)) {
                    fromTo = workbook.Sheets[sheet]["!ref"];
                    console.log(fromTo);
                    persons = persons.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
                    // break; // 
                }
            }
            console.log(persons);
        };
        // 
        fileReader.readAsBinaryString(files[0]);
    };
< hr >

question:
is there any way to read data from excel files correctly?

or are there other ways to get local data?

Jan.22,2022

this is impossible. The browser cannot obtain the user's local file


when sending an ajax request without user authorization, add XMLHttpRequest.responseType:'blob' and then try
https://developer.mozilla.org.

.
Menu