首先安装PhpSpreadsheet
composer require phpoffice/phpspreadsheet
导入导出代码入下:
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx as ReaderXlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;
/**
* 导出excel表
* $data:要导出excel表的数据,接受一个二维数组
* $fileName:excel表的表名
* $title:excel表的表头,接受一个一维数组
* $sheetName:excel表的sheet名 跟版网
*/
function exportExcel($fileName='', $title=[], $data=[],$sheetName=null,$type = null)
{
// $data = array(0 => array(0 => 1, 1 => 'alex1', 2 => 1,),
// 1 => array(0 => 2, 1 => 'alex2', 2 => 2,),
// 2 => array(0 => 3, 1 => 'alex3', 2 => 1,),
// 3 => array(0 => 4, 1 => 'alex4', 2 => 2,),
// 4 => array(0 => 5, 1 => 'alex5', 2 => 1,),
// 5 => array(0 => 6, 1 => 'alex6', 2 => 2,));
//
// $title = ['id', 'name', 'sex'];
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
//设置工作表标题名称
if(isset($sheetName) && !empty($sheetName)){
$sheet->setTitle($sheetName);
}else{
$sheet->setTitle(date('Y-m-d',time()));
}
// $sheet->getDefaultColumnDimension()->setWidth(40);
$iRow=0;
//设置单元格内容
foreach ($title as $key => $value) {
// 单元格内容写入
$sheet->setCellValueByColumnAndRow($key + 1, 1, $value);
$iRow =$iRow +1;
$colum=index2ColName($iRow);
$sheet->getColumnDimension($colum)->setAutoSize(true);
//设置单元格宽度 与setAutoSize 是冲突的
//$sheet->getDefaultColumnDimension()->setWidth(20);
//$sheet->getColumnDimension('B')->setWidth(50);
$sheet->getStyle($colum.'1')->getFont()->setBold(true);
}
$row = 2; // 从第二行开始
foreach ($data as $item) {
$column = 1;
foreach ($item as $value) {
// 单元格内容写入
$sheet->setCellValueByColumnAndRow($column, $row, $value);
$column++;
}
$row++;
}
if(isset($type)){
# 保存为xlsx
$fileName = $fileName.'.Xlsx';
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$filePath = ROOT_PATH.'uploads/excel/'.$fileName;
$writer->save($filePath);
return $filePath;
die;
}else{
# 浏览器下载
$fileName = $fileName.'.Xlsx';
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
ob_end_clean();
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$fileName.'"');
header('Cache-Control: max-age=0');
$writer->save('php://output');
//删除清空
$spreadsheet->disconnectWorksheets();
unset($spreadsheet);
exit;
}
}
//根据列数转Excel的列名;
function index2ColName($columnNumber)
{
$dividend = $columnNumber;
$columnName = '';
while ($dividend > 0) {
$modulo = ($dividend - 1) % 26;
$columnName = chr(65 + $modulo) . $columnName;
$dividend = (int)(($dividend - $modulo) / 26);
}
return $columnName;
}
//导入excel表
function importExcel($file='',$sheetName = 0){
// 有Xls和Xlsx格式两种
$objReader = IOFactory::createReader('Xls');
if (!$objReader->canRead($file)) {
$objReader = IOFactory::createReader('Xlsx');
}
$objPHPExcel = $objReader->load($file); //$filename可以是上传的表格,或者是指定的表格
$sheet = $objPHPExcel->getSheet($sheetName); //excel中的第一张sheet
$highestRow = $sheet->getHighestRow(); // 取得总行数
$highestColumn = $sheet->getHighestColumn(); // 取得总列数
//循环获取表中的数据,$currentRow表示当前行,从哪行开始读取数据,索引值从0开始
for ($currentRow = 1; $currentRow <= $highestRow; $currentRow++) {
//从哪列开始,A表示第一列
for ($currentColumn = 'A'; $currentColumn <= $highestColumn; $currentColumn++) {
//数据坐标
$address = $currentColumn . $currentRow;
//读取到的数据,保存到数组$data中
$cell = $sheet->getCell($address)->getValue();
if ($cell instanceof PHPExcel_RichText) {
$cell = $cell->__toString();
}
$data[$currentRow - 1][$currentColumn] = $cell;
// print_r($cell);
}
}
return $data;
}
/**
* Created by PhpStorm.
* function: imports
* Description:导入excell
*/
function imports()
{
header("Content-Type:text/html;charset = utf-8");
$upload = new \Think\Upload();// 实例化上传类
$upload->maxSize = 3145728;// 设置附件上传大小
$upload->exts = array('xls', 'xlsx');// 设置附件上传类
$upload->rootPath = '../uploads/excel'; // 设置附件上传目录
// 上传文件
$info = $upload->uploadOne($_FILES['excelData']);
$filename = $upload->rootPath . $info['savepath'] . $info['savename'];
$exts = $info['ext'];
if (!$info) {// 上传错误提示错误信息
$this->error($upload->getError());
} else {// 上传成功
$this->data_import($filename, $exts,3);
}
}
//上传excel
function import($request)
{
//解决后缀获取不对的问题
$file = $request->file('excel');
$ext = $file->getClientOriginalExtension();
$fileName = uniqid('', true) . '.' . $ext;
$path = $file->storeAs('excel', $fileName, 'local');
return storage_path('app') . "/" . $path;
}