欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

PHP使用PhpSpreadsheet操作Excel实例详解

程序员文章站 2022-10-10 20:57:17
本文实例讲述了php使用phpspreadsheet操作excel。分享给大家供大家参考,具体如下:一、phpspreadsheet 介绍1、phpspreadsheet 是什么phpspreadsh...

本文实例讲述了php使用phpspreadsheet操作excel。分享给大家供大家参考,具体如下:

一、phpspreadsheet 介绍

1、phpspreadsheet 是什么

phpspreadsheet是一个用纯php编写的库,提供了一组类,使您可以读取和写入不同的电子表格文件格式
phpspreadsheet提供了丰富的api接口,可以设置诸多单元格以及文档属性,包括样式、图片、日期、函数等等诸多应用,总之你想要什么样的excel表格,phpspreadsheet都能做到

  • 使用 phpspreadsheet 开发的php要求 7.1或更高版本
  • phpspreadsheet 支持链式操作
2、phpspreadsheet 支持的文件格式

PHP使用PhpSpreadsheet操作Excel实例详解

3、phpspreadsheet 官方网址
4、phpspreadsheet 安装
  • composer require phpoffice/phpspreadsheet

二、基础知识

1、载入
<?php
  # 载入composer自动加载文件 require 瑞块儿
  require 'vendor/autoload.php'; autoload 奥特老特
  # 给类文件的命名空间起个别名
  use phpoffice\phpspreadsheet\spreadsheet;
  # 实例化 spreadsheet 对象
  $spreadsheet = new spreadsheet();
2、获取工作簿
  • getactivesheet
<?php
  # 载入composer自动加载文件
  require 'vendor/autoload.php';
  # 给类文件的命名空间起个别名
  use phpoffice\phpspreadsheet\spreadsheet;
  # 实例化 spreadsheet 对象
  $spreadsheet = new spreadsheet();
  # 获取活动工作薄
  $sheet = $spreadsheet->getactivesheet();
3、获取单元格
  • 两种获取单元格方式
  • getcell
  • getcellbycolumnandrow
<?php
  # 载入composer自动加载文件
  require 'vendor/autoload.php';
  # 给类文件的命名空间起个别名
  use phpoffice\phpspreadsheet\spreadsheet;
  # 实例化 spreadsheet 对象
  $spreadsheet = new spreadsheet();
  # 获取活动工作薄
  $sheet = $spreadsheet->getactivesheet();
  # 获取单元格
  $cell = $sheet->getcell('a1');
  $cell = $sheet->getcellbycolumnandrow(1,1);
4、设置单元格
  • setvalue
  • 参数:单元格的值
<?php
	# 载入composer自动加载文件
	require 'vendor/autoload.php';
	# 给类文件的命名空间起个别名
	use phpoffice\phpspreadsheet\spreadsheet;
	# 实例化 spreadsheet 对象
	$spreadsheet = new spreadsheet();
	# 获取活动工作薄
	$sheet = $spreadsheet->getactivesheet();

	# 获取单元格
	$cella = $sheet->getcell('a1');
	# 设置单元格值
	$cella->setvalue('欧阳克');

	# 获取单元格
	$cellb = $sheet->getcellbycolumnandrow(1,2);
	# 设置单元格值
	$cellb->setvalue('黄蓉');

	# 获取设置单元格,链式操作
	$sheet->getcell('a3')->setvalue('郭靖');
	$sheet->getcellbycolumnandrow(1,4)->setvalue('杨康');
5、获取单元格值
  • getvalue 获取单元格值
  • getcoordinate 获取单元格坐标
<?php
	# 载入composer自动加载文件
	require 'vendor/autoload.php';
	# 给类文件的命名空间起个别名
	use phpoffice\phpspreadsheet\spreadsheet;
	# 实例化 spreadsheet 对象
	$spreadsheet = new spreadsheet();
	# 获取活动工作薄
	$sheet = $spreadsheet->getactivesheet();

	# 获取单元格
	$cella = $sheet->getcell('a1');
	# 设置单元格值
	$cella->setvalue('欧阳克');

	echo '值: ', $cella->getvalue(),php_eol;
	echo '坐标: ', $cella->getcoordinate();
6、保存表格
<?php
	# 载入composer自动加载文件
	require 'vendor/autoload.php';
	# 给类文件的命名空间起个别名
	use phpoffice\phpspreadsheet\spreadsheet;
	# 实例化 spreadsheet 对象
	$spreadsheet = new spreadsheet();
	# 获取活动工作薄
	$sheet = $spreadsheet->getactivesheet();

	# 获取单元格
	$cella = $sheet->getcell('a1');
	# 设置单元格值
	$cella->setvalue('欧阳克');

	# 获取单元格
	$cellb = $sheet->getcellbycolumnandrow(1,2);
	# 设置单元格值
	$cellb->setvalue('黄蓉');

	# 获取设置单元格,链式操作
	$sheet->getcell('a3')->setvalue('郭靖');
	$sheet->getcellbycolumnandrow(1,4)->setvalue('杨康');

	# xlsx类 将电子表格保存到文件
	use phpoffice\phpspreadsheet\writer\xlsx;
	$writer = new xlsx($spreadsheet);
	$writer->save('1.xlsx');

