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. UITableView.separatorInset

    [UITableView.separatorInset] separatorInset指定每行row之间的分隔线的长度,iOS7.0后提供,官方文档如下: 示例截图如下,分隔线没有紧贴着左右边界:

  2. centos中如何查看tomcat的版本

    centos中如何查看tomcat的版本 如果使用的rpm安装的tomcat,则使用如下命令查看 rpm -q tomcat 如果不是使用rpm安装的tomcat ./catalina.sh vers ...

  3. 【转】C中的静态存储区和动态存储区

    一.内存基本构成    可编程内存在基本上分为这样的几大部分:静态存储区.堆区和栈区.他们的功能不同,对他们使用方式也就不同.    静态存储区:内存在程序编译的时候就已经分配好,这块内存在程序的整个 ...

  4. centos6.6 下安装mysql5.7

    背景 没啥好说的,就是需要搭建自己的测试数据库跟研发的数据隔离开来,需要怼mysql 这个方法只适合mysql5.7 # mysql5.6的有差异 步骤 1. 确认线上mysql的版本 SELECT ...

  5. Jenkins+.Net Core+Git集成发布 - SkyMallCore快速开发平台

    准备工作:安装 Jenkins+java 直接百度安装,在此忽略 dotnet sdk(iis部署已经安装) 一:windows 部署到IIS 首先搭建IIS,站点应用程序池选择 ‘无托管代码’ 安装 ...

  6. Mycat SqlServer 技术栈 实现 主从分离

    先说明下版本:SqlServer2008R2 + MyCat 1.6 现在主从分离 一主一从 用的是 代码 写死的方式  转换下思路 一主两从 或者多从 怎么实现 负载均衡 或者 按权重调用相应库呢 ...

  7. winform textbox控件keydown、keypress、keyup简单介绍

    1.执行先后顺序: keydown-->keypress-->keyup 2.按键相关操作: 1)keydown和keyup参数类型KeyEventArgs(提供了KeyCode)实现形式 ...

  8. docker pull manifest unknown blob errors

    问题:docker pull manifest unknown blob errors 原因:公司网络是代理模式,所以我的 docker 服务配置成proxy模式: [root@localhost ~ ...

  9. python中的函数(基础)

    1.什么是函数 函数是指将一组数据的集合通过一个名字(函数名)封装起来,要想执行这个函数,只需调用函数名即可 (函数就是对功能或者动作的封装) 2.函数的语法和定义 def 函数名() 函数体 调用: ...

  10. 学习xss模拟构造攻击(第一篇)

    本文作者:i春秋签约作家——rosectow 0×00前言 XSS又名叫CSS全程(cross site scriptting),中文名跨站脚本攻击,目前网站的常见漏洞之一,它的危害没有像上传漏洞,s ...