/**
* Excel 助手
* sudo composer require phpoffice/phpspreadsheet
*/
namespace CommonUtil;
use PhpOfficePhpSpreadsheetSpreadsheet;
use PhpOfficePhpSpreadsheetWriterXlsx;
use PhpOfficePhpSpreadsheetStyleAlignment;
use PhpOfficePhpSpreadsheetStyleColor;
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’);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。