简体   繁体   中英

Output mysql query result to formated excel table with php

I have to fetch the result of a mysql query to a "user friendly" excel (.xls or.xlsx) table. I don't want to use imports or packages for php.

This is what I got so far:

<?php

function query_to_csv($database, $query, $filename, $attachment = false, $headers = true) {

if ($attachment) {
    // send response headers to the browser
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment;filename=' . $filename);
    $fp = fopen('php://output', 'w');
} else {
    $fp = fopen($filename, 'w');
}

$result = mysqli_query($database, $query) or die(mysqli_error($database));
foreach ($result as $fields) {
    fputcsv($fp, $fields);
    
}
    
    fclose($fp);
} 

This is the Result

How can I get the array sperated in different Cells?

Sadly I had to use a library named PHP Excel (old) or PhpSpreadsheet (new).

$objReader->setDelimiter(',');

That's the PHP Excel Function to set the Delimiter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM