0

I have a table that I managed to export to excel, using the following solution by @Nidhin Chalil, that I simplified a bit :

function tableToExcel(table, sheetName, fileName) {

    var uri = 'data:application/vnd.ms-excel;base64,',
        templateData = '<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><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></head><body><table>{table}</table></body></html>',
        base64Conversion = function (s) { return window.btoa(unescape(encodeURIComponent(s))) },
        formatExcelData = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) }

    if (!table.nodeType)
        table = document.getElementById('testExportId')
    
    var ctx = { worksheet: sheetName || 'Worksheet', table: table.innerHTML }

    var element = document.createElement('a');
    element.setAttribute('href', 'data:application/vnd.ms-excel;base64,' + base64Conversion(formatExcelData(templateData, ctx)));
    element.setAttribute('download', fileName);
    element.style.display = 'none';
    document.body.appendChild(element);
    element.click();
    document.body.removeChild(element);
    
}

Here's the jsfiddle : https://jsfiddle.net/g4znjchu/2/

Now I would like to export the 2nd table as well, in a separate sheet. I tried several things but with no success (by the way, the "sheetname" doesn't work either, but it's secondary to me)

Kev
  • 107
  • 9

1 Answers1

0

You could use another external script to perform your task: https://unpkg.com/exceljs/dist/exceljs.min.js

Tutorials:

Video: https://www.youtube.com/watch?v=4vyAJzzfzjM


async function exportData() { 
  const workbook = new ExcelJS.Workbook();
  const sheet = workbook.addWorksheet('My Sheet');

  sheet.addTable({
    name: 'MyTable',
    ref: 'A1',
    style: { theme: 'TableStyleDark3', showRowStripes: true },
    columns: [{ name: 'Date' }, { name: 'Amount' }],
    rows: [
      [new Date('2019-07-20'), 70.10],
      [new Date('2019-07-21'), 70.60],
      [new Date('2019-07-22'), 70.10],
    ],
  });
 
  const buffer = await workbook.xlsx.writeBuffer()
  utils.downloadFile({ base64Binary: buffer.toString('base64')}, "file-name", "xlsx")
}
 
return exportData()


Include the following ExcelJS js-library in your HTML file:

<html>
<head>
<script src="https://unpkg.com/exceljs/dist/exceljs.min.js"></script>
...
sylvain
  • 853
  • 1
  • 7
  • 20