三、强化单元格

1、设置单元格
  • setcellvalue
  • 参数1:单元格位置
  • 参数2:单元格的值
  • setcellvaluebycolumnandrow
  • 参数1:列位置
  • 参数2:行位置
  • 参数3:单元格的值
<?php
	# 载入composer自动加载文件
	require 'vendor/autoload.php';
	# 给类文件的命名空间起个别名
	use phpoffice\phpspreadsheet\spreadsheet;
	# 实例化 spreadsheet 对象
	$spreadsheet = new spreadsheet();
	# 获取活动工作薄
	$sheet = $spreadsheet->getactivesheet();

	$sheet->setcellvalue('a1','id');
	$sheet->setcellvalue('b1','姓名');
	$sheet->setcellvalue('c1','年龄');
	$sheet->setcellvalue('d1','身高');

	$sheet->setcellvaluebycolumnandrow(1, 2, 1);
	$sheet->setcellvaluebycolumnandrow(2, 2, '欧阳克');
	$sheet->setcellvaluebycolumnandrow(3, 2, '18岁');
	$sheet->setcellvaluebycolumnandrow(4, 2, '188cm');

	$sheet->setcellvaluebycolumnandrow(1, 3, 2);
	$sheet->setcellvaluebycolumnandrow(2, 3, '黄蓉');
	$sheet->setcellvaluebycolumnandrow(3, 3, '17岁');
	$sheet->setcellvaluebycolumnandrow(4, 3, '165cm');

	# xlsx类 将电子表格保存到文件
	use phpoffice\phpspreadsheet\writer\xlsx;
	$writer = new xlsx($spreadsheet);
	$writer->save('1.xlsx');
2、单元格文字样式
  • getstyle 获取单元格样式
  • getfont 获取单元格文字样式
  • setbold 设置文字粗细
  • setname 设置文字字体
  • setsize 设置文字大小
<?php
	# 载入composer自动加载文件
	require 'vendor/autoload.php';
	# 给类文件的命名空间起个别名
	use phpoffice\phpspreadsheet\spreadsheet;
	# 实例化 spreadsheet 对象
	$spreadsheet = new spreadsheet();
	# 获取活动工作薄
	$sheet = $spreadsheet->getactivesheet();

	$sheet->setcellvalue('a1','id');
	$sheet->setcellvalue('b1','姓名');
	$sheet->setcellvalue('c1','年龄');
	$sheet->setcellvalue('d1','身高');

	$sheet->setcellvaluebycolumnandrow(1, 2, 1);
	$sheet->setcellvaluebycolumnandrow(2, 2, '欧阳克');
	$sheet->setcellvaluebycolumnandrow(3, 2, '18岁');
	$sheet->setcellvaluebycolumnandrow(4, 2, '188cm');

	$sheet->setcellvaluebycolumnandrow(1, 3, 2);
	$sheet->setcellvaluebycolumnandrow(2, 3, '黄蓉');
	$sheet->setcellvaluebycolumnandrow(3, 3, '17岁');
	$sheet->setcellvaluebycolumnandrow(4, 3, '165cm');

	$sheet->getstyle('b2')->getfont()->setbold(true)->setname('宋体')->setsize(20);

	# xlsx类 将电子表格保存到文件
	use phpoffice\phpspreadsheet\writer\xlsx;
	$writer = new xlsx($spreadsheet);
	$writer->save('1.xlsx');
3、单元格文字颜色
  • getcolor() 获取坐标颜色
  • setrgb() 设置字体颜色
  • getrgb() 获取字体颜色
  • setargb() 设置字体颜色
  • getargb() 获取字体颜色
<?php
	# 载入composer自动加载文件
	require 'vendor/autoload.php';
	# 给类文件的命名空间起个别名
	use phpoffice\phpspreadsheet\spreadsheet;
	# 实例化 spreadsheet 对象
	$spreadsheet = new spreadsheet();
	# 获取活动工作薄
	$sheet = $spreadsheet->getactivesheet();

	$sheet->setcellvalue('a1','id');
	$sheet->setcellvalue('b1','姓名');
	$sheet->setcellvalue('c1','年龄');
	$sheet->setcellvalue('d1','身高');

	$sheet->setcellvaluebycolumnandrow(1, 2, 1);
	$sheet->setcellvaluebycolumnandrow(2, 2, '欧阳克');
	$sheet->setcellvaluebycolumnandrow(3, 2, '18岁');
	$sheet->setcellvaluebycolumnandrow(4, 2, '188cm');

	$sheet->setcellvaluebycolumnandrow(1, 3, 2);
	$sheet->setcellvaluebycolumnandrow(2, 3, '黄蓉');
	$sheet->setcellvaluebycolumnandrow(3, 3, '17岁');
	$sheet->setcellvaluebycolumnandrow(4, 3, '165cm');

	$sheet->getstyle('b2')->getfont()->getcolor()->setrgb('#aeeeee');
	echo $sheet->getstyle('b2')->getfont()->getcolor()->getrgb(),php_eol;

	$sheet->getstyle('b3')->getfont()->getcolor()->setargb('ffff0000');
	echo $sheet->getstyle('b3')->getfont()->getcolor()->getargb();

	# xlsx类 将电子表格保存到文件
	use phpoffice\phpspreadsheet\writer\xlsx;
	$writer = new xlsx($spreadsheet);
	$writer->save('1.xlsx');
