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. spark standalone集群部署 实践记录

    本文记录了一次搭建spark-standalone模式集群的过程,我准备了3个虚拟机服务器,三个centos系统的虚拟机. 环境准备: -每台上安装java1.8 -以及scala2.11.x (x代 ...

  2. 编译驱动的Makefile解析

    一个典型的编译驱动模块的Makefile文件如下所示: KERN_DIR = /root/driver/kernel obj-m += module_test.o all: make -C $(KER ...

  3. swoole1.8.0+版本异步redis安装(本实例为swoole1.8.10版本)详解

    Swoole-1.8.0+版本增加了对异步Redis客户端的支持,基于redis官方提供的hiredis库实现.Swoole提供了__call魔术方法,来映射绝大部分Redis指令(本次安装实例为sw ...

  4. medusa爆破路由

    medusa –M http -h 192.168.10.1 -u admin -P /usr/share/wfuzz/ wordlist/fuzzdb/wordlists-user-passwd/p ...

  5. 布局分析002:入门级的CSS导航弹出菜单

    这种弹出菜单非常有意思,也有记录的意义,甚至可以说,掌握了这种弹出菜单,基本上CSS掌握的差不多. 主要涉及下面三个重要知识: CSS的继承性质. relative absolute定位. 子选择符& ...

  6. [Erlang30]Erlang shell是如何工作的?

    一些关于Erlang启动进程的分析:希望你会喜欢. 原英文地址:http://ferd.ca/repl-a-bit-more-and-less-than-that.html 研究Erlang shel ...

  7. WPF解决方案------调用线程无法访问此对象,因为另一个线程拥有该对象

    WPF [调用线程无法访问此对象,因为另一个线程拥有该对象.] 解决方案 在这里以播放图片为例进行说明,代码如下: void _Timer_Elapsed(object sender, Elapsed ...

  8. Enabling Remote Errors in SSRS

    January 18, 2011 By default the remote errors property in SQL Server Reporting Services is set to fa ...

  9. DS作业01--日期抽象数据类型设计与实现

    第六次作业 1.思维导图及学习体会 1.1 思维导图 1.2 学习体会 因为假期里面代码的练习量很小,所以开学来上学期的知识遗忘了很多,刚刚开始写大作业的时候很困难,完全没有思路,后来看了几位同学的代 ...

  10. 问题 E: YK的书架

    点击打开链接 问题 E: YK的书架 时间限制: 1 秒  内存限制: 128 MB 提交: 596  解决: 138 提交 状态 题目描述     YK新买了2n+1本相同的书,准备放在家里的3层书 ...