Wednesday, August 3, 2011

Generate an Excel file with sfPhpExcel in Symfony

  public function executeExcel(sfWebRequest $request)
  {
    // We're not going to be displaying any html, so no need to pass the data through the template
    $this->setLayout(false);

    // Initialize the Excel document
    $obj = new PHPExcel();
       
    // Set the active excel sheet
    $obj->setActiveSheetIndex(0);
    
    $obj->setActiveSheetIndex(0);
    $obj->getActiveSheet()->setCellValue('A1', 'Hello');
    $obj->getActiveSheet()->setCellValue('B2', 'world!');
    $obj->getActiveSheet()->setCellValue('C1', 'Hello');
    $obj->getActiveSheet()->setCellValue('D2', 'world!');
    
    // Output the excel data to a file
    $filePath = realpath('./excel') . DIRECTORY_SEPARATOR . 'excel.xlsx';
    $writer = PHPExcel_IOFactory::createWriter($obj, 'Excel2007');
    $writer->save($filePath);
    
    // Redirect request to the outputed file
    $this->getResponse()->setHttpHeader('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    $this->redirect('/excel/excel.xlsx');
  }

No comments:

Post a Comment