1

I'm trying to export a table from MySql database to excel with PHP. But I'm getting the error that the file format or file extension is not valid. My current code is below:

$db = JFactory::getDBO();
$output = '';

$query = "SELECT * FROM  student_management_module";
$db->setQuery($query);
$rows = $db->loadObjectList();

$output .= '
    <table class="table" bordered="1">
        <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Program</th>
            <th>Class</th>
            <th>Start Date</th>
            <th>End Date</th>
        </tr>
';

foreach ($rows as &$row) {
    $output .= '
        <tr>
            <td>'.$row->name.'</td>
            <td>'.$row->email.'</td>
            <td>'.$row->program.'</td>
            <td>'.$row->class.'</td>
            <td>'.$row->start_date.'</td>
            <td>'.$row->end_date.'</td>
            <td>'.$row->student_id.'</td>
    ';
}
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition: attachment; filename='download.xlsx");
header("Pragma: no-cache");

$output .= '</table>';
echo $output;

Thanks in advance, any help would be much appreciated.

Kilter
  • 41
  • 5

1 Answers1

0

Change the filename's extension from .xlsx to .xls.


If you're still having problems after that, you may have an incorrect MIME type for an extension in the registry; repair steps and more information can be found in the below links.


ashleedawg
  • 20,365
  • 9
  • 72
  • 105
  • ok, I changed the content-type to "application/vnd.ms-excel" and filename to "download.xls" and it opens. But it gives a warning that the file format and extension of "download.xls" don't match. Also, when I open the excel file, there are no lines to seperate each cell. – Kilter Jul 07 '18 at 22:39
  • If could be related to which version of Excel you are using, or the issue might be a registry setting. See the links I've added to the answer for more information. – ashleedawg Jul 07 '18 at 23:19