如何使用 PHPExcel Cakephp 2.0 将数据导出到 excel 文件

How to export data to an excel file using PHPExcel Cakephp 2.0

我尝试使用 PHPExcel 库和 Cakephp 2.5 将数据导出到 Excel 文件。 我的代码:

<?php

App::import('Vendor', 'PHPExcel', array('file' => 'PHPExcel'.DS.'PHPExcel.php'));
App::import('Vendor', 'PHPExcel_IOFactory', array('file' => 'PHPExcel'.DS.'PHPExcel'.DS.'IOFactory.php'));
App::import('Vendor', 'PHPExcel_IOFactory', array('file' => 'PHPExcel'.DS.'PHPExcel'.DS.'Style.php'));

class LeadUploadController extends AppController {

    public function exel_download($emp_id='')
    {
        $this->autoRender = false;
        $this-> layout='ajax';

        $objPHPExcel = new PHPExcel();
        $serialnumber=0;
        $tmparray =array("Sr.Number","Employee ID","Employee Name");
        $sheet =array($tmparray);
        $tmparray =array();
        $serialnumber = $serialnumber + 1;
        array_push($tmparray,$serialnumber);
        $employeelogin = 'aa';
        array_push($tmparray,$employeelogin);
        $employeename = 'bb';
        array_push($tmparray,$employeename);   
        array_push($sheet,$tmparray);
        header('Content-type: application/vnd.ms-excel');
        header('Content-Disposition: attachment; filename="file.xlsx"');
        $worksheet = $objPHPExcel->getActiveSheet();
        foreach($sheet as $row => $columns) {
        foreach($columns as $column => $data) {
        $worksheet->setCellValueByColumnAndRow($column, $row + 1, $data);
        }
        }
        $objPHPExcel->getActiveSheet()->getStyle("A1:I1")->getFont()->setBold(true);
        $objPHPExcel->setActiveSheetIndex(0);
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save(str_replace('.php', '.xlsx', __FILE__));
    }
}

问题是下载的 Excel 文件不包含任何数据,它完全空白并出现错误 "can not open the file because of file format or extension not valid "。不知道这些代码有什么问题。

以下代码应该适用于 xls 扩展。

    $objPHPExcel = new PHPExcel();
    $serialnumber=0;
    $tmparray =array("Sr.Number","Employee ID","Employee Name");
    $sheet =array($tmparray);
    $tmparray =array();
    $serialnumber = $serialnumber + 1;
    array_push($tmparray,$serialnumber);
    $employeelogin = 'aa';
    array_push($tmparray,$employeelogin);
    $employeename = 'bb';
    array_push($tmparray,$employeename);   
    array_push($sheet,$tmparray);
    header('Content-type: application/vnd.ms-excel');
    header('Content-Disposition: attachment; filename="file.xls"');
    $worksheet = $objPHPExcel->getActiveSheet();
    foreach($sheet as $row => $columns) {
        foreach($columns as $column => $data) {
            $worksheet->setCellValueByColumnAndRow($column, $row + 1, $data);
        }
    }
    $objPHPExcel->getActiveSheet()->getStyle("A1:I1")->getFont()->setBold(true);
    $objPHPExcel->setActiveSheetIndex(0);
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output');