Implementing Data Export and Custom Print in Layui Tables

Layui (version 2.4.5 and above) includes native methods for exporting table data. This guide covers how to utilize these built-in features, the differences between Layui's modular and non-modular builds, a native JavaScript fallback for exports, and how to implement a custom print fnuction with headers and footers.

  1. Exporting Data with Layui's Built-in API

For Layui versions 2.4.5 and higher, the table.exportFile method is available natively. Below is an example demonstrating how to render a table and trigger an Excel export.


<html>
<head>
  <meta charset="utf-8">
  <title>Layui Table Export Demo</title>
  <link rel="stylesheet" href="/path/to/layui/css/layui.css">
</head>
<body>

<div class="layui-btn-group">
  <button class="layui-btn" onclick="renderDataTable()">Load Data Table</button>
  <button class="layui-btn" onclick="downloadExcel()">Download Excel</button>
</div>



<script src="/path/to/layui/layui.js"></script>
<script>
  const staffDataset = [
    { id: 101, name: 'Alice', role: 'Engineer' },
    { id: 102, name: 'Bob', role: 'Designer' }
  ];

  function renderDataTable() {
    layui.use('table', function() {
      const table = layui.table;
      table.render({
        elem: '#employeeTable',
        data: staffDataset,
        cols: [[
          { field: 'id', title: 'ID', width: 100 },
          { field: 'name', title: 'Name', width: 150 },
          { field: 'role', title: 'Role', width: 150 }
        ]]
      });
    });
  }

  function downloadExcel() {
    layui.use('table', function() {
      const table = layui.table;
      const headers = ["Name", "Join Date", "Remark"];
      const rows = [
        ['Alice', '2023-01-15', 'Team Lead'],
        ['Bob', '2023-02-20', 'UI/UX']
      ];
      table.exportFile(headers, rows, 'staff_report.xls');
    });
  }
</script>
</body>
</html>

Understanding layui.js vs layui.all.js

When working with Layui, it is crucial to understand the distinction between the modular layui.js and the bundled layui.all.js:

  • layui.js (Modular): Requires you to use layui.use('table', function(){...}) to load and access modules. Without this wrapper, modules like layui.table will be undefined.
  • layui.all.js (Bundled): Contains all built-in modules upfront. The layui.use() method becomes largely ineffective for loading modules dynamically. Instead, you can directly access modules like layui.table globally in your scripts without the layui.use wrapper.

If you are using layui.all.js, the export function simplifies to:

function downloadExcelBundled() {
  const table = layui.table;
  const headers = ["Name", "Join Date", "Remark"];
  const rows = [
    ['Alice', '2023-01-15', 'Team Lead'],
    ['Bob', '2023-02-20', 'UI/UX']
  ];
  table.exportFile(headers, rows, 'staff_report.xls');
}

Note: Be cautious of version conflicts. For instance, if your project already relies on an older layer.js (e.g., v2.2), importing layui.js v2.4.5 (which bundles layer.js v3.1.1) may override the older version and alter existing UI behaviors.

  1. Native JavaScript Export Fallback

If you need to export data without relying on Layui's built-in API, you can construct an HTML table string, encode it to Base64, and trigger a download using an anchor tag.

<html>
<head>
  <style>
    .export-link { display: inline-block; padding: 10px 15px; background: #5FB878; color: #fff; cursor: pointer; text-decoration: none; }
  </style>
</head>
<body>
  <a class="export-link" onclick="generateExcel()" id="downloadAnchor">Export Data</a>

  <script>
    function generateExcel() {
      const records = [
        { user: 'John', contact: '555-0100', mail: 'john@test.com' },
        { user: 'Jane', contact: '555-0200', mail: 'jane@test.com' }
      ];
      
      let tableRows = '<tr><td>User</td><td>Phone</td><td>Email</td></tr>';
      records.forEach(rec => {
        tableRows += '<tr>';
        for (const prop in rec) {
          // Appending \t prevents Excel from formatting long numbers or dates as scientific notation
          tableRows += `<td>${rec[prop]}\t</td>`; 
        }
        tableRows += '</tr>';
      });

      const sheetName = 'Contact_List';
      const base64Uri = 'data:application/vnd.ms-excel;base64,';
      const htmlTemplate = `
        <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>${sheetName}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions>
        </x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head>
        <body></body></html>`;

      const anchor = document.getElementById('downloadAnchor');
      anchor.download = `${sheetName}.xls`;
      anchor.href = base64Uri + window.btoa(unescape(encodeURIComponent(htmlTemplate)));
    }
  </script>
</body>
</html>

  1. Custom Print Functionality

While Layui provides a default print button, it lacks the flexibility to add custom headers (like organization names or report dates) and footers (like operator names or print timestamps). By opening a new window and constructing the HTML manually, we can achieve a fully customized print layout.

function printCustomTableReport(tableId) {
  // Simulating dynamic metadata
  const orgTitle = "Global Corp";
  const reportLabel = "Daily Operations Overview";
  const opDate = "2023-10-25";
  const operatorName = "Admin";
  const printTimestamp = new Date().toLocaleString();

  const printableContainer = document.createElement("div");
  
  const customStyles = `
    <head>
      <div style="text-align:center;font-size:24px;font-weight:bold;">${orgTitle}</div>
      <div style="text-align:center;font-size:16px;font-weight:bold;">${reportLabel} - Date: ${opDate}</div>
      <style>
        body { font-size: 14px; color: #333; }
        table { width: 100%; border-collapse: collapse; }
        th, td { padding: 8px; border: 1px solid #999; text-align: center; }
        .layui-hide { display: none; }
      </style>
    </head>`;

  // Extract Layui table headers and body rows
  const headerHtml = $(".layui-table-box").find(".layui-table-header").html();
  const bodyHtml = $(`[lay-id="${tableId}"] .layui-table-body.layui-table-main table`).html();
  
  $(printableContainer).append(headerHtml);
  $(printableContainer).find("tr").after(bodyHtml);
  $(printableContainer).find(".layui-table-patch, .layui-table-col-special").remove();

  const customFooter = `
    <footer style="margin-top: 20px;">
      <div style="float:left;">Operator: ${operatorName}</div>
      <div style="float:right;">Printed at: ${printTimestamp}</div>
    </footer>`;

  const printWindow = window.open("_blank");
  printWindow.document.write(customStyles + $(printableContainer).prop("outerHTML") + customFooter);
  printWindow.document.close();
  printWindow.print();
  printWindow.close();
}

This custom approach is heavily inspired by the official table.js source code. The native LAYTABLE_PRINT implementation uses the exact same mechanism: it opens a new window, injects CSS styles, scrapes the layHeader and layMain HTML, removes special columns (like checkboxes or radio buttons), and calls window.print(). The custom version simply expands upon this by injecting specific metadata before and after the table structure.

Tags: LayUI Data Export Web Printing javascript Excel

Posted on Fri, 23 Oct 2026 16:51:51 +0000 by yahelb