tp6安装、封装phpspreadsheet,表格excel导入导出
发布时间:2022-07-26, 09:33:33 分类:PHP | 编辑 off 网址 | 辅助
正文 7375字数 277,747阅读
1、安装phpspreadsheet
composer require phpoffice/phpspreadsheet
Run code
Cut to clipboard
2、封装类
<?php
namespace excel;
use PHPExcel_IOFactory;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Fill;
class Excel
{
// public function test()
// {
// $data = [
// ['title1' => '111', 'title2' => '111'],
// ['title1' => '222', 'title2' => '222'],
// ['title1' => '333', 'title2' => '333']
// ];
// $mergeCells = [
// ['A1:B1'=>'第一行标题','C1:F1'=>'第一111行标题'],
// ['A2:B2'=>'第一行标题','C2:E2'=>'第一222行标题'],
// ];
// $tableHeader = [
// ['第一行标题','第一行标题'],
// ['第二行标题', '第二行标题']
// ];
// $fileName = "8888.xlsx";
//
// $data = Excel::saveFile($data, $fileName, $tableHeader,$mergeCells);
//
// var_dump($data);
// exit;
// }
public static $excelCol = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ'];
public static $setBold = false;
public static $setName = '宋体';
public static $setSize = '12';
public static $setBgRGB = 'FFFFFFFF';
public static $setFontRGB = 'FF000000';
public static $styleArray = [
'alignment' => [
'horizontal' => Alignment::HORIZONTAL_CENTER,
'vertical' => Alignment::VERTICAL_CENTER
],
'borders' => [
'allBorders' => [
'borderStyle' => Border::BORDER_THIN,
'color' => ['argb' => '000000'],
],
],
];
/**
* 读取excel
* @param $filePath
* @param int $pageIndex
* @param int $readRow
* @return array
* @throws \PhpOffice\PhpSpreadsheet\Exception
*/
public static function read($filePath, $pageIndex = 0,$readRow = 0)
{
//加载文件
$spreadSheet = IOFactory::load($filePath);
//获取文件内容
$workSheet = $spreadSheet->getSheet($pageIndex)->toArray('', true, true, false);
//删除表头几行
if ($readRow > 0) {
for ($i = 0; $i < $readRow; $i++) {
array_shift($workSheet);
}
}
return $workSheet;
}
/**
* 下载文件
* @param $data
* @param $fileName
* @param array $tableHeader
* @param array $mergeCells
* @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
*/
public static function download($data, $fileName, $tableHeader = [], $mergeCells = [], $suffix = 'xlsx')
{
$spreadsheet = self::write($data, $tableHeader, $mergeCells);
// 将输出重定向到客户端的网络浏览器(Xlsx)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $fileName . '"');//文件名
header('Cache-Control: max-age=0');
// 如果你服务于IE 9,那么以下可能是需要的
header('Cache-Control: max-age=1');
// 如果您通过SSL为工业工程服务,那么可能需要以下内容
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, ucwords($suffix));
$writer->save('php://output');
}
/**
* 保存文件
* @param $data
* @param $fileName
* @param array $tableHeader
* @param array $mergeCells
* @throws \PhpOffice\PhpSpreadsheet\Exception
* @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
*/
public static function saveFile($data, $fileName, $tableHeader = [], $mergeCells = [], $suffix = 'xlsx')
{
$spreadsheet = self::write($data, $tableHeader, $mergeCells);
$writer = IOFactory::createWriter($spreadsheet, ucwords($suffix));
$writer->save($fileName, true);
exit;
}
/**
* 写入数据
* @param $data
* @param $tableHeader
* @param $mergeCells
* @return Spreadsheet
* @throws \PhpOffice\PhpSpreadsheet\Exception
*/
public static function write($data, $tableHeader, $mergeCells)
{
// 创建excel对象
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$totalCol = 0;
//设置表头合并单元格
foreach ($mergeCells as $row => $rows) {
$i = 0;
foreach ($rows as $col => $colValue) {
//合并单元格
$sheet->mergeCells($col);
//设置样式
self::setStyle($sheet, $i, $totalCol, $row);
//单元格内容写入
$sheet->setCellValue(substr($col, 0, strpos($col, ":")), $colValue);
$i++;
}
}
$totalCol = count($mergeCells);
//设置表头
foreach ($tableHeader as $row => $rows) {
$headerRowDatas = array_values($rows);
foreach ($headerRowDatas as $col => $colValue) {
//设置样式
self::setStyle($sheet, $col, $totalCol, $row);
//单元格内容写入
$sheet->setCellValue(self::$excelCol[$col] . ($totalCol + $row + 1), $colValue);
}
}
$totalCol += count($tableHeader);
//设置内容
foreach ($data as $row => $rows) {
$rowDatas = array_values($rows);
foreach ($rowDatas as $col => $colValue) {
// 单元格内容写入
$sheet->setCellValue(self::$excelCol[$col] . ($totalCol + $row + 1), $colValue);
}
}
return $spreadsheet;
}
/**
* 设置单元格样式
* @param $sheet
* @param $col
* @param $totalCol
* @param $row
*/
public static function setStyle($sheet, $col, $totalCol, $row)
{
//设置单元格居中
$sheet->getStyle(self::$excelCol[$col] . ($totalCol + $row + 1))->applyFromArray(self::$styleArray);
//设置单元格
$sheet->getStyle(self::$excelCol[$col] . ($totalCol + $row + 1))
->getFill()
->setFillType(Fill::FILL_SOLID)
->getStartColor()
->setRGB(self::$setBgRGB);
//设置单元格字体样式、字体、字体大小
$sheet->getStyle(self::$excelCol[$col] . ($totalCol + $row + 1))
->getFont()
->setBold(self::$setBold)
->setName(self::$setName)
->setSize(self::$setSize);
//设置字体颜色
$sheet->getStyle(self::$excelCol[$col] . ($totalCol + $row + 1))
->getFont()
->getColor()->setRGB(self::$setFontRGB);
}
}
Run code
Cut to clipboard
(支付宝)给作者钱财以资鼓励 (微信)→
有过 1 条评论 »
<?php declare (strict_types = 1); namespace app\union\controller; use app\Request; use app\union\model\Groups; use think\facade\Cookie; use think\facade\Db; use think\facade\View; use PHPExcel_IOFactory; //通过composer加载的第三方类,直接在头部引入一下就可以 class Group extends Base { public function import_save(Request $request){ if(!$request->param('excel')){ return returnJson('500','请上传excel文件'); } $path = public_path().$request->param('excel'); //实例化PHPExcel类 $PHPExcel = new \PHPExcel(); //默认用excel2007读取excel,若格式不对,则用之前的版本进行读取 $PHPReader = new \PHPExcel_Reader_Excel2007(); if (!$PHPReader->canRead($path)) { $PHPReader = new \PHPExcel_Reader_Excel5(); if (!$PHPReader->canRead($path)) { return returnJson('500','请上传excel文件'); } } //读取Excel文件 $PHPExcel = $PHPReader->load($path); //读取excel文件中的第一个工作表 $sheet = $PHPExcel->getSheet(0); //取得最大的列号 $allColumn = $sheet->getHighestColumn(); //取得最大的行号 $allRow = $sheet->getHighestRow(); //从第二行开始插入,第一行是列名 for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) { //获取B列的值 $data = [ 'number'=>$PHPExcel->getActiveSheet()->getCell("A" . $currentRow)->getValue(), 'nickName'=>$PHPExcel->getActiveSheet()->getCell("B" . $currentRow)->getValue(), 'name'=>$PHPExcel->getActiveSheet()->getCell("C" . $currentRow)->getValue(), 'tel'=>$PHPExcel->getActiveSheet()->getCell("D" . $currentRow)->getValue(), 'money'=>$PHPExcel->getActiveSheet()->getCell("E" . $currentRow)->getValue(), 'time'=>self::get_date_by_excel($PHPExcel->getActiveSheet()->getCell("F" . $currentRow)->getValue()), 'is_pay'=>$PHPExcel->getActiveSheet()->getCell("G" . $currentRow)->getValue(), 'shop_name'=>$PHPExcel->getActiveSheet()->getCell("H" . $currentRow)->getValue(), 'remarks'=>$PHPExcel->getActiveSheet()->getCell("I" . $currentRow)->getValue(), 'status'=>0, 'created_at'=>date('Y-m-d') ]; if($data['number'] == ''){ $result = 1; continue; }else{ $find = Groups::where(array('number'=>$data['number']))->find(); if($find){ $result = 1; continue; }else{ $result=Db::name('group')->insert($data); } } } if($result){ return returnJson('200','导入成功'); }else{ return returnJson('500','导入失败'); } } public static function get_date_by_excel($date){ if (!$date || $date == '0000-00-00') return null; $unix_time = \PHPExcel_Shared_Date::ExcelToPHP($date); return gmdate('Y-m-d H:i',$unix_time); } } ?>