目录
一:背景
二:excel表头数据实现
三:excel渲染数据实现:
四:最终效果如下:
一:背景
最近需要统计一些数据,导出到excel,主要是一些区域的人员销售统计数据,涉及到复杂的表头和数据合并,我们使用PhpSpreadsheet这个excel操作库很容易就实现了,记录一下实现过程。
二:excel表头数据实现
表头有两行数据,前几列是两行合并,后几列是按照两行显示具体如下:
首先我们把表头展示实现:
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet;
$sheet = $spreadsheet->getActiveSheet();
$header = [
['大区','省','销售员','一月','','二月','','三月',''],
['','','','推广数量','销售额','推广数量','销售额','推广数量','销售额',])
];
$row = 1;
foreach ($header as $value) {
$col = 1;
foreach ($value as $v) {
$sheet->setCellValueByColumnAndRow($col, $row, $v);
$col += 1;
}
$row += 1;
}
合并单元格:
$cellValue = $sheet->getCell('A2')->getValue();
$sheet->mergeCells('A2:A3');
$sheet->setCellValue('A2', $cellValue);
$cellValue = $sheet->getCell('B2')->getValue();
$sheet->mergeCells('B2:B3');
$sheet->setCellValue('B2', $cellValue);
$cellValue = $sheet->getCell('C2')->getValue();
$sheet->mergeCells('C2:C3');
$sheet->setCellValue('C2', $cellValue);
$sheet->mergeCells('E2:F2');
$sheet->setCellValue('E2', '一月');
$sheet->mergeCells('G2:H2');
$sheet->setCellValue('G2', '二月');
$sheet->mergeCells('I2:J2');
$sheet->setCellValue('I2', '三月');
设置样式:
$styleArray = [
'borders' => [
'outline' => [
'borderStyle' => Border::BORDER_THICK, // 边框样式
'color' => ['argb' => 'red'], // 边框颜色
],
'bottom' => [
'borderStyle' => Border::BORDER_THIN, // 下边界线:细线
'color' => ['argb' => 'red'], // 边框颜色
],
],
'alignment' => [
'horizontal' => Alignment::HORIZONTAL_CENTER,
'vertical' => Alignment::VERTICAL_CENTER,
],
'fill' => [
'fillType' => Fill::FILL_SOLID,
'startColor' => [
'rgb' => 'ff9900'
]
],
'font' => [
'bold' => true,
'color' => [
'rgb' => '000000'
]
],
];
$sheet->getStyle('A2:AB2')->applyFromArray($styleArray);
三:excel渲染数据实现:
实现逻辑是,获取每个省的销售员数据,去循环渲染,如果是同一个省,省列的单元格合并,如果是同一个区,大区列的单元格合并
//根据销售员销售数据
$row = $areaStart = $provinceStart = 4;
$col = 3;
$monthCol = [7,9,11,13,15,17,19,21,23,25,27,29];//12个月的销售起始列
foreach ($areaDeptArr as $areaName => $areaValue) {
foreach ($areaValue as $provinceName => $value) {
foreach ($value as $v) {
$sheet->setCellValueByColumnAndRow($col, $row, $v['user_name']);
//填充销售数据
foreach ($monthCol as $m => $mValue) {
$lastCol = $mValue + 1;
$sheet->setCellValueByColumnAndRow($mValue, $row, 0);
$sheet->setCellValueByColumnAndRow($lastCol, $row, 0);
}
$row+= 1;
}
//设置省区名称
$sheet->mergeCells('B'.$provinceStart.':B'.($row-1));
$sheet->setCellValue('B'.$provinceStart, $provinceName);
$provinceStart = $row;
}
//设置大区名称
$sheet->mergeCells('A'.$areaStart.':A'.($row-1));
$sheet->setCellValue('A'.$areaStart, $areaName);
$areaStart = $row;
}
$excelName = '业务员销售数据.xlsx';
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
$writer->save($excelName);