如何通过PhpSpreadsheet操作Excel文档


目录

  • 概述
  • phpspreadsheet简介
  • 从phpspreadsheet helloworld开始
  • 下载保存excel
  • 工作表
  • 单元格样式
  • 单元格保护
  • 设置单元值
  • 列宽和行高
  • 对齐
  • 边框
  • 换行
  • 超链接
  • 设置文档属性
  • 合并拆分单元格
  • 设置日期格式
  • 设置单元格背景色
  • 设置单元格批注
  • php7进阶到架构师相关阅读

概述

这是关于php进阶到架构之PHP工具包学习的系列课程:如何通过PhpSpreadsheet操作Excel文档

学习目标:

  1. 了解PhpSpreadsheet与PHPExcel的区别
  2. 掌握PhpSpreadsheet如何操作excel

phpspreadsheet简介

是一个纯PHP编写的组件库,它使用PHP7写法,代码质量和性能比PHPExcel高不少,完全可以替代PHPExcel(PHPExcel已不再维护)。

使用PhpSpreadsheet可以轻松读取和写入Excel文档,支持Excel的所有操作

安装phpspreadsheet

composer require phpoffice/phpspreadsheet

从phpspreadsheet helloworld开始

require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World !');
$writer = new Xlsx($spreadsheet);
$writer->save('hello world.xlsx');

运行上面代码即可生成hello world.xlsx的excel文件

下载保存excel

强制浏览器下载数据并保存为Excel文件

$filename = 'test.xlsx';
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
$spreadsheet = new Spreadsheet();
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');

如想要保存为.xls文件格式的话,可以改下header代码:

$filename = 'test.xls';
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
$spreadsheet = new Spreadsheet();
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
$writer->save('php://output');

工作表

//创建spreadsheet对象
$spreadsheet = new Spreadsheet();

//创建工作表
$spreadsheet->createSheet(0);
$spreadsheet->createSheet(1);

//获取工作表
$sheet = $spreadsheet->getSheet(0);
$sheet2 = $spreadsheet->getSheet(1);

//设置工作单名称
$sheet->setTitle('sheet1');
$sheet2->setTitle('sheet2');
//激活工作表
 $spreadsheet->setActiveSheetIndex(0);
 //$spreadsheet->setActiveSheetIndex(1);

单元格样式

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
//将A1至F1单元格设置为粗体字,Arial字体,10号字
$sheet->getStyle('A1:F1')->getFont()->setBold(true)->setName('Arial')->setSize(10);
$sheet->setCellValue('A1', '姓名');

 //设置单元格A2字体颜色
 $sheet->getStyle('A2')->getFont()->getColor()->setARGB("ff0000");
$sheet->setCellValue('A2', '红色');

单元格保护

//设置保护,这样该工作表的内容就不可以修改
$sheet->getProtection()->setSheet(true);
$sheet->protectCells('A3:E13', '123456');//指定区域修改时,需要输入密码123456才可以修改

设置单元值

通过字母设置单元格值

$sheet->setCellValue('A1', '姓名');
$sheet->setCellValue('C2',2);
$sheet->setCellValue('C3',7);
$sheet->setCellValue('C4',1);
$sheet->setCellValue('C5', '=SUM(C2:C5)');//求和
$sheet->setCellValue('B8', '=MIN(C2:C5)');//取最小值

通过数字下表设置单元格值

$sheet->setCellValueByColumnAndRow(1, 1, '学生成绩表');
$sheet->setCellValueByColumnAndRow(1, 2, '姓名');
$sheet->setCellValueByColumnAndRow(2, 2, '语文');
$sheet->setCellValueByColumnAndRow(3, 2, '数学');
$sheet->setCellValueByColumnAndRow(4, 2, '外语');

列宽和行高

//设置列宽
$sheet->getColumnDimension('A')->setWidth(30);
$sheet->getColumnDimension('B')->setAutoSize(true);//自动计算列宽
$sheet->getDefaultColumnDimension()->setWidth(12);//设置默认列宽
//设置行高
$sheet->getRowDimension('2')->setRowHeight(50);;//设置第2行行高
$sheet->getDefaultRowDimension()->setRowHeight(15);//设置默认行高

对齐

将A1单元格设置为水平居中对齐:

$styleArray = [
    'alignment' => [
        'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
    ],
];
$sheet->getStyle('A1')->applyFromArray($styleArray);

边框

将B2至G8的区域添加红色边框:

$styleArray = [
    'borders' => [
        'outline' => [
            'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK,
            'color' => ['argb' => 'FFFF0000'],
        ],
    ],
];
$sheet->getStyle('B2:G8')->applyFromArray($styleArray);

换行

使用\n进行单元格内换行,相当于(ALT+"Enter"):

$sheet->getCell('A5')->setValue("hello\nworld");
$sheet->getStyle('A5')->getAlignment()->setWrapText(true);

超链接

将单元格设置为超链接形式:

$sheet->setCellValue('B2', '超链接');
$sheet->getCell('B2')->getHyperlink()->setUrl('https://www.baidu.com');

设置文档属性

可以设置Excel文档属性:

$spreadsheet = new Spreadsheet();
$spreadsheet->getProperties()
    ->setCreator("Gofor")    //作者
    ->setLastModifiedBy("Jack") //最后修改者
    ->setTitle("文档测试")  //标题
    ->setSubject("副标题") //副标题
    ->setDescription("文档描述")  //描述
    ->setKeywords("keyword") //关键字
    ->setCategory("分类"); //分类

合并拆分单元格

//合并单元格
$sheet->mergeCells('A1:E1');
$sheet->mergeCells('A18:E22');

//拆分单元格
$sheet->unmergeCells('A18:E22');

设置日期格式

$sheet->setCellValue('D10', '2018-06-15');
$sheet->getStyle('D10')->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_DATE_YYYYMMDD2);

设置单元格背景色

//【注意】颜色设置没有#,不然背景色为黑色
$sheet->getStyle('A1:A5')->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('ffff00');

设置单元格批注

【注意】批注功能只有xlxs格式有效,xls格式无效。之前实现这个功能,网上查了,就是不行,后来发现文件格式xls不行,但运行不报错。【血和泪的教训的教训呀】

$sheet->getComment('A2')->getText()->createTextRun('批注:123456');
$sheet->getComment('M1')->setWidth('200pt');

php7进阶到架构师相关阅读

https://www.kancloud.cn/gofor/gofor

最后,欢迎大家留言补充,讨论~~~

原文链接:,转发请注明来源!