Pergunta

Looking to write the results of a mysql query into an excel file. I am currently using a pivot query to display the results as a preview in the web browser, but am wondering if anyone has used a library to convert the query into an excel file on the server?

Foi útil?

Solução

If you need more formats than just csv use PHPexcel it has good documentation and examples. I have used it a few times and it gives prety good results.

Outras dicas

A common practice I've used for awhile is to take the output of the query and convert it to a .CSV file. ON most computers with Excel installed, CSV files will be opened by Excel. Additionally you wont have to worry about any of the control characters or other Microsoft characters in excel that might be difficult to reproduce.

I would have code similar to this:

$output=''; //USED TO STORE ALL THE OUTPUT

$sql = "SELECT * FROM (table)";
$result = mysql_query($sql);
$count = mysql_num_rows($result);

for($s=0;$s<$sql;$s++)
{
    mysql_data_seek($s);
    $answer = mysql_fetch_array($result);

    $output .= $answer['field_1'] . ',';
    $output .= $answer['field_2'] . ',';
    $output .= $answer['field_3'] . ',';
    ....
    $output .= chr(10) . chr(13); //INSERT NEW LINE / CARRIAGE RETURN
}//END FOR S < SQL

file_put_contents('myfile.csv', $output);

Let me know if you have any questions! (You may need to fix a slight syntax error here and there I haven't ran this exact code)

(I've used the old Mysql methods here, but you may need to update for whichever database driver / library you are using.)

Just save the delimited output off to a variable and then download it with something like this.

$filename = "file_name".".csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
echo $output;
exit;
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top