<?php
/**
* Excel 助手
* sudo composer require phpoffice/phpspreadsheet
*/
namespace Common\Util;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Color;
class ExcelUtil extends CommonUtil
{
public function __construct()
{
parent::__construct();
}
/**
* 导出数据
*/
public function exportExcel($expTitle, $expCellName, $expTableData)
{
$fileName = $expTitle;
$spreadsheet = new Spreadsheet();
// 获取活动的工作空间
$worksheet = $spreadsheet->getActiveSheet();
$cellNum = count($expCellName);
$dataNum = count($expTableData);
$cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
// 合并单元格
$worksheet->mergeCells('A1:'.$cellName[$cellNum - 1] . '1');
// 设置第一格的内容
$worksheet->setCellValue('A1', $expTitle);
// 设置加粗
$worksheet->getStyle('A1')->getFont()->setBold(true);
// 设置居中
$styleArray = [
'alignment' => [
'horizontal' => Alignment::HORIZONTAL_CENTER,
],
];
$worksheet->getStyle('A1')->applyFromArray($styleArray);
// 设置颜色
$worksheet->getStyle('A1')->getFont()->getColor()->setARGB(Color::COLOR_DARKRED);
// 设置标题
$worksheet->setTitle($expTitle);
// 设置表格菜单
for ($i = 0; $i < $cellNum; $i++) {
$worksheet->setCellValue($cellName[$i] . (+2), $expCellName[$i][1]);
$worksheet->getStyle($cellName[$i] . (+2))->getFont()->setBold(true);
// 自动宽度
$worksheet->getColumnDimension($cellName[$i])->setAutoSize(true);
}
// 设置表格内容
for ($i = 0; $i < $dataNum; $i++) {
for ($j = 0; $j < $cellNum; $j++) {
$worksheet->setCellValue($cellName[$j] . ($i + 3), $expTableData[$i][$expCellName[$j][0]]);
// 支持换行
if ($expCellName[$j][2] == 1) {
$worksheet->getStyle($cellName[$j] . ($i + 3))->getAlignment()->setWrapText(true);
}
}
}
// 设置列宽为自动
// $spreadsheet->getActiveSheet()->getDefaultColumnDimension()->setWidth(20);
// $worksheet->getDefaultColumnDimension()->setAutoSize(true);
// 设置行高
$worksheet->getDefaultRowDimension()->setRowHeight(20);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告诉浏览器输出07Excel文件
//header('Content-Type:application/vnd.ms-excel');//告诉浏览器将要输出Excel03版本文件
header('Content-Disposition: attachment;filename="'.$fileName.'.xlsx"');//告诉浏览器输出浏览器名称
header('Cache-Control: max-age=0');//禁止缓存
$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
}
}