PhpSpreadsheet读写Excel文件
本文介绍PhpSpreadsheet读写excel文件的一些使用方法。
目录
- 简介
- 写入excel文件
- 工作表默认样式
- 单元格样式
- 单元格数据类型
- 冻结单元格
- 单元格条件格式
- 写入图片
- 设置超链接
- 读取excel文件
- 读取文本数据
- 读取图片
- 读取超链接
- 下载文件
简介
PhpSpreadsheet要求PHP 7.3及以上版本,是PHPExcel库的扩展版本,可用来读写xls、xlsx、CSV、HTML等格式文件。
Format | Reading | Writing |
---|---|---|
Open Document Format/OASIS (.ods) | ✓ | ✓ |
Office Open XML (.xlsx) Excel 2007 and above | ✓ | ✓ |
BIFF 8 (.xls) Excel 97 and above | ✓ | ✓ |
BIFF 5 (.xls) Excel 95 | ✓ | |
SpreadsheetML (.xml) Excel 2003 | ✓ | |
Gnumeric | ✓ | |
HTML | ✓ | ✓ |
SYLK | ✓ | |
CSV | ✓ | ✓ |
PDF (using either the TCPDF, Dompdf or mPDF libraries, which need to be installed separately) | ✓ |
PhpSpreadsheet安装方法可参考禅道二次开发(四):集成PhpSpreadsheet解析Excel文件
下面来介绍PhpSpreadsheet读写excel格式文件方法。
写入excel文件
以写入Xlsx格式文件为例,
<?phprequire 'vendor/autoload.php';use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;/* 写入excel */
$fileName = './test.xlsx';
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World !');
$sheet->setCellValue('C3', '你好 !');$writer = new Xlsx($spreadsheet);
$writer->save($fileName);
?>
工作表默认样式
可以设置工作表默认样式,比如:
$spreadsheet->getDefaultStyle()->getFont()->setName('宋体'); // 字体
$spreadsheet->getDefaultStyle()->getFont()->setSize(8); // 字体大小
$spreadsheet->getDefaultStyle()->getAlignment()->setWrapText(true); // 自动换行
$spreadsheet->getDefaultStyle()->getAlignment()->setVertical(Alignment::VERTICAL_CENTER); //垂直居中
单元格样式
use PhpOffice\PhpSpreadsheet\Style\Alignment;$spreadsheet->getActiveSheet()->getStyle('A1:D4')->getAlignment()->setWrapText(true); // 自动换行
$caseSpreadsheet->getActiveSheet()->getStyle('A1:D4')->getAlignment()->setVertical(Alignment::VERTICAL_CENTER); //垂直居中
单元格对齐方式包括水平对齐和垂直对齐:
// 水平对齐样式
HORIZONTAL_GENERA
HORIZONTAL_LEFT
HORIZONTAL_RIGHT
HORIZONTAL_CENTER
HORIZONTAL_CENTER_CONTINUOUS
HORIZONTAL_JUSTIFY
HORIZONTAL_FILL
HORIZONTAL_DISTRIBUTED // Excel2007 only// 垂直对齐样式
VERTICAL_BOTTOM
VERTICAL_TOP
VERTICAL_CENTER
VERTICAL_JUSTIFY
VERTICAL_DISTRIBUTED // Excel2007 only
除了设置单元格的字体,还可以设置边框,填充颜色等样式信息。
比如设置单元格背景颜色:
$spreadsheet->getActiveSheet()->getStyle('E2')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FFFF0000');// 多个单元格,如果设置多个单元格推荐此方法,性能更优。
$spreadsheet->getActiveSheet()->getStyle('B3:B7')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FFFF0000');
注意:颜色代码为ARGB,带了Alpha通道。
设置单元格高度,某一行高度:
$spreadsheet->getActiveSheet()->getRowDimension('10')->setRowHeight(100);
$spreadsheet->getActiveSheet()->getDefaultRowDimension()->setRowHeight(15); // 默认行高
设置某列:
// 设置列宽
$spreadsheet->getActiveSheet()->getColumnDimension('A') ->setWidth(30);// 自动列宽
$spreadsheet->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);// 默认列宽
$spreadsheet->getActiveSheet()->getDefaultColumnDimension() ->setWidth(12);
单元格数据类型
use PhpOffice\PhpSpreadsheet\Cell\DataType;
$spreadsheet->getActiveSheet()->setCellValueExplicit("A1", "123", DataType::TYPE_STRING);/*
TYPE_STRING2
TYPE_STRING
TYPE_FORMULA
TYPE_NUMERIC
TYPE_BOO
TYPE_NULL
TYPE_INLINE
TYPE_ERROR
*/
数字添加引号前缀:
$spreadsheet->getActiveSheet()->setCellValueExplicit("A1", "123", DataType::TYPE_STRING);
$spreadsheet->getActiveSheet()->getStyle("A1")->setQuotePrefix(true);
// $spreadsheet->getActiveSheet()->getStyle("A1")->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
设置数据有效性:
use PhpOffice\PhpSpreadsheet\Cell\DataValidation;$objValidation = $spreadsheet->getActiveSheet()->getCell('C1')->getDataValidation(); // 设置数据有效性的单元格
$objValidation -> setType(DataValidation::TYPE_LIST)-> setErrorStyle(DataValidation::STYLE_INFORMATION)-> setAllowBlank(false)-> setShowInputMessage(true)-> setShowErrorMessage(true)-> setShowDropDown(true)-> setErrorTitle('错误提示')-> setError('您输入的值有误')-> setPromptTitle('结果')-> setFormula1('"成功,失败"');
冻结单元格
$sheet = $spreadsheet->getActiveSheet();
$sheet->freezePane('A2'); // 冻结第一行
$sheet->freezePane('B1'); // 冻结第一列
$sheet->freezePane('B3'); // 冻结B3单元格
单元格条件格式
可以设置单元格的条件格式,可以对满足某个条件的单元格设置样式,比如设置大于80的单元格:
$conditional = new \PhpOffice\PhpSpreadsheet\Style\Conditional();
$conditional->setConditionType(\PhpOffice\PhpSpreadsheet\Style\Conditional::CONDITION_CELLIS);
$conditional->setOperatorType(\PhpOffice\PhpSpreadsheet\Style\Conditional::OPERATOR_GREATERTHAN);
$conditional->addCondition(80);
$conditional->getStyle()->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_DARKGREEN);
$conditional->getStyle()->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID);
$conditional->getStyle()->getFill()->getStartColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_GREEN);$conditionalStyles = $spreadsheet->getActiveSheet()->getStyle('A1:A10')->getConditionalStyles();
$conditionalStyles[] = $conditional;$spreadsheet->getActiveSheet()->getStyle('A1:A10')->setConditionalStyles($conditionalStyles);
可以使用的条件及操作符:
// Condition types
CONDITION_NONE
CONDITION_CELLIS
CONDITION_CONTAINSTEXT
CONDITION_EXPRESSION
CONDITION_CONTAINSBLANKS
CONDITION_NOTCONTAINSBLANKS
CONDITION_DATABAR
CONDITION_NOTCONTAINSTEXT// Operator types
OPERATOR_NONE
OPERATOR_BEGINSWITH
OPERATOR_ENDSWITH
OPERATOR_EQUA
OPERATOR_GREATERTHAN
OPERATOR_GREATERTHANOREQUAL
OPERATOR_LESSTHAN
OPERATOR_LESSTHANOREQUAL
OPERATOR_NOTEQUAL
OPERATOR_CONTAINSTEXT
OPERATOR_NOTCONTAINS
OPERATOR_BETWEEN
OPERATOR_NOTBETWEEN
写入图片
将图片写入某个单元格中:
$drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
$drawing->setName('Logo');
$drawing->setDescription('Logo');
$drawing->setPath($diagramPath);
$drawing->setHeight(120);
$drawing->setCoordinates("D2");$drawing->setOffsetX(0);
$drawing->setRotation(0);
$drawing->getShadow()->setVisible(true);
$drawing->getShadow()->setDirection(0);
$drawing->setWorksheet($spreadsheet->getActiveSheet());
设置超链接
给单元格设置超链接:
$spreadsheet->getActiveSheet()->getCell('B2')->getHyperlink()->setUrl("sheet://'Sheetname'!A1"); // 当前文档位置
$spreadsheet->getActiveSheet()->getCell('B2')->getHyperlink()->setUrl("https://www.baidu.com/"); // 外链地址
读取excel文件
下面介绍读取excel文件方法。
读取文本数据
<?phprequire 'vendor/autoload.php';use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;/* 读取excel */
// $reader = new Xlsx();
// $spreadsheet = $reader->load($fileName);
$reader = IOFactory::createReader('Xlsx');
$spreadsheet = $reader->load($fileName);
// $reader->setReadDataOnly(true); // 设置后无法获取excel中的图片$worksheet = $spreadsheet->getActiveSheet();
// $worksheet = $spreadsheet->getSheetByName('testcase');
// $rawCasedata = $worksheet->toArray();
$highestRow = $worksheet->getHighestRow(); // 取得总行数
$highestColumn = $worksheet->getHighestColumn(); // 取得总列数
$highestColumnIndex = Coordinate::columnIndexFromString($highestColumn); // 取得总列数$excelData = [];
for ($row = 1; $row <= $highestRow; $row++) {for ($col = 1; $col <= $highestColumnIndex; $col++) {$excelData[$row][] = (string)$worksheet->getCellByColumnAndRow($col, $row)->getValue();}
}echo "<pre>";
print_r($excelData);
echo "</pre>";?>
结果:
Array
([1] => Array([0] => Hello World ![1] => [2] => )[2] => Array([0] => [1] => [2] => )[3] => Array([0] => [1] => [2] => 你好 !))
读取图片
读取Excel文件中的图片,支持png、gif和jpg格式图片:
<?phprequire 'vendor/autoload.php';use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;$fileName = './test.xlsx';
$reader = IOFactory::createReader('Xlsx');
$spreadsheet = $reader->load($fileName);
$worksheet = $spreadsheet->getActiveSheet();/* 读取excel中的图片 */
$imgpath = './';
$imgArray = array();
foreach ($worksheet->getDrawingCollection() as $drawing) {list($startColumn, $startRow) = Coordinate::coordinateFromString($drawing->getCoordinates());print_r($startColumn);print_r($startRow);switch ($drawing->getExtension()) {case 'jpeg':$source = imagecreatefromjpeg($drawing->getPath());$imgname = $imgpath . $drawing->getCoordinates() . '.jpg';imagejpeg($source, $imgname);break;case 'png':$source = imagecreatefrompng($drawing->getPath());$imgname = $imgpath . $drawing->getCoordinates() . '.png';imagepng($source, $imgname);break;default: echo "Unsupported file type: " . $drawing->getExtension() . "\n";; }
}
读取超链接
读取超链接:
$spreadsheet = $reader->load($fileName);
$worksheet = $spreadsheet->getActiveSheet();
$spreadsheet->getActiveSheet()->getCell('A1')->hasHyperlink(); // 判断是否有超链接
$url = $spreadsheet->getActiveSheet()->getCell('A1')->getHyperlink()->getUrl(); // 读取超链接
下载文件
在服务器上创建了excel文件后,可以将它下载到客户端。
// redirect output to client browser
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header("Content-Disposition: attachment;filename=$downloadFileName");
header('Cache-Control: max-age=0');
$writer = new PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
$writer->save('php://output');
当然也可以下载已经生成的xlsx格式文件:
$FileName = basename($FilePath);
header("Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition: attachment; filename=$FileName");
header("Content-length: " . filesize($FilePath));
header("Pragma: no-cache");
header("Expires: 0");
readfile("$FilePath");
xls格式文件类型为:application/vnd.ms-excel
。
这里就介绍这么多了,PhpSpreadsheet的更多使用方法可参考官方文档:https://phpspreadsheet.readthedocs.io/en/latest/。
--THE END--
说人坏话只能说明自己也同样抱有小气的本性。——太宰治《人间失格》
PhpSpreadsheet读写Excel文件相关推荐
- php读写excel文件
1.引入包 有不少提供读写excel文件的包,这里选择比较常用的一个,加到自己的项目里就好了. "phpoffice/phpspreadsheet": "1.8.2&qu ...
- python怎么读excelsheet_python3 excle(python怎么读写excel文件)
python读取已经打开的3个word和excle文件的路径 用 win32com 操控 word和Excel就可以实现 咋样把python写入excle中 # 需安装 xlrd-0.9.2 和 xl ...
- python pandas读取excel-Python使用Pandas读写EXCEL文件教程
欢迎,来自IP地址为:211.103.135.163 的朋友 教程开始之前,我们需要首先了解一下什么是Excel,这有助于理解之后教程中的内容. 什么是Excel Excel 是微软出品的和款办公软 ...
- python处理excel教程实例-python 读写excel文件操作示例【附源码下载】
本文实例讲述了python 读写excel文件操作.分享给大家供大家参考,具体如下: 对excel文件的操作,python有第三方的工具包支持,xlutils,在这个工具包中包含了xlrd,xlwt等 ...
- python导入excel文件-python使用xlrd模块读写Excel文件的方法
本文实例讲述了python使用xlrd模块读写Excel文件的方法.分享给大家供大家参考.具体如下: 一.安装xlrd模块 到python官网下载http://pypi.python.org/pypi ...
- C++读写EXCEL文件方式比较 .
C++读取Excel的XLS文件的方法有很多,但是也许就是因为方法太多,大家在选择的时候会很疑惑. 由于前两天要做导表工具,比较了常用的方法,总结一下写个短文, 1.OLE的方式 这个大约是最常用的方 ...
- Python使用openpyxl读写excel文件
Python使用openpyxl读写excel文件 Python使用openpyxl读取excel文件中数据 Python使用openpyxl往excel文件中写入数据 Python使用openpyx ...
- 基于POI的读写Excel文件的工具类
依赖的jar包: import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStrea ...
- python xlrd xlwt pandas 模块 区别_python如何读写excel文件|python教程|python入门|python教程...
https://www.xin3721.com/eschool/pythonxin3721/ python读写excel的方式有很多,不同的模块在读写的方法上稍有区别: 用xlrd和xlwt进行exc ...
- python读取python源代码文件_python 读写excel文件操作示例【附源码下载】
本文实例讲述了python 读写excel文件操作.分享给大家供大家参考,具体如下: 对excel文件的操作,python有第三方的工具包支持,xlutils,在这个工具包中包含了xlrd,xlwt等 ...
最新文章
- GOF23设计模式(创建型模式) 原型模式
- webpack 最简打包结果分析
- iframe如何发送请求_插件分享 | 如何半天玩转一个“ES未授权利用”插件
- 【朝夕技术专刊】Core3.1WebApi_Filter详解
- 过程(栈帧结构是干货)
- 解决vue项目在ie浏览器中不显示的问题
- 灵魂拷问!一起刷完了这份1307页的安卓面试宝典吧,不吃透都对不起自己
- 【转】去掉换行符的几个方法
- 本地html如何导出pdf,html表格以pdf格式导出到本地
- vue key重复_12道vue高频原理面试题,你能答出几道?
- Java生鲜电商平台-提现模块的设计与架构
- RocketMQ Client 编码快速入门 与 可视化控制台
- 小白学 Python 爬虫(14):urllib 基础使用(四)
- 7.13建行天津实习面经
- 看《墨攻》理解IoC
- 机器学习在脊柱的应用现状:从临床的观点
- 十四五期间我国区块链技术趋势特征分析
- SaaS 软件开发为企业数字化转型赋能
- 基于汽车CAN总线专有协议OBD接口的调试方法及经验
- 【Android 10 源码】MediaRecorder 录像流程:MediaRecorder 开始录制
热门文章
- 艾司博讯:拼多多店铺要不要一直上新?上新有用吗?
- EasyCVR人脸识别框在播放器上显示及消失的机制设定
- 【转】前端开发设计必备的Chrome插件
- 从零开始用 Windows C++ 桌面程序制作方舟同人游戏(五)
- 总结:KPCB中国合伙人周炜
- USACO3.4 “破锣摇滚”乐队 Raucous Rockers - DP
- docker快速搭建http服务器
- 语言技能c1,从0开始学法语,20个月考下DALF C1,我如何立竿见影学语言?
- 人生没有退路,你所有遇到过的人,做过的事都不是偶然,一念天堂一念地狱
- C/C++在线IDE