thinkphp6 XLSXWriter导出数据

文章描述:

thinkphp6使用XLSXWriter返回文件流或者另存为文件格式

 

use app\common\libs\XLSXWriter;

 

文件流

$writer = new XLSXWriter();

// 准备数据
$data = [
            ['ID', 'Name', 'Score'],
            [1, 'Alice', 95],
            [2, 'Bob', 85],
            [3, 'Charlie', 90],
];

// 添加数据到表格
$writer->writeSheet($data, 'Sheet1');

// 设置header信息
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="example.xlsx"');
header('Cache-Control: max-age=0');

// 输出文件流
$writer->writeToStdOut();
exit();

 

 

设置表头宽度样式和从数据库取数据

 $style_header['widths'] = [12,40,40,10,80,25,20,10,10,10,10,20,15,15,25,10,10];
        $style_content = ['height'=>16,'font-size'=>11,'font'=>'Calibri,宋体'];

        $writer->writeSheetHeader('商品信息',[
            '序号' => 'string',     // A
            '名称' => 'string',     // B
            '类型'=>'string',
        ], $style_header);

 

$i = 1;
foreach ($arr as $key=>$val){
      $writer->writeSheetRow('商品信息',[
                $i++, //A
                $val['name'], //B
                $val['type'],
      ],$style_content);
}

 

 

前端请求

ids是一个数组

 

let that = this

let loadingInstance = Loading.service({ fullscreen: true }); // 设置整页遮罩

let formData = new FormData();
formData.append('AdminToken', getAdminToken())
formData.append('ids', ids)

axios.post(process.env.VUE_APP_REPORT_URL+'/admin/company.Customer/export',formData, {
          responseType: 'blob' // 告诉Axios返回的数据是一个Blob对象
}).then(response => {
        if (response.status === 200) {
            console.log(response.headers['content-type'])
            if(response.headers['content-type'] == 'application/json; charset=utf-8'){
              console.log('json')
            }else if(response.headers['content-type'] == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'){
              console.log('文件流')
              const filename = that.filename || 'file.xlsx'; //文件名
              // 保存Blob对象到本地文件
              const url = window.URL.createObjectURL(response.data);
              const a = document.createElement('a');
              a.href = url;
              a.download = filename; // 下载文件的名称

              document.body.appendChild(a);

              a.click();
              window.URL.revokeObjectURL(url);

              loadingInstance.close();//关闭整页遮罩
            }else{
              console.log('其他')
            }
        }
}).catch(error => {
          loadingInstance.close();//关闭整页遮罩
          console.error('Error:', error);
})

 

输出文件

// 输出文件
$name = date("Y-m-d",strtotime("-1 day")).".xlsx";
$writer->writeToFile($name);
exit;

 

发布时间:2024/10/30

发表评论