Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Client-Side HTML Table to Excel Export Using Base64 Data URIs

Tech 1

A lightweight method for generating Excel-compatible files directly from HTML tables utilizes Base64-encoded data URIs with Microsoft Office XML namespaces. This approach requires no server-side processing or external dependnecies.

HTML Structure

<button id="downloadTrigger">Export to Excel</button>

<table id="sourceData">
  <thead>
    <tr>
      <th>Product</th>
      <th>Revenue</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Widget A</td>
      <td>12500</td>
    </tr>
  </tbody>
</table>

Core Implementation

The solution constructs a valid Excel document by wrapping table markup within Office-specific XML schemas, then encoding the result as a downloadable payload:

const exportTableToExcel = (tableIdentifier, worksheetName = 'Sheet1') => {
  const mimeHeader = 'data:application/vnd.ms-excel;base64,';
  
  const documentTemplate = `<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>
      <meta charset="UTF-8">
      <!--[if gte mso 9]>
        <xml>
          <x:ExcelWorkbook>
            <x:ExcelWorksheets>
              <x:ExcelWorksheet>
                <x:Name>${worksheetName}</x:Name>
                <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions>
              </x:ExcelWorksheet>
            </x:ExcelWorksheets>
          </x:ExcelWorkbook>
        </xml>
      <![endif]-->
    </head>
    <body>${document.getElementById(tableIdentifier).outerHTML}</body>
  </html>`;

  const binaryToAscii = (content) => window.btoa(unescape(encodeURIComponent(content)));
  
  return mimeHeader + binaryToAscii(documentTemplate);
};

Trigger Mechanisms

For anchor elements, bind the generated URI directly to the href attribute:

document.querySelector('#exportLink').addEventListener('click', function() {
  this.href = exportTableToExcel('sourceData', 'SalesReport');
  this.download = 'financial_data.xls';
});

For button elements or programmatic triggers lacking native download capabilities, instantiate a temporary anchor node to handle the binary stream:

document.getElementById('downloadTrigger').addEventListener('click', () => {
  const dataUri = exportTableToExcel('sourceData');
  const tempAnchor = document.createElement('a');
  
  tempAnchor.href = dataUri;
  tempAnchor.download = 'export.xls';
  tempAnchor.style.display = 'none';
  
  document.body.appendChild(tempAnchor);
  tempAnchor.click();
  document.body.removeChild(tempAnchor);
});

Technical Constraints

Direct assignment to window.location.href fails when handling Base64-encoded data URIs in modern browsers due to security policies restricting navigation to non-HTTP schemes. The temporary anchor element approach circumvents this limitation by leveraging the HTML5 download attribute within the same-origin context, preserving the filename specification capability that window.location lacks.

Tags: javascript

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.