实例化对象
composer 导包 "phpoffice/phpspreadsheet": "^1.11",
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
- 合并单元格
$sheet->mergeCells('A1:J1');
- 设置单元格的内容
$spreadsheet->getActiveSheet()
->setCellValue('A2', '序号')
->setCellValue('D2', '联系人')
->setCellValue('G2', '手机');
- 单元格水平和垂直都居中
$styleArray = [
'alignment' => [
'horizontal' => Alignment::HORIZONTAL_CENTER,
'vertical'=>Alignment::VERTICAL_CENTER
],
];
$sheet->getStyle('A1')->applyFromArray($styleArray);
- 单元格垂直居中水平左对齐
$styleArray2 = [
'alignment' => [
'horizontal' => Alignment::HORIZONTAL_LEFT,
'vertical'=>Alignment::VERTICAL_CENTER
],
];
$sheet->getStyle('A2')->applyFromArray($styleArray2);
- 将单元格字体设置粗体,字体大小20
$spreadsheet->getActiveSheet()
->getStyle('A1')
->getFont()
->setBold(true)
->setSize(20);
- 设置第一行的行高为30
$spreadsheet->getActiveSheet()->getRowDimension('1')->setRowHeight(30);
- 选择单元格设置自动换行,并且设置水平和垂直居中
$sheet->getStyle('A4:J8')
->getAlignment()->setWrapText(true) // 自动换行
->setVertical(Alignment::VERTICAL_CENTER)
->setHorizontal(Alignment::HORIZONTAL_CENTER);
- 单元格所有边框
$styleArray = [
'borders' => [
'allBorders' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
'color' => ['argb' => '000000'],
],
],
];
$sheet->getStyle('A3:J8')->applyFromArray($styleArray);
- 设置列宽
$sheet->getColumnDimension("B")->setWidth(20);