从控制器

时间:2015-07-20 11:42:41

标签: symfony controller phpexcel

我会使用除控制器之外的PHPExcel软件包(用于创建服务),但我无法在这些条件下使用它。

以下是我在命令文件的'execute'函数中编写的内容:

类XportXcelPourAnalyseCommand扩展了ContainerAwareCommand ....
protected function execute(InputInterface $ input,OutputInterface $ output){ ....         $ phpExcelObject = $ this-> getContainer('phpexcel') - > createPHPExcelObject();

    $phpExcelObject->getProperties()->setCreator("liuggio")
        ->setLastModifiedBy("Giulio De Donato")
        ->setTitle("Office 2005 XLSX Test Document")
        ->setSubject("Office 2005 XLSX Test Document")
        ->setDescription("Test document for Office 2005 XLSX, generated using PHP classes.")
        ->setKeywords("office 2005 openxml php")
        ->setCategory("Test result file");
    $phpExcelObject->setActiveSheetIndex(0)
        ->setCellValue('A1', 'Hello')
        ->setCellValue('B2', 'world!');
    $phpExcelObject->getActiveSheet()->setTitle('Simple');
    // Set active sheet index to the first sheet, so Excel opens this as the first sheet
    $phpExcelObject->setActiveSheetIndex(0);

    // create the writer
    $writer = $this->get('phpexcel')->createWriter($phpExcelObject, 'Excel5');
    // create the response
    $response = $this->get('phpexcel')->createStreamedResponse($writer);
    // adding headers
    $dispositionHeader = $response->headers->makeDisposition(
        ResponseHeaderBag::DISPOSITION_ATTACHMENT,
        'stream-file.xls'
    );
    $response->headers->set('Content-Type', 'text/vnd.ms-excel; charset=utf-8');
    $response->headers->set('Pragma', 'public');
    $response->headers->set('Cache-Control', 'maxage=1');
    $response->headers->set('Content-Disposition', $dispositionHeader);

    return $response;
    $output->writeln('done');
}

1 个答案:

答案 0 :(得分:0)

当您通过以下docs创建命令时,您的命令类会继承ContainerAwareCommand类,您可以通过在命令类的$this->getContainer()函数内调用execute()来获取容器,一旦你有容器,你可以访问任何服务,比如获得excel服务,你可以得到它$this->getContainer()->get('phpexcel')

class GenerateExcelCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        //..............
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $excelObj= $this->getContainer()->get('phpexcel');
        // do your excel stuff here 
        $phpExcelObject = $excelObj->createPHPExcelObject('file.xls');
        $writer = $excelObj->createWriter($phpExcelObject, 'Excel5');
        $writer->save('file.xls');
        $output->writeln('done');
    }
}
  

通过使用ContainerAwareCommand作为命令的基类(而不是更基本的命令),您可以访问服务容器。换句话说,您可以访问任何已配置的服务

Getting Services from the Service Container