Excel.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. //Excel操作类
  3. class Excel{
  4. public $excel;
  5. public $documentRoot;
  6. function __construct(){
  7. Yii::$enableIncludePath = false;
  8. $this->documentRoot = Yii::app()->basePath."/../";
  9. require_once($this->documentRoot."lib/plugins/phpexcel/PHPExcel.php");
  10. require_once($this->documentRoot."lib/plugins/phpexcel/PHPExcel/Writer/Excel2007.php");
  11. $this->excel = new PHPExcel();
  12. }
  13. public function export($rs, $fileName){
  14. $colNumber = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
  15. "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
  16. $excel = $this->excel;
  17. $writer = new PHPExcel_Writer_Excel2007($excel);
  18. $writer->setOffice2003Compatibility(true);
  19. $excel->getProperties()->setCreator("互教教育");
  20. $excel->getProperties()->setLastModifiedBy("互教教育");
  21. $excel->getProperties()->setTitle("Document");
  22. $excel->getProperties()->setSubject("Document");
  23. $excel->getProperties()->setDescription("Generated with PHP");
  24. $excel->getProperties()->setKeywords("office2007 openxml php");
  25. $excel->getProperties()->setCategory("result");
  26. $excel->setActiveSheetIndex(0);
  27. $sheet = $excel->getActiveSheet();
  28. $rowsCount = count($rs);
  29. $colsCount = count(current($rs));
  30. for($i = 0; $i < $rowsCount; $i++){
  31. for($j = 0; $j < $colsCount; $j++){
  32. if($j === 0)
  33. $val = current($rs[$i]);
  34. else
  35. $val = next($rs[$i]);
  36. $sheet->setCellValue($colNumber[$j].($i + 1), $val);
  37. }
  38. }
  39. ob_end_clean();
  40. ob_start();
  41. header("Content-Type: application/force-download");
  42. header("Content-Type: application/octet-stream");
  43. header("Content-Type: application/download");
  44. header("Content-Disposition:inline;filename={$fileName}.xlsx");
  45. header("Content-Transfer-Encoding: binary");
  46. header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
  47. header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  48. header("Pragma: no-cache");
  49. $writer->save("php://output");
  50. }
  51. public function read($file){
  52. $sheetData = array();
  53. if($file){
  54. $mValues = "";
  55. $sValues = "";
  56. // 导入PHPExcel类
  57. require_once($this->documentRoot."lib/plugins/phpexcel/PHPExcel/IOFactory.php");
  58. // 读取Excel文档
  59. $objPHPExcel = PHPExcel_IOFactory::load($file);
  60. $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
  61. // 去掉导航
  62. unset($sheetData[1]);
  63. $sheetData = Filter::act($sheetData);
  64. //krsort($sheetData);
  65. }
  66. return $sheetData;
  67. }
  68. }