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. 用JQ去实现一个轮播效果

    前提:用JQ去实现轮播效果一步步的做一个梳理. 首先肯定是轮播的HTML和CSS样式了: <body> <div class="pic"> <div ...

  2. C++中函数模版与类模版

    1.什么是模板? (1)可以这样来解释这个问题,例如当我们需要定义多个函数,而这个函数功能其实都是一样的,例如两个数相加的函数, 只是相加的两个数的类型不相同而已,这就导致我们需要定义多个函数:当我们 ...

  3. Ubuntu下的apache2的配置过程

    参考apache2的中文文档:http://httpd.apache.org/docs/2.4/ 安装apache2: apt-get install apache2 安装apache2doc文档:a ...

  4. 企业搜索引擎开发之连接器connector(十八)

    创建并启动连接器实例之后,连接器就会基于Http协议向指定的数据接收服务器发送xmlfeed格式数据,我们可以通过配置http代理服务器抓取当前基于http协议格式的数据(或者也可以通过其他网络抓包工 ...

  5. Give $20/month and provide 480 hours of free education

    Hi , Hope all is well. Summer is right around the corner, and the Khan Academy team is excited to sp ...

  6. tomcat启动时就频繁gc和full gc

    一个小业务,流量并不大,功能也很简单,spring framework+mybatis+quartz,一启动就看到gc的频次和full gc的频次非常高: 4.202: [Full GC 4.202: ...

  7. 在TFS 2013中选择一周中的工作日,例如增加星期日

    默认情况下,TFS在迭代视图中不计算周末的工作,如果出现调休的情况,则周末的工作日不会出现在迭代视图中,也不会参与燃尽图的计算.但是可以调整团队一周中的工作日,从而修正迭代计算方式,修改的方式参考下图 ...

  8. .NET框架源码解读之准备CLR源码阅读环境

    微软发布了CLR 2.0的源码,这个源码是可以直接在freebsd和windows环境下编译及运行的,请在微软shared source cli(http://www.microsoft.com/en ...

  9. Maven新建项目产生Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resource

    需要 打开并修改conf/settings.xml,添加如下内容: <!-- 设置本地仓库位置--> <localRepository>F:\maven\repository& ...

  10. FIM控制同步用户

     C:\Program Files\Microsoft Office Servers\15.0\Synchronization Service\UIShell 这个路径下,你如果懂FIM,可以进去看看 ...