PhpSpreadsheet是一个纯PHP类库,使你能够读写Excel、LibreOffic Calc等这样的表格格式。

https://phpspreadsheet.readthedocs.io/en/develop/

列从1开始算,行从1开始算

$sheet->setCellValueByColumnAndRow(1,1,'特别说明');

安装

composer require phpoffice/phpspreadsheet 版本号

默认情况会提示找不到库,上composer找是有的,是因为还没有稳定版,所以要指定版本 1.0.0beta

依赖

The following software is required to develop using PhpSpreadsheet:

  • PHP version 5.6 or newer
  • PHP extension php_zip enabled
  • PHP extension php_xml enabled
  • PHP extension php_gd2 enabled (if not compiled in)

默认使用ZipArchive来压缩保存

注意读写权限

简单示例

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');

默认保存到执行php的根目录,以thinkphp为例index.php在D:\wwwroot\thinkphp\public,那么文件就保存在这

注:如果不想保存到文件,可以传入php://outputphp://stdout直接输出(例如html,输出网页)

通过模板来生成文件

全用代码写太累,可以用模板来修改,但是对于动态数据,还是要由代码生成

//通过工厂模式创建内容
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load('template.xlsx'); $worksheet = $spreadsheet->getActiveSheet(); $worksheet->getCell('A1')->setValue('John');
$worksheet->getCell('A2')->setValue('Smith');
//通过工厂模式来写内容
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
$writer->save('write.xls');

释放内存

为了防止内存泄露,建议用完手动清理

$spreadsheet->disconnectWorksheets();
unset($spreadsheet);

单元格

根据索引获取英文列

其中A=0

Cell::stringFromColumnIndex($pColumn)

设置值

$worksheet->getCell('A1')->setValue('John');
$sheet->setCellValue('A1', 'Hello World !');
$sheet->setCellValueByColumnAndRow($columnIndex, $rowIndex, $value);

合并单元格

    /**
* Set merge on a cell range by using numeric cell coordinates.
*
* @param int $pColumn1 Numeric column coordinate of the first cell (A = 0)
* @param int $pRow1 Numeric row coordinate of the first cell
* @param int $pColumn2 Numeric column coordinate of the last cell (A = 0)
* @param int $pRow2 Numeric row coordinate of the last cell
*
* @throws Exception
*
* @return Worksheet
*/
$sheet->mergeCellsByColumnAndRow($pColumn1, $pRow1, $pColumn2, $pRow2)

居中显示

$sheet->getStyleByColumnAndRow(0, 1, $columnIndex, $rowIndex)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER);

宽度设置

`$this->getColumnDimension($columnIndex)->setWidth($width);`
还可以让其自适应(不靠谱,建议自行设置)
`$sheet->calculateColumnWidths();`

批量设置单元格格式

这样效率更高

https://phpspreadsheet.readthedocs.io/en/develop/topics/recipes/#formatting-cells

https://phpspreadsheet.readthedocs.io/en/develop/topics/recipes/#valid-array-keys-for-style-applyfromarray

        $spreadsheet->getActiveSheet()->getStyleByColumnAndRow(1, 1, 18, count($todayRank) + 2)->applyFromArray([
'alignment' => [
'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
]
]);

直接输出下载

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告诉浏览器输出07Excel文件
//header('Content-Type:application/vnd.ms-excel');//告诉浏览器将要输出Excel03版本文件
header('Content-Disposition: attachment;filename="01simple.xlsx"');//告诉浏览器输出浏览器名称
header('Cache-Control: max-age=0');//禁止缓存
$writer = new Xlsx($spreadsheet);
$writer->save('php://output');

自动计算列宽

  //注意$fromCol,$toCol是string类型,例如A、B、C、D
function autoFitColumnWidthToContent($sheet, $fromCol, $toCol) {
if (empty($toCol) ) {//not defined the last column, set it the max one
$toCol = $sheet->getColumnDimension($sheet->getHighestColumn())->getColumnIndex();
}
for($i = $fromCol; $i <= $toCol; $i++) {
$sheet->getColumnDimension($i)->setAutoSize(true);
}
$sheet->calculateColumnWidths();
}

函数formula

https://phpspreadsheet.readthedocs.io/en/develop/references/function-list-by-name/

https://phpspreadsheet.readthedocs.io/en/develop/topics/calculation-engine/#function-reference

$worksheet->setCellValue('A12', '=DMIN(A4:E10,"Profit",A1:A2)');

$retVal = $worksheet->getCell('A12')->getCalculatedValue();
// $retVal = 225

单元格变可点击的超链

$spreadsheet->getActiveSheet()->setCellValue('E26', 'www.phpexcel.net');
$spreadsheet->getActiveSheet()->getCell('E26')->getHyperlink()->setUrl('https://www.example.com');

如果需要在表格内跳转,则

$spreadsheet->getActiveSheet()->setCellValue('E26', 'www.phpexcel.net');
$spreadsheet->getActiveSheet()->getCell('E26')->getHyperlink()->setUrl("sheet://'Sheetname'!A1");

