PhpSpreadsheet是一个纯PHP类库,使你能够读写Excel、LibreOffic Calc等这样的表格格式。
https://phpspreadsheet.readthedocs.io/en/develop/
坑
列从0开始算,行从1开始算
$sheet->setCellValueByColumnAndRow(0,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; $spredsheet = new Spreadsheet(); $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://output
或php://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);
宽度设置
$this->getColumnDimension($columnIndex)->setWidth($width);
还可以让其自适应(不靠谱,建议自行设置)
$sheet->calculateColumnWidths();
直接输出下载
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‘);
自动计算列宽
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