4、单元格格式
  • getnumberformat 获取格式
  • setformatcode 设置格式
<?php
	# 载入composer自动加载文件
	require 'vendor/autoload.php';
	# 给类文件的命名空间起个别名
	use phpoffice\phpspreadsheet\spreadsheet;
	# 实例化 spreadsheet 对象
	$spreadsheet = new spreadsheet();
	# 获取活动工作薄
	$sheet = $spreadsheet->getactivesheet();

	$sheet->setcellvalue('a1','2019-10-10 10:10:10');
	$sheet->setcellvalue('a2','2019-10-10 10:10:10');
	$sheet->getstyle('a2')->getnumberformat()->setformatcode(\phpoffice\phpspreadsheet\style\numberformat::format_date_yyyymmdd2);

	# xlsx类 将电子表格保存到文件
	use phpoffice\phpspreadsheet\writer\xlsx;
	$writer = new xlsx($spreadsheet);
	$writer->save('1.xlsx');
  • setwraptext 设置文本里的\n符合为:换行
<?php
	# 载入composer自动加载文件
	require 'vendor/autoload.php';
	# 给类文件的命名空间起个别名
	use phpoffice\phpspreadsheet\spreadsheet;
	# 实例化 spreadsheet 对象
	$spreadsheet = new spreadsheet();
	# 获取活动工作薄
	$sheet = $spreadsheet->getactivesheet();

	$sheet->setcellvalue('a1',"欧阳克\n黄蓉");
	$sheet->getstyle('a1')->getalignment()->setwraptext(true);

	# xlsx类 将电子表格保存到文件
	use phpoffice\phpspreadsheet\writer\xlsx;
	$writer = new xlsx($spreadsheet);
	$writer->save('1.xlsx');
  • gethyperlink 获取单元格链接
  • seturl 设置单元格链接
<?php
	# 载入composer自动加载文件
	require 'vendor/autoload.php';
	# 给类文件的命名空间起个别名
	use phpoffice\phpspreadsheet\spreadsheet;
	# 实例化 spreadsheet 对象
	$spreadsheet = new spreadsheet();
	# 获取活动工作薄
	$sheet = $spreadsheet->getactivesheet();

	$sheet->setcellvalue('a1','www.php.cn');
	$sheet->getcell('a1')->gethyperlink()->seturl('http://www.php.cn');

	# xlsx类 将电子表格保存到文件
	use phpoffice\phpspreadsheet\writer\xlsx;
	$writer = new xlsx($spreadsheet);
	$writer->save('1.xlsx');

四、批量操作

1、使用公式
<?php
	# 载入composer自动加载文件
	require 'vendor/autoload.php';
	# 给类文件的命名空间起个别名
	use phpoffice\phpspreadsheet\spreadsheet;
	# 实例化 spreadsheet 对象
	$spreadsheet = new spreadsheet();
	# 获取活动工作薄
	$sheet = $spreadsheet->getactivesheet();

	$sheet->setcellvalue('a1','10');
	$sheet->setcellvalue('b1','15');
	$sheet->setcellvalue('c1','20');
	$sheet->setcellvalue('d1','25');
	$sheet->setcellvalue('e1','30');
	$sheet->setcellvalue('g1','35');
	$sheet->setcellvalue('a2', '总数:');
	$sheet->setcellvalue('b2', '=sum(a1:g1)');
	$sheet->setcellvalue('a3', '平均数:');
	$sheet->setcellvalue('b3', '=average(a1:g1)');
	$sheet->setcellvalue('a4', '最小数:');
	$sheet->setcellvalue('b4', '=min(a1:g1)');
	$sheet->setcellvalue('a5', '最大数:');
	$sheet->setcellvalue('b5', '=max(a1:g1)');
	$sheet->setcellvalue('a6', '最大数:');
	$sheet->setcellvalue('b6', '\=max(a1:g1)');	// 使用转义字符

	# xlsx类 将电子表格保存到文件
	use phpoffice\phpspreadsheet\writer\xlsx;
	$writer = new xlsx($spreadsheet);
	$writer->save('1.xlsx');
2、批量赋值
  • fromarray 从数组中的值填充工作表
  • 参数1:数据(数组)
  • 参数2:去除某个值
  • 参数3:从哪个位置开始
<?php
	# 载入composer自动加载文件
	require 'vendor/autoload.php';
	# 给类文件的命名空间起个别名
	use phpoffice\phpspreadsheet\spreadsheet;
	# 实例化 spreadsheet 对象
	$spreadsheet = new spreadsheet();
	# 获取活动工作薄
	$sheet = $spreadsheet->getactivesheet();

	$sheet->setcellvalue('a1','id');
	$sheet->setcellvalue('b1','姓名');
	$sheet->setcellvalue('c1','年龄');
	$sheet->setcellvalue('d1','身高');

	$sheet->fromarray(
		[
			[1,'欧阳克','18岁','188cm'],
			[2,'黄蓉','17岁','165cm'],
			[3,'郭靖','21岁','180cm']
		],
		3,
		'a2'
	);

	# xlsx类 将电子表格保存到文件
	use phpoffice\phpspreadsheet\writer\xlsx;
	$writer = new xlsx($spreadsheet);
	$writer->save('1.xlsx');
3、合并单元格
<?php
	# 载入composer自动加载文件
	require 'vendor/autoload.php';
	# 给类文件的命名空间起个别名
	use phpoffice\phpspreadsheet\spreadsheet;
	# 实例化 spreadsheet 对象
	$spreadsheet = new spreadsheet();
	# 获取活动工作薄
	$sheet = $spreadsheet->getactivesheet();

	$sheet->mergecells('a1:b5');

	$sheet->getcell('a1')->setvalue('欧阳克');

	# xlsx类 将电子表格保存到文件
	use phpoffice\phpspreadsheet\writer\xlsx;
	$writer = new xlsx($spreadsheet);
	$writer->save('1.xlsx');

合并后,赋值只能给a1,开始的坐标。

4、拆分单元格
<?php
	# 载入composer自动加载文件
	require 'vendor/autoload.php';
	# 给类文件的命名空间起个别名
	use phpoffice\phpspreadsheet\spreadsheet;
	# 实例化 spreadsheet 对象
	$spreadsheet = new spreadsheet();
	# 获取活动工作薄
	$sheet = $spreadsheet->getactivesheet();

	$sheet->mergecells('a1:b5');

	$sheet->unmergecells('a1:b5');

	# xlsx类 将电子表格保存到文件
	use phpoffice\phpspreadsheet\writer\xlsx;
	$writer = new xlsx($spreadsheet);
	$writer->save('1.xlsx');
5、列和行操作
  • getcolumndimension 获取一列
  • getwidth 获取一列的宽度
  • setwidth 设置一列的宽度
  • setautosize 设置一列的宽度自动调整
  • getdefaultcolumndimension 获取一列的默认值
<?php
	# 载入composer自动加载文件
	require 'vendor/autoload.php';
	# 给类文件的命名空间起个别名
	use phpoffice\phpspreadsheet\spreadsheet;
	# 实例化 spreadsheet 对象
	$spreadsheet = new spreadsheet();
	# 获取活动工作薄
	$sheet = $spreadsheet->getactivesheet();

	echo $sheet->getcolumndimension('a')->getwidth();

	$sheet->getcolumndimension('a')->setwidth(100);

	$sheet->getcolumndimension('b')->setautosize(true);

	$sheet->getdefaultcolumndimension()->setwidth(1);

	# xlsx类 将电子表格保存到文件
	use phpoffice\phpspreadsheet\writer\xlsx;
	$writer = new xlsx($spreadsheet);
	$writer->save('1.xlsx');
  • getrowdimension 获取一行
  • getrowheight 获取一行的高度
  • setrowheight 设置一行的高度
<?php
	# 载入composer自动加载文件
	require 'vendor/autoload.php';
	# 给类文件的命名空间起个别名
	use phpoffice\phpspreadsheet\spreadsheet;
	# 实例化 spreadsheet 对象
	$spreadsheet = new spreadsheet();
	# 获取活动工作薄
	$sheet = $spreadsheet->getactivesheet();

	echo $sheet->getrowdimension(1)->getrowheight();

	$sheet->getrowdimension(1)->setrowheight(100);

	$sheet->getdefaultrowdimension()->setrowheight(1);

	# xlsx类 将电子表格保存到文件
	use phpoffice\phpspreadsheet\writer\xlsx;
	$writer = new xlsx($spreadsheet);
	$writer->save('1.xlsx');
  • gethighestcolumn 获取总列数
  • gethighestrow 获取总行数
<?php
	# 载入composer自动加载文件
	require 'vendor/autoload.php';
	# 给类文件的命名空间起个别名
	use phpoffice\phpspreadsheet\spreadsheet;
	# 实例化 spreadsheet 对象
	$spreadsheet = new spreadsheet();
	# 获取活动工作薄
	$sheet = $spreadsheet->getactivesheet();

	$sheet->setcellvalue('a1','id');
	$sheet->setcellvalue('b1','姓名');
	$sheet->setcellvalue('c1','年龄');
	$sheet->setcellvalue('d1','身高');

	$sheet->setcellvaluebycolumnandrow(1, 2, 1);
	$sheet->setcellvaluebycolumnandrow(2, 2, '欧阳克');
	$sheet->setcellvaluebycolumnandrow(3, 2, '18岁');
	$sheet->setcellvaluebycolumnandrow(4, 2, '188cm');

	$sheet->setcellvaluebycolumnandrow(1, 3, 2);
	$sheet->setcellvaluebycolumnandrow(2, 3, '黄蓉');
	$sheet->setcellvaluebycolumnandrow(3, 3, '17岁');
	$sheet->setcellvaluebycolumnandrow(4, 3, '165cm');

	echo $sheet->gethighestcolumn();
	echo $sheet->gethighestrow();

	# xlsx类 将电子表格保存到文件
	use phpoffice\phpspreadsheet\writer\xlsx;
	$writer = new xlsx($spreadsheet);
	$writer->save('1.xlsx');
6、单元格样式
  • applyfromarray
<?php
	# 载入composer自动加载文件
	require 'vendor/autoload.php';
	# 给类文件的命名空间起个别名
	use phpoffice\phpspreadsheet\spreadsheet;
	# 实例化 spreadsheet 对象
	$spreadsheet = new spreadsheet();
	# 获取活动工作薄
	$sheet = $spreadsheet->getactivesheet();

	$sheet->setcellvalue('a1','id');
	$sheet->setcellvalue('b1','姓名');
	$sheet->setcellvalue('c1','年龄');
	$sheet->setcellvalue('d1','身高');

	$sheet->setcellvaluebycolumnandrow(1, 2, 1);
	$sheet->setcellvaluebycolumnandrow(2, 2, '欧阳克');
	$sheet->setcellvaluebycolumnandrow(3, 2, '18岁');
	$sheet->setcellvaluebycolumnandrow(4, 2, '188cm');

	$stylearray = [
		// use phpoffice\phpspreadsheet\style\alignment; 文件里常量,就是参数
		// alignment::horizontal_center 水平居中
		// alignment::vertical_center	垂直居中
		'alignment' => [
			// 'horizontal' => alignment::horizontal_center, //水平居中
			// 'vertical' => alignment::vertical_center, //垂直居中
			'horizontal' => 'center', //水平居中
			'vertical' => 'center', //垂直居中
		],
		// use phpoffice\phpspreadsheet\style\border; 文件里常量,就是参数
		// border::border_thick 边框样式
		'borders' => [
			'outline' => [
				// 'borderstyle' => '\phpoffice\phpspreadsheet\style\border::border_thick',
				'borderstyle' => 'thick',
				'color' => ['argb' => 'ffff0000'],
			],
		],
		'font' => [
			'name' => '黑体',
			'bold' => true,
			'size' => 22
		]
	];

	$sheet->getstyle('a1')->applyfromarray($stylearray);

	# xlsx类 将电子表格保存到文件
	use phpoffice\phpspreadsheet\writer\xlsx;
	$writer = new xlsx($spreadsheet);
	$writer->save('1.xlsx');

五、工作薄操作

1、xlsx 文件下载
  • iofactory::createwriter 写入到文件
