首先需要安装phpexcel依赖:
composer require phpoffice/phpexcel
定义一个上传类:
<?php
namespace app\common\utils;
use app\common\exception\BusinessException;
use app\common\exception\BusinessExceptionEnum;
use Qiniu\Auth;
use think\facade\Config;
use think\facade\Request;
use Qiniu\Storage\UploadManager;
class UploadUtils
{
public static function Excelupload($file,$path)
{
if ($file==null) {
throw new BusinessException(BusinessExceptionEnum::FILE_EMPTY);
}
else{
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
// 判断文件是否合法
if(!in_array($extension, array('xls','xlsx'))){
throw new BusinessException(BusinessExceptionEnum::FILE_WRONG);
}else{
$savename = \think\facade\Filesystem::disk('public')->putFile( $path, $file);
$savename=str_replace('\\', '/', $savename);
$data['sendurl']=app()->getRootPath().'/public/storage/'.$savename;
$data['savename']=$savename;
$data['ext']=$extension;
return $data;
}
}
}
}
Excel工具类:
<?php
namespace app\common\utils;
use app\common\exception\BusinessException;
use app\common\exception\BusinessExceptionEnum;
use PHPExcel_IOFactory;
use think\facade\Filesystem;
class ExcelUtils
{
public static function shibie($excelFile){
$retData=UploadUtils::excelupload($excelFile,'/excel');
$inputFileName=$retData['sendurl'];
$inputFileType=PHPExcel_IOFactory::identify($inputFileName);
if($retData['ext']=='xlsx'){
$objReader=\PHPExcel_IOFactory::createReader('Excel2007');
}else if($retData['ext']=='xls'){
$objReader=\PHPExcel_IOFactory::createReader('Excel5');
}
$objPHPExcel=$objReader->load($inputFileName);
$data['excelArray']=$objPHPExcel->getSheet(0)->toArray();
$data['highestRow']=$objPHPExcel->getSheet(0)->getHighestRow()-1;
unlink($retData['sendurl']);
return $data;
}
public static function makeExcel($data,$filename,$title,$description,$keywords,$category){
//初始化
$filename=str_replace('.xls', '', $filename).'.xls';
$phpexcel = new \PHPExcel();
$phpexcel->getProperties()
->setCreator("CMSSYSTEM")
->setLastModifiedBy("CMSSYSTEM")
->setTitle($title)
->setSubject($title)
->setDescription($description)
->setKeywords($keywords)
->setCategory($category);
$phpexcel->getActiveSheet()->fromArray($data);
$phpexcel->getActiveSheet()->setTitle('Sheet1');
$phpexcel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment;filename=$filename");
header('Cache-Control: max-age=0');
header('Cache-Control: max-age=1');
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
$objwriter = PHPExcel_IOFactory::createWriter($phpexcel, 'Excel5');
$objwriter->save('php://output');
exit;
}
}
识别:
$data=ExcelUtils::shibie(request()->file('file'));//返回数组形式的数据
生成并下载:
$data=[['年龄','性别','姓名'],[12,'女','张三'],[11,'男','李四']];
ExcelUtils::makeExcel($data,'人员','人员','人员列表','人员','OA');
评论