-1

I have a controller that renders up a template file (twig) with some forms and a table response.

I need to export to an Excel file that table response. Is there a way to do that using Symfony, jQuery or Javascript?

I want to avoid using https://github.com/liuggio/ExcelBundle for which I need to recreate the objects. I already have them created as they are used in twigs.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
M. Marc
  • 512
  • 6
  • 25

1 Answers1

0

You can create an HTML table using Twig (using Twig is not necessary) and then save the output as an Excel file (.xls). You can use simple CSS in a <style> tag and in inline styles. For example:

<style>
  .last {
    color: red;
    text-align: center;
  }
</style>
<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Age</th>
      <th style="font-style: italic">Country</th>
    </tr>
  </thead>
  <tbody>
    {% for row in data %}
      <tr>
        <td>row.name</td>
        <td>row.age</td>
        <td>row.country</td>
      </tr>
    {% endfor %}
    <tr class="last">
      <td colspan="3">This last row is red</td>
    </tr>
  </tbody>
</table>

When you open the file in Excel, you probably get a message saying:

The file you are trying to open file.xls is in a different format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now?

There might be a workaround for this but I'm not sure.

This approach is simple and doesn't use any dependencies so it might be good enough for you if you don't need a very complex Excel file.

There are many resources with more information about this. See for example: How can I export tables to excel from a webpage.

Matias Kinnunen
  • 7,828
  • 3
  • 35
  • 46