最新版本的phpoffice组件最低版本要求PHP8.0,所以需要安装旧版本的,这里测试挑选了一个1.23的版本可以使用,在项目根目录composer运行安装组件:
composer require phpoffice/phpspreadsheet:1.23
应用案例:首先定义一个导出表格的函数
#[NoReturn]
function exportExcel($expTitle, $expCellName, $expTableData, $setWidth = []): void
{
$spreadsheet = new Spreadsheet();
$spreadsheet->getActiveSheet()->setTitle($expTitle . date('Ymd'));
$cellNum = count($expCellName);
$len = count($expTableData);
// 设置表头字段
foreach ($expCellName as $k => $v) {
$spreadsheet->getActiveSheet()->setCellValueByColumnAndRow($k + 1, 1, $v);
}
// 添加数据
foreach ($expTableData as $k => $v) {
for ($i = 0; $i < $cellNum; $i++) {
$spreadsheet->getActiveSheet()->setCellValueByColumnAndRow($i + 1, $k + 2, $expTableData[$k][$expCellName[$i]]);
}
}
// // 添加所有边框/居中
// $styleArrayBody = [
// 'borders' => [
// 'allBorders' => [
// 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
// 'color' => ['argb' => '333333'],
// ],
// ],
// 'alignment' => [
// 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
// ],
// ];
// $total_rows = $len + 1; // 表格总行数要加上表头一栏
// $spreadsheet->getActiveSheet()->getStyle('A1:' . end($setWidth) . $total_rows)->applyFromArray($styleArrayBody);
// // 设置列宽
// if ($setWidth) {
// foreach ($setWidth as $k => $v) {
// $spreadsheet->getActiveSheet()->getColumnDimension($v)->setAutoSize(true); // 列宽自定义
// }
// } else {
// $spreadsheet->getActiveSheet()->getDefaultColumnDimension()->setWidth(14);
// }
$filename = $expTitle . date('Ymd') . '.xlsx';
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $filename . '"');
header('Cache-Control: max-age=0');
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
die();
}
其次处理数据
// 导出数据
$list = Db::table('user')->select();
$columns = [
'id' => 'ID',
'username' => '用户名',
'age' => '年龄',
'gender' => '性别',
];
$columns_fields = array_keys($columns);
// 导出数据到csv文件
$xlsData = [];
// 导出数据到excel文件
foreach ($list as $key => $value) {
foreach ($columns_fields as $k => $v) {
if (isset($value[$v])) {
$xlsData[$key][$columns[$v]] = $value[$v];
}
}
}
// 编辑表格的title,返回的数据格式是:$xlsCell = ['id', 'username', 'age']
$length = count($xlsData);
$xlsCell = [];
foreach ($xlsData[$length - 1] as $k => $v) {
$xlsCell[] = $k;
}
// 你的表格一共有多少字段信息需要导出,设置对应的excel坐标,动态判断,从A到Z
$cellNum = count($xlsCell);
$setWidth = [];
for ($i = 0; $i < $cellNum; $i++) {
$setWidth[] = chr(ord('A') + $i);
}
// 调用自定义方法
exportExcel('用户表', $xlsCell, $xlsData, $setWidth);
评论 (0)