php phpOffice/PhpSpreadsheet 使用记录
时间:2024-4-30 10:54 作者:杨佳乐 分类: PHP
<?php
//先自行使用composer下载phpoffice到项目文件夹
//官网地址:https://phpspreadsheet.readthedocs.io/en/latest/
//安装命令:composer require phpoffice/phpspreadsheet
//引入自动加载
require "./vendor/autoload.php";
//运行命名空间
use PhpOffice\PhpSpreadsheet;
//文件名
$inputFileName="1.xlsx";
//自动识别文件类型
$inputFileType = \PhpOffice\PhpSpreadsheet\IOFactory::identify($inputFileName);
/** Create a new Reader of the type that has been identified **/
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
/** Load $inputFileName to a Spreadsheet Object **/
$spreadsheet = $reader->load($inputFileName);
//获取工作簿
$sheet=$spreadsheet->getActiveSheet();
//读取表格全部数据为数组
$sheetData = $sheet->toArray(null, true, true, true);
//获取单个单元格内容
$sheetvalue=$sheet->getCell('A1')->getValue();
$sheetvalue=$sheet->getCellByColumnAndRow(1,1)->getValue();
//设置单元格内容
$sheet->setCellValueByColumnAndRow(1,1,'2020级学生学号');
$sheet->setCellValue('A2', 'www.phpexcel.net');
//将上面单元格设置可点击的链接 注:网址需要加http://
$sheet->getCell('A2')->getHyperlink()->setUrl('http://www.phpexcel.net');
//设置工作簿标签颜色
//$sheet->getTabColor()->setRGB('F9F900');
//写入图片到单元格
$drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
$drawing->setName('Logo');
$drawing->setDescription('Logo');
$drawing->setPath('1.jpg');
//单元格坐标
$drawing->setCoordinates('A2');
//设置图片宽高
$drawing->setWidth(30);
$drawing->setHeight(30);
$drawing->setWorksheet($sheet);
//多个图片需用遍历new
/*for ($i=3;$i<=5;$i++){
$drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
$drawing->setName('Logo');
$drawing->setDescription('Logo');
$drawing->setPath('1.jpg');
$drawing->setCoordinates('A'.$i);
$drawing->setWidth(30);
$drawing->setHeight(30);
$drawing->setWorksheet($sheet);
}*/
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('01simple.xlsx');
//写入文件到项目目录
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
$writer->save("2.xlsx");
//下载文件
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告诉浏览器输出07Excel文件
//header(‘Content-Type:application/vnd.ms-excel‘);//告诉浏览器将要输出Excel03版本文件
header('Content-Disposition: attachment;filename="文档.xlsx"');//告诉浏览器输出浏览器名称
header('Cache-Control: max-age=0');//禁止缓存
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');