buildadmin中header导出功能

 



    
     {{ t('treetable.export') }}

 绑定点击事件

/**
 * 导出点击方法
 */
const derive = () => {
    createAxios(
        {
            url: '/admin/Treetable/export',
            method: 'get',
            responseType: 'blob',
        },
        { reductDataFormat: false }
    ).then((response) => {
        const disposition = response.headers['content-disposition']
        const arr = disposition.split('filename=')
        const fileName = decodeURI(arr[1])
        fileDownload(response.data, fileName)
    })
}
参数说明:
xhr.response的数据类型
responseType值 xhr.response 数据类型 说明
"" String字符串 默认值(在不设置responseType时)
"text" String字符串
"document" Document对象 希望返回 XML 格式数据时使用
"json" javascript对象 存在兼容性问题,IE10/IE11不支持
"blob" Blob对象
"arrayBuffer" ArrayBuffer对象

 编写控制器中导出方法

/**
     * 导出
     * @return void
     * @throws Throwable
     */
    public function export(): void
    {
        $list = $this->model->select()->toArray();

        $spreadsheet = new Spreadsheet();
        $sheet       = $spreadsheet->getActiveSheet();
        $sheet->setCellValue([1, 1], '名称');
        $sheet->setCellValue([2, 1], 'ID');
        $sheet->setCellValue([3, 1], '创建时间');

        $h = 2;
        foreach ($list as $v) {
            $sheet->setCellValue([1, $h], $v['name']);
            $sheet->setCellValue([2, $h], $v['id']);
            $sheet->setCellValue([3, $h], date('Y-m-d H:i:s', $v['create_time']));
            $h++;
        }

        $writer = new Xlsx($spreadsheet);
        $file   = time() . '.xlsx';
        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Access-Control-Expose-Headers:Content-Disposition');
        header('Content-Disposition: attachment;filename=' . $file);
        header('Cache-Control: max-age=0');
        $writer->save('php://output');
        $spreadsheet->disconnectWorksheets();
    }

你可能感兴趣的:(php)