PhpSpreadsheet 设置常用格式

辛盛
2023-12-01
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
//导出处理
$objPHPExcel = new Spreadsheet();
$objPHPExcel->setActiveSheetIndex(0);
//水平居中对齐样式
$styleCenterArray = [
    'alignment' => [
        'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
        'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
    ]
];

//垂直居中对齐样式
$styleVerticalCenterArray = [
    'alignment' => [
        'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
    ]
];
$index=3;//excel第几行开始生成数据
$count = count($list);//数据的总数
$objPHPExcel->getActiveSheet()->getStyle('A1:P' . ($count + $index))->applyFromArray($styleVerticalCenterArray);
$objPHPExcel->getActiveSheet()->getStyle('A1:P' . ($count + $index))->applyFromArray($styleCenterArray);
//设置背景颜色
$objPHPExcel->getActiveSheet()->getStyle('A2:P2')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('548235');
//设置字体颜色
$objPHPExcel->getActiveSheet()->getStyle('K' . $index)
    ->getFont()->getColor()->setARGB('FF018001');//前面多两个F
$objPHPExcel->getActiveSheet()->getStyle('K' . $index)->getFont()->setBold(true);
//合并
$objPHPExcel->getActiveSheet()->mergeCells('A1:A2');
//默认高度
$objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(25);
//默认宽度
$objPHPExcel->getActiveSheet()->getDefaultColumnDimension()->setWidth(15);
//A列宽度为20
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
//B列自动计算宽度
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
//设置第3行的高度为18
$objPHPExcel->getActiveSheet()->getRowDimension('3')->setRowHeight(18);

//设置货币符号$
$objPHPExcel->getActiveSheet()->getStyle('A1')->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_CURRENCY_USD_SIMPLE);

ob_end_clean();
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $name . '.xls"');
header('Cache-Control: max-age=0');
$objWriter = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($objPHPExcel, 'Xls');
$objWriter->save('php://output');

 类似资料: