PHPExcel是国外人开发的一个php处理excel插件,用来操作Office Excel 文档的一个PHP类库,它基于微软的Openxml标准和PHP语言。
可以使用它来读取、写入不同格式的电子表格。整体来说是一个不错的Excel操作类。
本文档搜集了两种文档,一个是PHPExcel中文手册,一个是全英文PHPExcel开发手册!
知识点文档:PHP知识总结 · 看云
参考文档地址:PHP操作Excel – PHPExcel 基本用法详解 - meiyoufan - 博客园
参考英文文档地址:Welcome to PhpSpreadsheet's documentation - PhpSpreadsheet Documentation
1、安装扩展
查看本地PHP是否安装zip扩展
命令查看php -m | grep zip
composer require phpoffice/phpspreadsheet
2、实例
单独使用
public function test(){
$data = [
['title1' => '111', 'title2' => '222'],
['title1' => '111', 'title2' => '222'],
['title1' => '111', 'title2' => '222']
];
$title = ['第一行标题', '第二行标题'];
// Create new Spreadsheet object
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
// 方法一,使用 setCellValueByColumnAndRow
//表头
//设置单元格内容
foreach ($title as $key => $value) {
// 单元格内容写入
$sheet->setCellValueByColumnAndRow($key + 1, 1, $value);
}
$row = 2; // 从第二行开始
foreach ($data as $item) {
$column = 1;
foreach ($item as $value) {
// 单元格内容写入
$sheet->setCellValueByColumnAndRow($column, $row, $value);
$column++;
}
$row++;
}
// 方法二,使用 setCellValue
//表头
//设置单元格内容
$titCol = 'A';
foreach ($title as $key => $value) {
// 单元格内容写入
$sheet->setCellValue($titCol . '1', $value);
$titCol++;
}
$row = 2; // 从第二行开始
foreach ($data as $item) {
$dataCol = 'A';
foreach ($item as $value) {
// 单元格内容写入
$sheet->setCellValue($dataCol . $row, $value);
$dataCol++;
}
$row++;
}
ob_end_clean();
// Redirect output to a client’s web browser (Xlsx)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="01simple.xlsx"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header('Pragma: public'); // HTTP/1.0
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
exit;
}
封装方法:
<?php
/**
* Created by PhpStorm.
* Author: Shadow
* Date: 2021/12/14
* Time: 8:00 上午
* description: Excel.php
*/
namespace app\admin\library;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\exception\ValidateException;
use think\facade\Filesystem;
class Excel
{
/**
* @param string $filename
* @return array|string
* @throws \PhpOffice\PhpSpreadsheet\Exception
* @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
*/
public static function importExcel($filename = "")
{
$file[] = $filename;
try {
// 验证文件大小,名称等是否正确
validate(['file' => 'filesize:51200|fileExt:xls,xlsx'])
->check($file);
// 将文件保存到本地
$savename = Filesystem::disk('public')->putFile('file', $file[0]);
// 截取后缀
$fileExtendName = substr(strrchr($savename, '.'), 1);
// 有Xls和Xlsx格式两种
if ($fileExtendName == 'xlsx') {
$objReader = IOFactory::createReader('Xlsx');
} else {
$objReader = IOFactory::createReader('Xls');
}
// 设置文件为只读
$objReader->setReadDataOnly(TRUE);
// 读取文件,tp6默认上传的文件,在runtime的相应目录下,可根据实际情况自己更改
$objPHPExcel = $objReader->load(public_path() . 'admin/' . $savename);
//excel中的第一张sheet
$sheet = $objPHPExcel->getSheet(0);
// 取得总行数
$highestRow = $sheet->getHighestRow();
// 取得总列数
$highestColumn = $sheet->getHighestColumn();
Coordinate::columnIndexFromString($highestColumn);
$lines = $highestRow - 1;
if ($lines <= 0) {
return "数据为空数组";
}
// 直接取出excle中的数据
$data = $objPHPExcel->getActiveSheet()->toArray();
// 删除第一个元素(表头)
array_shift($data);
//删除文件
unlink(public_path() . 'admin/' . $savename);
// 返回结果
return $data;
} catch (ValidateException $e) {
return $e->getMessage();
}
}
// 导出
public static function export($header = [], $type = true, $data = [], $fileName = "1910")
{
// 实例化类
$preadsheet = new Spreadsheet();
// 创建sheet
$sheet = $preadsheet->getActiveSheet();
// 循环设置表头数据
foreach ($header as $k => $v) {
$sheet->setCellValue($k, $v);
}
// 生成数据
$sheet->fromArray($data, null, "A2");
// 样式设置
$sheet->getDefaultColumnDimension()->setWidth(12);
// 设置下载与后缀
if ($type) {
header("Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
$type = "Xlsx";
$suffix = "xlsx";
} else {
header("Content-Type:application/vnd.ms-excel");
$type = "Xls";
$suffix = "xls";
}
ob_end_clean();//清楚缓存区
// 激活浏览器窗口
header("Content-Disposition:attachment;filename=$fileName.$suffix");
//缓存控制
header("Cache-Control:max-age=0");
// 调用方法执行下载
$writer = IOFactory::createWriter($preadsheet, $type);
// 数据流
$writer->save("php://output");
}
}
控制器调用:
导入:
public function index(Request $request)
{
// 接收文件上传信息
$files = $request->file("myfile");
// 调用类库,读取excel中的内容
$data = Excel::importExcel($files);
dd($data); // 二维数组
}
导出
public function get()
{
// 设置表格的表头数据
$header = ["A1" => "编号", "B1" => "姓名", "C1" => "年龄"];
// 假设下面这个数组从数据库查询出的二维数组
$data = [
[1,'张三',18],
[2,'李四',19],
[3,'王五',22],
];
// 保存文件的类型
$type= true;
// 设置下载文件保存的名称
$fileName = '信息导出'.time();
// 调用方法导出excel
Excel::export($header,$type,$data,$fileName);
}