Search code examples
parsingfetchxlsx

How to load and parse .xlsx file using fetch API and XLSX library


I'm importing these library:

<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/xlsx.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/jszip.js"></script>

and trying to fetch & parse local file saved in my project folder:

fetch('Eshop_product_list.xlsx').then(res => { 
    return res.blob();
}).then(res => {
    console.log('file:', res);
    var workbook = XLSX.read(res, {
        type: 'binary'
    });
});

But I can't get it working. I've tried different combinations of XLSX type arguments with res.blob(), res.text(), res.bufferArray() but everytime it is throwing an error.

What is the correct way?


Solution

  • Try to use res.arrayBuffer() instead of res.bufferArray()

    Replaced in your example:

    fetch('Eshop_product_list.xlsx').then(res => { 
        return res.arrayBuffer();
    }).then(res => {
        console.log('file:', res);
        var workbook = XLSX.read(new Uint8Array(res), {
            type: 'array'
        });
    });