phpspreadsheet开发手记的更多相关文章

  1. [分享]源代码&开发手记:SAE应用“车百科” (Python + SAE + Bottle + Bootstrap) - Bottle - Python4cn(news, jobs)

    [分享]源代码&开发手记:SAE应用"车百科" (Python + SAE + Bottle + Bootstrap) - Bottle - Python4cn(news, ...

  2. HoloLens开发手记 - HoloLens真机上手简评

    千呼万唤始出来,终于今天拿到了HoloLens真机. 使用体验 使用自带的应用录制了一段使用视频,如下 设备概览 包装盒 本体 试戴 实际效果 GalaxyExplorer试玩 全息图像贴到现实场景表 ...

  3. [转]Unity3D新手引导开发手记

    直接跳转吧  Unity3D新手引导开发手记 看到还不错就直接转过来了,我是有多懒啊

  4. [转]Nodejs开发框架Express4.x开发手记

    Express: ?web application framework for?Node.js? Express 是一个简洁.灵活的 node.js Web 应用开发框架, 它提供一系列强大的特性,帮 ...

  5. Doris开发手记4:倍速性能提升,向量化导入的性能调优实践

    最近居家中,对自己之前做的一些工作进行总结.正好有Doris社区的小伙伴吐槽向量化的导入性能表现并不是很理想,就借这个机会对之前开发的向量化导入的工作进行了性能调优,取得了不错的优化效果.借用本篇手记 ...

  6. 大型B2B网站开发手记 1

    本手记记录所有该B2B网站开发中遇到的问题和解决方法,一方面给大家一些思路,一方面提升自己,记录整个过程 1. 测试环境部署问题 部署环境是server2012 R2,部署上去发现WCF报错如下 sv ...

  7. APP开发手记01(app与web的困惑)

    文章链接:http://quke.org/post/app-dev-fragment.html (转载时请注明本文出处及文章链接) 最近在用博客园的wcf服务做博客园的android和ios的app, ...

  8. Doris开发手记2:用SIMD指令优化存储层的热点代码

    最近一直在进行Doris的向量化计算引擎的开发工作,在进行CPU热点排查时,发现了存储层上出现的CPU热点问题.于是尝试通过SIMD的指令优化了这部分的CPU热点代码,取得了较好的性能优化效果.借用本 ...

  9. Unity3D新手引导开发手记

    最近开始接手新手引导的开发,记录下这块相关的心得 首先客户端是Unity,在接手前,前面的同学已经初步完成了新手引导框架的搭建,这套框架比较简单,有优点也有缺点,稍后一一点评 我们的新手引导是由一个个 ...

随机推荐

  1. mongo学习-TTL索引 过期数据

    在mongo中我们可以设置文档的过期时间,超过时间,文档会自动删除.(2.x版本中  固定结合也支持,但是到了3.x中 固定集合这个索引不好用) 用法: 1.创建一个db:db.createColle ...

  2. Hadoop-2.7.2分布式安装手册

    目录 目录 1 1. 前言 3 2. 特性介绍 3 3. 部署 5 3.1. 机器列表 5 3.2. 主机名 5 3.2.1. 临时修改主机名 6 3.2.2. 永久修改主机名 6 3.3. 免密码登 ...

  3. linux每天一小步---sed命令详解

    1 命令功能 sed是一个相当强大的文件处理编辑工具,sed用来替换,删除,更新文件中的内容.sed以文本行为单位进行处理,一次处理一行内容.首先sed吧当前处理的行存储在临时的缓冲区中(称为模式空间 ...

  4. 启动hive命令时指定参数或自定义参数

    启动hive命令时指定参数或自定义参数 在hive启动命令中指定一个参数 hive --hiveconf hive.job.submit.username=fuxin.zhao -e "se ...

  5. makefile文件。批处理文件。

    makefile文件: NAME=XXX             #要编译的文件名 OBJS=$(NAME).obj              #指定输出的目标文件名 ML_FLAG=/C  /COF ...

  6. ADO.NET操作SQL Server:数据库操作类(已封装)

    1.增.删.改通用方法 /// <summary> /// 增.删.改通用方法 /// </summary> /// <param name="commandT ...

  7. iOS Png Crush 错误

    添加新的 png 图片到项目里的时候,出现错误 错误内容: while reading... pngcrush caught libpng error: cound not find file... ...

  8. 洛谷P4250 [SCOI2015]小凸想跑步(半平面交)

    题面 传送门 题解 设\(p\)点坐标为\(x_p,y_p\),那么根据叉积可以算出它与\((i,i+1)\)构成的三角形的面积 为了保证\(p\)与\((0,1)\)构成的面积最小,就相当于它比其它 ...

  9. CF1109DSasha and Interesting Fact from Graph Theory(数数)

    题面 传送门 前置芝士 Prufer codes与Generalized Cayley's Formula 题解 不行了脑子已经咕咕了连这么简单的数数题都不会了-- 首先这两个特殊点到底是啥并没有影响 ...

  10. Vulnhub Billu_b0x

    1.信息收集 1.1.获取IP地址: map scan report for 192.168.118.137 Host is up (0.00017s latency). Not shown: 998 ...