// 数据总列数
$allColumns = count($formsTable);
// 数据总行数
$allRows = $model->where(['status' => 1, 'ac_id' => $ac_id])->count();
// 实例化
$spreadsheet = new Spreadsheet();
// 获取活动单元格
$sheet = $spreadsheet->getActiveSheet();
//设置单元格内容
foreach ($formsTable as $key => $value) {
// 单元格内容写入
$sheet->setCellValueByColumnAndRow($key + 1, 1, $value['title']);
}
// 如有数据,添加数据
$row = 2; //从第二行开始
for ($i = 0; $i < $allRows; $i++) {
for ($j = 1; $j <= $allColumns; $j++) {
$sheet->setCellValueByColumnAndRow($j, $row, $formsTable[$j - 1]['value']);
}
$row++;
}
$getHighestRowAndColumn = $sheet->getHighestRowAndColumn();
$HighestRow = $getHighestRowAndColumn['row']; //最大行数
$column = $getHighestRowAndColumn['column']; //最大列数
// 填充背景颜色 -- 第一行
$titleScope = 'A1:' . $column . '1'; //第一(标题)范围(例:A1:D1)
$sheet->getStyle($titleScope)
->getFill()
->setFillType(Fill::FILL_SOLID) // 设置填充样式
->getStartColor()
->setARGB('00B0F0');
// 设置文字颜色为白色
$sheet->getStyle($titleScope)->getFont()->getColor()
->setARGB('FFFFFF');
$spreadsheet->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
// 添加表格/边框线
$allCope = 'A1:' . $column . $HighestRow;//整个表格范围(例:A1:D5)
$sheet->getStyle($allCope)->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN);
$acTitle = Activity::where('id', $ac_id)->value('title');
// 下载文件名称
$file_name = $acTitle . '_集体报名模板.xlsx';
// 实例化导出类
header('Content-Type:application/vnd.ms-excel');
header('Content-Disposition:attachment;filename=' . $file_name);
header('Cache-Control:max-age=0');
// 输出文件
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');