【发布时间】:2019-07-30 14:11:53
【问题描述】:
我有一个简单的代码如下 (docs):
// Set the headers to a downloadble content
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="nomfichier.xlsx"');
// Initialize spreadsheet
$objPHPExcel = new PhpOffice\PhpSpreadsheet\Spreadsheet();
$objPHPExcel->setActiveSheetIndex(0);
// Get the sheet and set the value of the first cell
$objPHPExcel->getActiveSheet()->setCellValue('A1', 'ID');
// Create the .xlsx file and download it
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($objPHPExcel, 'Xlsx');
$writer->save('/tmp/temp.csv');
知道这段代码在我的 PHP 页面中间,下载的内容是 HTML 页面的整个文本,试图在第一列中放入我的 excel 文件,而不是我正在寻找的简单结果:值在第一个单元格和第一列中命名为 ID。
我错过了什么?这段代码是否需要包含在它自己的文件中?
【问题讨论】:
-
你能澄清你的问题吗?
-
@Justinas 定义
clarify?你不明白什么? :-) -
它不需要包含在它自己的文件中。如果需要,您可以将其移动到文件的顶部。 (不要忘记在这段代码之后有一个
exit;)。其原因是 Web 服务器(和客户端)不知道您的预期响应应该是什么,因此它无法为您“删除”已经输出的 HTML。此外,任何header()-call must 都必须在 any 输出之前。标头始终在任何内容之前发送,因此如果您输出任何内容,则无法为该响应设置额外的标头。 -
@MagnusEriksson 将代码放在文件顶部并在保存后立即退出下载一个空的 excel 文件 - 但不是我指定的单元格值。知道为什么吗?
-
那是因为您没有将文件发送给客户端。您只是将它保存在服务器上的
temp.csv文件夹中的tmp中。如果您想输出它,请使用$writer->save('php://output');
标签: php spreadsheet phpspreadsheet