使用phpexcel从mysql数据库创buildexcel报告

我有一个SQL查询,显示每名员工的出席logging,所以我现在想要的是从它生成一个Excel报告,但我真的不知道如何phpexcel的作品,我也用于像水晶报表拖放报告工具。 有人可以帮助它在phpexcel。 这里是我从MySQL数据库完整的代码:

try{ $con = new PDO("mysql:host=$host;dbname=$db",$user,$pass); $con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); $con->exec('SET NAMES "utf8"'); } catch(PDOException $e){ echo $e->getMessage(); exit(); } //print first employee table try{ $query = $con->prepare("SELECT * FROM emptb WHERE Department = :dept AND SectionName = :section AND LineName = :line ORDER BY id ASC"); $query->bindParam(':dept',$dept); $query->bindParam(':section',$section); $query->bindParam(':line',$line); $query->execute(); } catch(PDOException $e){ echo $e->getMessage(); exit(); } while($row = $query->fetch()) { echo <<<_END ID: <input type='text' value='$row[EmpID]' readonly='readonly'/> Employee: <input type='text' value='$row[Lastname], $row[Firstname]' readonly='readonly'/> <p/> Section: <input type='text' value='$row[SectionName]' readonly='readonly'/> Line: <input type='text' value='$row[LineName]' readonly='readonly'/><p/> _END; try{ $qry = $con->prepare("SELECT * FROM attendance WHERE EmpID = :id AND ValidDate BETWEEN DATE('2015-08-01') AND DATE('2015-08-30') GROUP BY ValidDate ORDER BY ValidDate ASC"); $qry->bindParam(':id',$row['EmpID']); $qry->execute(); } catch(PDOException $e){ echo $e->getMessage(); exit(); } echo "<table>"; while($subrow = $qry->fetch()) { echo <<<_END <tr> <td>$subrow[ValidDate]</td> <td>$subrow[TimeIn]</td> <td>$subrow[LunchOut]</td> <td>$subrow[LunchIn]</td> <td>$subrow[TimeOut]</td> </tr> _END; } echo "</table>"; } 

你需要更换

 echo "<table>"; while($subrow = $qry->fetch()) { echo <<<_END <tr> <td>$subrow[ValidDate]</td> <td>$subrow[TimeIn]</td> <td>$subrow[LunchOut]</td> <td>$subrow[LunchIn]</td> <td>$subrow[TimeOut]</td> </tr> _END; } echo "</table>"; 

像这样的东西:

 $objPHPExcel = new PHPExcel(); $row = 1; while($subrow = $qry->fetch()) { $objPHPExcel->getActiveSheet()->setCellValue('A'.$row, $subrow['ValidDate']); $objPHPExcel->getActiveSheet()->setCellValue('A'.$row, $subrow['TimeIn']); $objPHPExcel->getActiveSheet()->setCellValue('A'.$row, $subrow['LunchOut']); $objPHPExcel->getActiveSheet()->setCellValue('A'.$row, $subrow['LunchIn']); $objPHPExcel->getActiveSheet()->setCellValue('A'.$row, $subrow['TimeOut']); $row++; } $excelWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); $objWriter->save('myFileName.xlsx'); 

你可能需要玩一些date/时间转换为MS Excel序列化的时间戳,并应用格式掩码,但这是从数据库查询使用PHPExcel创buildExcel文件的基础知识

使用phpExcel创build和下载excel文件或报告

  1. 首先下载excel-report.zip并解压。
  2. 你会发现在root和另外一个文件夹index.php。
  3. 打开index.php并看看代码。
  4. 代码本身是自我描述性的,并得到很好的评价。
  5. 您可以添加列标题和logging。
  6. 您也可以在特定单元格或整行上添加颜色。
  7. 如果您想为特定的单元格或行设置粗体字体,则也可以在代码中给出。
  8. excel文件中任何一列的宽度都是可以调整的。我已经把它设置为自动调整。