Search code examples
phpexcelencodingdelimiterseparator

How to fix "tabs" in Excel Export (PHP)?


I applied this solution to solve an encoding problem I got exporting files to .CSV and Excel and it worked successfully, but now another problem emerged:

The tabs ("\t") I use in PHP as the delimiter for Excel files stopped working. It was working before I solve the previous problem. When I open the excel file, it display likes:

"ColumnAColumbBColumnC" (all together).

If a export it like csv ('Content-type: text/csv; charset=UTF-8') I have success, but not as Excel (Content-type: application/vnd.ms-excel; charset=UTF-8).

Any solution for this?

Note: using "," as a separator is not a good solution for me, because I have values with "," in some fields.


Solution

  • The tabs ("\t") I use in PHP as the delimiter for Excel files stopped working.

    Yes, that is correct.

    Despite this there is still a simple way to export to Excel.

    Use a table with <td> and <tr>, this does excel okay.

    An example:

    <?php
        header("Content-Type: text/plain");
        echo "<table border='1'>";
        echo "<tr>";
        echo "<th>Name</th>";
        echo "<th>First Name</th>";
        echo "<th>Department</th>";
        echo "<th>Date</th>";
        echo "<th>Topic</th>";
        echo "<th>State</th>";
        echo "<th>E-mail</th>";
        echo "<th>Place</th>";
        echo "<th>Registration fee</th>";
        echo '</tr>';
        echo '</table>';
        header("Content-disposition: attachment; filename=example_export_to_excel.xls");
        }
    ?>
    

    This works perfectly for export to excel. There are no libraries needed, why look complicated things simple as it can.