如何在Symfony中返回将输出excel文件的响应?我收到一个错误,我必须返回一个响应,它需要在字符串中正确吗?救命啊!
$excel = new PHPExcel();
$excel->setActiveSheetIndex(0);
$excel->getActiveSheet()
->setCellValue('A1', 'hi');
$objWriter = \PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
return $objWriter;
错误:
The controller must return a response (Object(PHPExcel_Writer_Excel2007) given).
答案 0 :(得分:9)
Controller必须返回Response
类的实例,请执行以下操作:
ob_start();
$objWriter->save('php://output');
return new Response(
ob_get_clean(), // read from output buffer
200,
array(
'Content-Type' => 'application/vnd.ms-excel',
'Content-Disposition' => 'attachment; filename="doc.xls"',
)
);
如果您使用Excel 2007或上限内容类型为"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
,文件扩展名为xlsx
。
答案 1 :(得分:0)
在我的情况下,我有一个路由和一个控制器来导出生成的XLS(在我的情况下,一个按钮访问路由并返回XLS文件)
另外,我读了一个已经生成并存储的文件,但是即使你没有存储文件它也应该工作,你应该只使用这行中的$objWriter;
$response = $this->get('phpexcel')->createStreamedResponse($writer);
另外,我没有使用VisioN表示我应该使用的Response对象。
行动:
public function exportAction() {
$readerObject = PHPExcel_IOFactory::createReader('Excel5');
$phpExcelObject = $readerObject->load('files/downloads/reports/' . $this->getUser()->getName() . '.xls');
$writer = $this->get('phpexcel')->createWriter($phpExcelObject, 'Excel5');
$response = $this->get('phpexcel')->createStreamedResponse($writer);
$response->headers->set('Content-Type', 'text/vnd.ms-excel; charset=utf-8');
$response->headers->set('Content-Disposition', 'attachment;filename=' . $this->getUser()->getName() . '.xls');
$response->headers->set('Pragma', 'public');
$response->headers->set('Cache-Control', 'maxage=1');
return $response;
}
请注意,'Excel5'
适用于XLS文件,如果您需要XLSX文件,则应替换'Excel2007'
答案 2 :(得分:-1)
使用请求symfony组件的另一个例子:
use Symfony\Component\HttpFoundation\Request;
/**
* Create a zip file with excel contain the list of clubs.
*
* @param Request $request
* @param $the_response_excel_file
* @param $the_file_name
*/
public function exportAction(Request $request, $the_response_excel_file, $the_file_name)
{
// adding headers
$dispositionHeader = $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
$filename
);
$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;
}