Search code examples
javascriptsheetjsjs-xlsx

SheetJs Convert workbook back to arraybuffer


I am new to SheetJs. We have this remote excel file within our internal platform which can be accessed only using API. I have to read this Excel file and update the excel contents and upload the excel file changes back using the API. The internal Platform API I use accepts blob as input and updates the original excel. The problem here is once I read the ArrayBuffer from the XLSX and update the workbook object how would I convert this workbook back to ArrayBuffer so that API would take it?

oReq.onload = function (e) {
 const arraybuffer = oReq.response; //Excel ArrayBuffer retrieved using Platform API
 let data = "";
 const bytes = new Uint8Array(arraybuffer);
 for (let i = 0; i < bytes.byteLength; i++) {
    data += String.fromCharCode(bytes[i]);
 }

 var workbook= XLSX.read(data, {
    type: 'binary'
 });

 //I Update the workbook contents here
 //How to convert workbook back to ArrayBuffer?
}

Solution

  • Finally I was able to find an answer here after little more digging.

    var out= XLSX.write(wb, {bookType:'xlsx',  type: 'binary'});
    let blob = new Blob([s2ab(out)],{type:"application/octet-stream"});
    
    
    //s2ab method
    function s2ab(s) { 
                    var buf = new ArrayBuffer(s.length); //convert s to arrayBuffer
                    var view = new Uint8Array(buf);  //create uint8array as viewer
                    for (var i=0; i<s.length; i++) view[i] = s.charCodeAt(i) & 0xFF; //convert to octet
                    return buf;    
    }