简体   繁体   English

使用PHPExcel将数据从mysql导出到xls

[英]Export data from mysql to xls using PHPExcel

I want to export some data from my mysql db, to excel file. 我想将一些数据从我的mysql数据库导出到excel文件。 I'm using PHPExcel library to do it. 我正在使用PHPExcel库来做到这一点。 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. 现在,当我运行该文件时,文件下载成功,但是当我尝试打开它时,看到错误消息:“文件的格式不同于其扩展名所指示的文件格式。”,但是当我删除。$ r [ “ ID”]并放置而不是数字,文件打开就好了。

May it be caused by wrong encoding, in db i have encoding UTF-8, but ID is only number. 可能是由于错误的编码引起的,在db中我编码为UTF-8,但是ID只是数字。 I don't have idea why it's not working. 我不知道为什么它不起作用。

Does $r["ID"] actually exist? $r["ID"]确实存在吗? is it $r["id"] ? $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; 注意charset=UTF-8是没有意义的,它仅适用于发送到浏览器的内容; the file isn't opened in the browser, but in MS Excel, which isn't aware of charsets sent to a web browser 该文件未在浏览器中打开,但是在MS Excel中打开,它不知道发送到Web浏览器的字符集

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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