简体   繁体   中英

Export data from mysql to xls using PHPExcel

I want to export some data from my mysql db, to excel file. I'm using PHPExcel library to do it. I have a code like this:

include 'PHPExcel/PHPExcel.php';
include 'config.php' //here I connect to db
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$sheet = $objPHPExcel->getActiveSheet();
$r = mysql_fetch_array(mysql_query("SELECT * FROM Users WHERE ID=6"));
..
Some cells formatting here
..
$sheet->SetCellValue('A1', "NUMER ZLECENIA: ".$r["ID"]);
..
Rest of formatting
..
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
header('Content-Type: application/vnd.ms-excel; charset=UTF-8');
header('Content-Disposition: attachment;filename="01simple.xls"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
exit;

Now when I run that, the file download successfully, but when I'm trying to open it I see the error: "A file is in a different file format than its extension indicates.", But when I remove the .$r["ID"] and place instead of it a number, the file open just fine.

May it be caused by wrong encoding, in db i have encoding UTF-8, but ID is only number. I don't have idea why it's not working.

Does $r["ID"] actually exist? is it $r["id"] ?

Open the file in a text editor and look for obvious error messages... but I think your column names are probably lower case.

Note that charset=UTF-8 is meaningless, it ony applies to content sent to the browser; the file isn't opened in the browser, but in MS Excel, which isn't aware of charsets sent to a web browser

I tried and found something that worked:

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
ob_end_clean();
header('Content-Type: application/vnd.ms-excel; charset=UTF-8');
header('Content-Disposition: attachment;filename="01simple.xls"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
exit;

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