toHtmlTable static method

String toHtmlTable(
  1. List<Map<String, dynamic>> data, {
  2. List<String>? columns,
  3. String? title,
  4. bool includeStyles = true,
})

Export data to HTML table format

Implementation

static String toHtmlTable(List<Map<String, dynamic>> data, {
  List<String>? columns,
  String? title,
  bool includeStyles = true,
}) {
  if (data.isEmpty) return '<p>No data</p>';

  final cols = columns ?? data.first.keys.toList();
  final buffer = StringBuffer();

  if (title != null) {
    buffer.writeln('<h1>${_escapeHtml(title)}</h1>');
  }

  if (includeStyles) {
    buffer.writeln('''
<style>
table { border-collapse: collapse; width: 100%; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
th { background-color: #f2f2f2; font-weight: bold; }
tr:nth-child(even) { background-color: #f9f9f9; }
tr:hover { background-color: #f1f1f1; }
</style>
''');
  }

  buffer.writeln('<table>');
  buffer.writeln('  <thead>');
  buffer.writeln('    <tr>');
  for (final col in cols) {
    buffer.writeln('      <th>${_escapeHtml(col)}</th>');
  }
  buffer.writeln('    </tr>');
  buffer.writeln('  </thead>');
  buffer.writeln('  <tbody>');

  for (final row in data) {
    buffer.writeln('    <tr>');
    for (final col in cols) {
      buffer.writeln('      <td>${_escapeHtml(row[col]?.toString() ?? '')}</td>');
    }
    buffer.writeln('    </tr>');
  }

  buffer.writeln('  </tbody>');
  buffer.writeln('</table>');

  return buffer.toString();
}