Thursday, March 28, 2019

Cast the guts of an Excel sheet tab to an HTML table with js-xlsx!

Following up on this, I would really ask that you look to the source code at this to better understand how to get js-xlsx to work out for you. I needed to revamp my two methods given before like so:

processFile(event:any):void{
   let filePath = event.target.value;
   if (filePath && event.target.files && event.target.files.length){
      let file = event.target.files[0];
      var reader = new FileReader();
      reader.onload = function(e:any) {
         var data = e.target.result;
         data = new Uint8Array(data);
         this.processWorkbook(XLSX.read(data, {type: 'array'}));
      }.bind(this);
      reader.readAsArrayBuffer(file);
   }
}
 
processWorkbook(workbook){
   let excelTabs:Array<ExcelTab> = [];
   let counter:number = 0;
   workbook.SheetNames.forEach(function(sheetName) {
      try {
         let html:string =
               XLSX.utils.sheet_to_html(workbook.Sheets[workbook.SheetNames[counter]]);
         html = html.replace("<html><head><meta charset=\"utf-8\"/><title>SheetJS Table
               Export</title></head><body>","");
         let excelTab:ExcelTab = {
            Name: sheetName,
            Html: html.replace("</body></html>","")
         };
         excelTabs.push(excelTab);
      }
      catch(exception) {
         excelTabs.push({ Name: sheetName });
      }
      counter++;
   });
   console.log(excelTabs);
}

 
 

The reason for the try/catch is that I have seen error messages where it (the tool) cannot make the HTML for a tab. It vaguely says something about how it cannot split on undefined. The error is bubbling up from within js-xlsx itself and I have not yet set breakpoints in there to troubleshoot. ExcelTab is just something I tossed together in TypeScript that looks like this:

export interface ExcelTab {
   Name:string;
   Html?:string;
}

No comments:

Post a Comment