如何使用PHP将SQL表导出为ex​​cel格式

所以我需要我的SQL表可以下载。 现在我的PHP文件创build了一个excel文件并强制下载,但是excel文件里面只有一个大的表格数据。

这是我的代码

$sql = mysql_query("SELECT * FROM table"); while ($row_user = mysql_fetch_assoc($sql)) { $userinfo[] = $row_user; print_r($row_user); header("Content-Disposition: attachment; filename=\"papi.xls\""); header("Content-Type: application/vnd.ms-excel;"); header("Pragma: no-cache"); header("Expires: 0"); $file = fopen("php://output","w"); foreach($userinfo as $data) { fputcsv($file,explode(',',$data),"\t"); } fclose($file); } 

任何帮助将不胜感激,提前谢谢。

有几个PHP库可以帮助您在强制下载之前格式化您的输出excel文件。 我有使用PHPExcel良好的经验。

使用PHPExcel不会改变访问表中的数据,但它会改变你如何处理MySQL的结果:

 //Collect result set $data = array(); while ($row = mysql_fetch_assoc($sql)){ $data[] = $row; } //initialize PHPExcel object $objPHPExcel = new PHPExcel(); $objPHPExcel->getProperties()->setCreator("AuthorName")->setTitle("DocumentTitle"); //Write Column Titles into first Row $col = 'A'; foreach($data[0] as $key => $val){ $objPHPExcel->setActiveSheetIndex(0)->setCellValue($col.1, $key); $col++; } //Write Data for($i = 0; $i < count($data); $i++){ $col = 'A'; $row = 2 + $i; foreach($data[$i] as $val){ $objPHPExcel->setActiveSheetIndex(0)->setCellValue($col.$row, $val); $col++; } } //Set Header header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename="DataExport.xlsx"'); header('Cache-Control: max-age=0'); //Output Results $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); ob_end_clean(); $objWriter->save('php://output'); 

这绝不是唯一的select,但是,我发现这个库有用于将数据导出到XLSX文件中,并具有其他选项来格式化或添加生成报告所需的方程式。

所以,这是我写的一个类,导出为CSV,并保持一切排列完美。

 <?php class exporter{ private $map = array(); private $data = array(); private $nr = "\n"; private $dl = ","; private $containerChar = "\""; private $exportData = ""; function extractFullMapData($data){ $map = array(); foreach($data as $row){ foreach($row as $colName => $col){ if(!in_array($colName, $map)){ $map[] = $colName; } } } $this->setMap($map); } function addData($row, $multipleRows){ if($multipleRows){ foreach($row as $curRow){ $this->addData($row); } }else{ if(empty($this->map)){ $this->extractMapData($row); } $newRow = array(); foreach($this->map as $varName){ if(isset($row[$varName])){ $newRow[$varName] = str_replace(, "\\".$this->containerChar, $row[$varName]); }else{ $newRow[$varName] = ""; } } $this->data[] = $newRow; } } function export(){ header('Content-Type: application/csv'); header('Content-Disposition: attachment; filename="export.csv"'); header('Pragma: no-cache'); $this->buildExport(); echo $this->exportData; } private function extractMapData($row){ $this->setMap(array_keys($row)); } private function setMap($map){ $this->map = $map; } private function buildExport(){ $exportData = ""; foreach($this->map as $varName){ $exportData .= ($exportData == "") ? "" : $this->dl; $exportData .= $this->containerChar.$varName.$this->containerChar; } foreach($this->data as $data){ $row = ""; $looped = false; foreach($data as $item){ $row .= (!$looped) ? "" : $this->dl; $row .= $this->containerChar.$item.$this->containerChar; $looped = true; } $exportData .= $this->nr.$row; } $this->exportData = $exportData; } } ?> 

这个代码是从我在我的框架中编写的类中派生出来的,它处理大量事情的输出。 我也写了一个可以读取这些数据的类。 这个课程的用法就是这样。

 <?php $exporter = new exporter(); $exporter->extractFullMapData($fullDataArray); $exporter->addData($fullDataArray, true); $exporter->export(); ?> 

像这样的东西应该工作。 我使用的是PDO而不是弃用的mysql。 我还包括准备声明,你可能想在大多数情况下使用bindParam来防止SQL注入…即使在这个例子中不需要。 你会注意到我也改变了你的头文件来表示一个CSV文件,而不是一个Excel文件。

 <?php $sql = "select * from table"; $dbh = new PDO("mysql:host=localhost; dbname=MYDB", "DBUSER", "DBPASSWORD"); $stmt = $dbh->prepare($sql); $stmt->execute(); header('Content-Type: application/csv'); header('Content-Disposition: attachment; filename=example.csv'); header('Pragma: no-cache'); $out = fopen('php://output', 'w'); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){ fputcsv($out, $row); } fclose($out); 

我认为把你扔掉的主要原因可能是你的爆炸声明,这通常是fputcsv所不需要的。 但是,我不熟悉你的数据。

这跟着你写一个CSV文件的例子。 如果您想使用Excel .xls或.xlsx文件,则可以使用PHPExcel。 这需要更长的时间来build立,文件不是最大的,但它做得很好。