none
Convert html tables to multiple Excel worksheets using Javascript

    Question

  • I am trying to export multiple tables from a webpage to an Excel workbook with one worksheet per table, has any one managed to do that without needing to transforming the tables into <rows> and leveraging the html <table> xml, ie inside <body></body>

    Currently I am using the below function but, while it does create multiple worksheets, it puts all tables into the first worksheet.


     function arrayToExcel(tablesId, filename) {  
    
    var uri = 'data:application/vnd.ms-excel;base64,';  
    
    var worksheetTemplate = '<x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions><table>{table}</table></x:ExcelWorksheet>';  
    
    var format = function(s, c) { return s.replace(/{(\w+)}/g, 
                 function(m, p) { return c[p]; }) }  
    
    var worksheets = tablesId.map(function(name){      return 
        format(worksheetTemplate, {worksheet: name});    }).join('');  
    
    var tables = tablesId.map(function(txt){      
        var table = document.getElementById(txt).innerHTML;     
        return format(tableTemplate, {table});    
    }).join('');  
    
    var formattedXML = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]>'          
    +'<xml><o:DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"><o:Author>Dominik Dumaine</o:Author><o:Created>'+ (new Date()).getTime() 
    +'</o:Created></o:DocumentProperties>'          +'<x:ExcelWorkbook><x:ExcelWorksheets>'          
    + worksheets          
    +'</x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></head><body>'          
    + tables          
    +'</body></html>'    , 
    base64 = function(s) { 
       return window.btoa(unescape(encodeURIComponent(s))) 
    }
    
    window.location.href = uri + base64(formattedXML);}

    Has anybody have any suggestion as to how I can amend the above so the different tables go to different worksheets?

    Thursday, November 16, 2017 5:02 AM

All replies

  • Hi,

    According to your description and code, but i can not reproduce your issue because of don't know your parameter value like name and txt, so i hope you could post complete code for us to test! 

    Best Regards,

    Eric   

    Friday, November 17, 2017 10:10 AM