<?php
	# 载入composer自动加载文件
	require 'vendor/autoload.php';
	# 给类文件的命名空间起个别名
	use phpoffice\phpspreadsheet\spreadsheet;
	# 实例化 spreadsheet 对象
	$spreadsheet = new spreadsheet();
	# 获取活动工作薄
	$sheet = $spreadsheet->getactivesheet();

	$sheet->setcellvalue('a1','id');
	$sheet->setcellvalue('b1','姓名');
	$sheet->setcellvalue('c1','年龄');
	$sheet->setcellvalue('d1','身高');

	$sheet->setcellvaluebycolumnandrow(1, 2, 1);
	$sheet->setcellvaluebycolumnandrow(2, 2, '欧阳克');
	$sheet->setcellvaluebycolumnandrow(3, 2, '18岁');
	$sheet->setcellvaluebycolumnandrow(4, 2, '188cm');

	// mime 协议,文件的类型,不设置,会默认html
	header('content-type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
	// mime 协议的扩展
	header('content-disposition:attachment;filename=1.xlsx');
	// 缓存控制
	header('cache-control:max-age=0');

	$writer = \phpoffice\phpspreadsheet\iofactory::createwriter($spreadsheet, 'xlsx');
	// php://output 它是一个只写数据流, 允许你以 print 和 echo一样的方式写入到输出缓冲区。 
	$writer->save('php://output');
2、xls 文件下载
<?php
	# 载入composer自动加载文件
	require 'vendor/autoload.php';
	# 给类文件的命名空间起个别名
	use phpoffice\phpspreadsheet\spreadsheet;
	# 实例化 spreadsheet 对象
	$spreadsheet = new spreadsheet();
	# 获取活动工作薄
	$sheet = $spreadsheet->getactivesheet();

	$sheet->setcellvalue('a1','id');
	$sheet->setcellvalue('b1','姓名');
	$sheet->setcellvalue('c1','年龄');
	$sheet->setcellvalue('d1','身高');

	$sheet->setcellvaluebycolumnandrow(1, 2, 1);
	$sheet->setcellvaluebycolumnandrow(2, 2, '欧阳克');
	$sheet->setcellvaluebycolumnandrow(3, 2, '18岁');
	$sheet->setcellvaluebycolumnandrow(4, 2, '188cm');

	$filename = '1.xls';
	header('content-type:application/vnd.ms-excel');
	header('content-disposition:attachment;filename=1.xls');
	header('cache-control:max-age=0');

	$writer = \phpoffice\phpspreadsheet\iofactory::createwriter($spreadsheet, 'xls');
	$writer->save('php://output');
3、设置工作簿标题
  • settitle
<?php
	# 载入composer自动加载文件
	require 'vendor/autoload.php';
	# 给类文件的命名空间起个别名
	use phpoffice\phpspreadsheet\spreadsheet;
	# 实例化 spreadsheet 对象
	$spreadsheet = new spreadsheet();
	# 获取活动工作薄
	$sheet = $spreadsheet->getactivesheet();

	$sheet->setcellvalue('a1','id');
	$sheet->setcellvalue('b1','姓名');
	$sheet->setcellvalue('c1','年龄');
	$sheet->setcellvalue('d1','身高');

	$sheet->setcellvaluebycolumnandrow(1, 2, 1);
	$sheet->setcellvaluebycolumnandrow(2, 2, '欧阳克');
	$sheet->setcellvaluebycolumnandrow(3, 2, '18岁');
	$sheet->setcellvaluebycolumnandrow(4, 2, '188cm');

	$sheet->settitle('欧阳克');

	// mime 协议,文件的类型,不设置,会默认html
	header('content-type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
	// mime 协议的扩展
	header('content-disposition:attachment;filename=1.xlsx');
	// 缓存控制
	header('cache-control:max-age=0');

	$writer = \phpoffice\phpspreadsheet\iofactory::createwriter($spreadsheet, 'xlsx');
	// php://output 它是一个只写数据流, 允许你以 print 和 echo一样的方式写入到输出缓冲区。 
	$writer->save('php://output');
4、读取表格
<?php
	# 载入composer自动加载文件
	require 'vendor/autoload.php';

	# 创建读操作
	$reader = \phpoffice\phpspreadsheet\iofactory::createreader('xlsx');
	# 打开文件、载入excel表格
	$spreadsheet = $reader->load('1.xlsx');
	# 获取活动工作薄
	$sheet = $spreadsheet->getactivesheet();

	# 获取 单元格值 和 坐标
	$cellc1 = $sheet->getcell('b2');
	echo '值: ', $cellc1->getvalue(),php_eol;
	echo '坐标: ', $cellc1->getcoordinate(),php_eol;

	$sheet->setcellvalue('b2','欧阳锋');

	# 获取 单元格值 和 坐标
	$cellc2 = $sheet->getcell('b2');
	echo '值: ', $cellc2->getvalue(),php_eol;
	echo '坐标: ', $cellc2->getcoordinate();

六、office 后缀对应的 content-type

后缀 mime type
.doc application/msword
.dot application/msword
.docx application/vnd.openxmlformats-officedocument.wordprocessingml.document
.dotx application/vnd.openxmlformats-officedocument.wordprocessingml.template
.docm application/vnd.ms-word.document.macroenabled.12
.dotm application/vnd.ms-word.template.macroenabled.12
.xls application/vnd.ms-excel
.xlt application/vnd.ms-excel
.xla application/vnd.ms-excel
.xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.xltx application/vnd.openxmlformats-officedocument.spreadsheetml.template
.xlsm application/vnd.ms-excel.sheet.macroenabled.12
.xltm application/vnd.ms-excel.template.macroenabled.12
.xlam application/vnd.ms-excel.addin.macroenabled.12
.xlsb application/vnd.ms-excel.sheet.binary.macroenabled.12
.ppt application/vnd.ms-powerpoint
.pot application/vnd.ms-powerpoint
.pps application/vnd.ms-powerpoint
.ppa application/vnd.ms-powerpoint
.pptx application/vnd.openxmlformats-officedocument.presentationml.presentation
.potx application/vnd.openxmlformats-officedocument.presentationml.template
.ppsx application/vnd.openxmlformats-officedocument.presentationml.slideshow
.ppam application/vnd.ms-powerpoint.addin.macroenabled.12
.pptm application/vnd.ms-powerpoint.presentation.macroenabled.12
.potm application/vnd.ms-powerpoint.presentation.macroenabled.12
.ppsm application/vnd.ms-powerpoint.slideshow.macroenabled.12

七、实战

1、导出数据
  • login_log 登陆日志表
create table `login_log` (
	`id` int(11) not null auto_increment,
	`uid` int(11) default null comment '管理员id',
	`client` tinyint(4) unsigned default '0' comment '0-pc 1-ios 2-android',
	`add_time` int(11) default '0' comment '创建时间',
	`ip` bigint(20) unsigned not null default '0' comment '登录ip',
	primary key (`id`) using btree
) engine=myisam auto_increment=1122 default charset=utf8mb4 collate=utf8mb4_0900_ai_ci comment='登录日志';
  • index.php 数据列表页面
<?php 
	# 载入方法库
	require 'function.php';

	$select = select('login_log','*');

	if(empty($select)){
		exit;
	}else{
		foreach($select as &$v){
			switch ($v['client']) {
				case 0:
					$v['client'] = 'pc电脑';
					break;
				case 1:
					$v['client'] = '苹果手机';
					break;
				case 2:
					$v['client'] = '安卓手机';
					break;
			}
			$v['add_time'] = date('y-m-d h:i:s',$v['add_time']);
		}
	}
?>
<!doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<title>导出数据</title>
		<link rel="stylesheet" href="layui/css/layui.css" rel="external nofollow" rel="external nofollow" >
	</head>
	<body>
		<div style="text-align:center;">
			<a href="download.php" rel="external nofollow" rel="external nofollow" class="layui-btn layui-btn-radius layui-btn-danger">导出数据</a>
		</div>
		<table class="layui-table">
			<thead>
				<tr>
					<th>id</th>
					<th>用户id</th>
					<th>登陆设备</th>
					<th>登陆时间</th>
					<th>登陆ip</th>
				</tr> 
			</thead>
			<tbody>
				<?php 
					foreach($select as $v){
				?>
					<tr>
						<td><?php echo $v['id'] ?></td>
						<td><?php echo $v['uid'] ?></td>
						<td><?php echo $v['client'] ?></td>
						<td><?php echo $v['add_time'] ?></td>
						<td><?php echo $v['ip'] ?></td>
					</tr>
				<?php 
					} 
				?>
			</tbody>
		</table>
	</body>
</html>
  • download.php 导出操作
<?php 
	# 载入方法库
	require 'function.php';

	$select = select('login_log','*');

	if(empty($select)){
		exit;
	}else{
		foreach($select as &$v){
			switch ($v['client']) {
				case 0:
					$v['client'] = 'pc电脑';
					break;
				case 1:
					$v['client'] = '苹果手机';
					break;
				case 2:
					$v['client'] = '安卓手机';
					break;
			}
			$v['add_time'] = date('y-m-d h:i:s',$v['add_time']);
		}
	}
	
	# 载入composer自动加载文件
	require 'vendor/autoload.php';
	# 给类文件的命名空间起个别名
	use \phpoffice\phpspreadsheet\spreadsheet;
	# 实例化 spreadsheet 对象
	$spreadsheet = new spreadsheet();
	# 获取活动工作薄
	$sheet = $spreadsheet->getactivesheet();

	$sheet->setcellvalue('a1','id');
	$sheet->setcellvalue('b1','用户id');
	$sheet->setcellvalue('c1','登陆设备');
	$sheet->setcellvalue('d1','登陆时间');
	$sheet->setcellvalue('e1','登陆ip');
	$sheet->fromarray(
		$select,
		null,
		'a2'
	);

	// mime 协议,文件的类型,不设置,会默认html
	header('content-type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
	// mime 协议的扩展
	header('content-disposition:attachment;filename=1.xlsx');
	// 缓存控制
	header('cache-control:max-age=0');

	$writer = \phpoffice\phpspreadsheet\iofactory::createwriter($spreadsheet, 'xlsx');
	// php://output 它是一个只写数据流, 允许你以 print 和 echo一样的方式写入到输出缓冲区。 
	$writer->save('php://output');
?>
2、导入数据
  • 数据库
# 商品分类表
create table `shop_cat` (
	`id` int(10) unsigned not null auto_increment comment 'id',
	`pid` int(10) unsigned default '0' comment '父id',
	`name` varchar(50) default null comment '分类名',
	`status` tinyint(1) unsigned default '1' comment '状态 1开启 0关闭',
	primary key (`id`)
) engine=myisam auto_increment=8 default charset=utf8mb4 comment='分类表';

insert into `shop_cat` values (1, 0, '女装', 1);
insert into `shop_cat` values (2, 0, '男装', 1);
insert into `shop_cat` values (3, 0, '孕产', 1);
insert into `shop_cat` values (4, 1, '连衣裙', 1);
insert into `shop_cat` values (5, 1, '牛仔裤', 1);
insert into `shop_cat` values (6, 2, '衬衫', 1);
insert into `shop_cat` values (7, 3, '睡衣', 1);

# 商品表
create table `shop_list` (
	`id` int(10) unsigned not null auto_increment,
	`cat_id` int(10) unsigned default null comment '分类id',
	`cat_fid` int(10) unsigned default null comment '分类父id',
	`title` varchar(200) not null comment '商品标题',
	`price` double(10,2) unsigned not null comment '价格',
	`img` varchar(200) not null comment '商品图片',
	`add_time` int(10) unsigned not null comment '添加时间',
	primary key (`id`)
) engine=myisam auto_increment=1 default charset=utf8mb4 comment='商品表';
  • index.php 导入页面
<!doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<title>导出数据</title>
		<link rel="stylesheet" href="layui/css/layui.css" rel="external nofollow" rel="external nofollow" >
	</head>
	<body>
		<div style="text-align:center;">
			<button type="button" class="layui-btn" id="up"><i class="layui-icon"></i>上传文件</button>
			<a href="download.php" rel="external nofollow" rel="external nofollow" class="layui-btn layui-btn-danger"><i class="layui-icon"></i>示例下载</a>
		</div>
		<div id="log" style="text-align:center;">
			
		</div>
	</body>
</html>
<script src="layui/layui.js" charset="utf-8"></script>
<script>
	layui.use('upload', function(){
		var $ = layui.jquery
		,upload = layui.upload;
		upload.render({
			elem: '#up'
			,url: 'data.php'
			,accept: 'file' //普通文件
			,done: function(res){
				if(res.code == 0){
					for(var i=0;i<res.data.length;i++){
						$("#log").append('<div>'+res.data[i]+'</div>');
					}
				}
			}
		});
	})
</script>
  • 导入功能
<?php
	$file = $_files['file']['tmp_name'];
	# 载入composer自动加载文件
	require 'vendor/autoload.php';
	# 载入方法库
	require 'function.php';

	# 创建读操作
	$reader = \phpoffice\phpspreadsheet\iofactory::createreader('xlsx');
	# 打开文件、载入excel表格
	$spreadsheet = $reader->load($file);
	# 获取活动工作薄
	$sheet = $spreadsheet->getactivesheet();

	# 获取总列数
	$highestcolumn = $sheet->gethighestcolumn();
	# 获取总行数
	$highestrow = $sheet->gethighestrow();

	# 列数 改为数字显示
	$highestcolumnindex = \phpoffice\phpspreadsheet\cell\coordinate::columnindexfromstring($highestcolumn);
	$log = [];
	for($a=2;$a<$highestrow;$a++){
		$title = $sheet->getcellbycolumnandrow(1,$a)->getvalue();
		$cat_fname = $sheet->getcellbycolumnandrow(2,$a)->getvalue();
		$cat_name = $sheet->getcellbycolumnandrow(3,$a)->getvalue();
		$price = $sheet->getcellbycolumnandrow(4,$a)->getvalue();
		$img = $sheet->getcellbycolumnandrow(5,$a)->getvalue();

		$cat_fid = find('shop_cat','id','name="'.$cat_fname.'"');
		$cat_id = find('shop_cat','id','name="'.$cat_name.'"');
		$data = [
			'title' => $title,
			'cat_fid' => $cat_fid['id'],
			'cat_id' => $cat_id['id'],
			'price' => $price,
			'img' => $img,
			'add_time' => time(),
		];
		$ins = insert('shop_list',$data);
		if($ins){
			$log[] = '第'.$a.'条,插入成功';
		}else{
			$log[] = '第'.$a.'条,插入失败';
		}
	}
	echo json_encode(['code'=>0,'msg'=>'成功','data'=>$log]);
  • 下载示例(范文)
<?php
	# 载入composer自动加载文件
	require 'vendor/autoload.php';
	# 给类文件的命名空间起个别名
	use \phpoffice\phpspreadsheet\spreadsheet;
	# 实例化 spreadsheet 对象
	$spreadsheet = new spreadsheet();
	# 获取活动工作薄
	$sheet = $spreadsheet->getactivesheet();

	$sheet->setcellvalue('a1','商品标题');
	$sheet->setcellvalue('b1','一级分类');
	$sheet->setcellvalue('c1','二级分类');
	$sheet->setcellvalue('d1','进货价');
	$sheet->setcellvalue('e1','图片');

	$data = [
		'云朵般轻盈的仙女裙 高级钉珠收腰长裙 气质无袖连衣裙',
		'女装',
		'连衣裙',
		279.99,
		'https://gd3.alicdn.com/imgextra/i3/266969832/o1cn01pwubbb2mv6ekbktb6_!!266969832.jpg_400x400.jpg',
	];
	$sheet->fromarray(
		$data,
		null,
		'a2'
	);

	// mime 协议,文件的类型,不设置,会默认html
	header('content-type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
	// mime 协议的扩展
	header('content-disposition:attachment;filename=商品列表示例.xlsx');
	// 缓存控制
	header('cache-control:max-age=0');

	$writer = \phpoffice\phpspreadsheet\iofactory::createwriter($spreadsheet, 'xlsx');
	// php://output 它是一个只写数据流, 允许你以 print 和 echo一样的方式写入到输出缓冲区。 
	$writer->save('php://output');