refactor: 修改xlsx导出
This commit is contained in:
@@ -77,9 +77,10 @@ if (!function_exists('xlsx_writer')) {
|
||||
* @param array $data 数据 例:[['name'=>'张三','age'=>18, 'sex'=>'男']]
|
||||
* @param array $schema 表头信息 例:['name' => '姓名', 'age' => '年龄', 'sex' => '性别']
|
||||
* @param string $filename 下载文件名称 默认为YmdHis时间
|
||||
* @return \PhpOffice\PhpSpreadsheet\Writer\IWriter
|
||||
* @param string $output 输出方式 php://output 或 文件路径
|
||||
* @return \think\Response
|
||||
*/
|
||||
function xlsx_writer(array|\think\model\Collection $data, array $schema, string $filename = ''): \PhpOffice\PhpSpreadsheet\Writer\IWriter
|
||||
function xlsx_writer(array|\think\model\Collection $data, array $schema, string $filename = '', string $output = 'php://output'): \think\Response
|
||||
{
|
||||
// 获取Spreadsheet对象
|
||||
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
|
||||
@@ -109,10 +110,16 @@ if (!function_exists('xlsx_writer')) {
|
||||
flush();
|
||||
ob_flush();
|
||||
if ($filename == '') $filename = date('YmdHis');
|
||||
header('Access-Control-Expose-Headers: Content-Disposition');
|
||||
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; Charset=UTF-8');
|
||||
header('Content-Disposition: attachment;filename=' . $filename . '.xlsx');
|
||||
header('Cache-Control: max-age=0');
|
||||
return \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
|
||||
// 文件写入缓冲区
|
||||
\PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx')->save($output);
|
||||
// 从缓冲区获取导出文件,并通过Response返回(解决thinkphp框架的Response无法获取设置的header问题)
|
||||
$file_data = ob_get_clean();
|
||||
$response = \think\Response::create($file_data)->header([
|
||||
'Access-Control-Expose-Headers' => 'Content-Disposition',
|
||||
'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; Charset=UTF-8',
|
||||
'Content-Disposition' => 'attachment;filename=' . $filename . '.xlsx',
|
||||
'Cache-Control' => 'max-age=0'
|
||||
]);
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user