<?php
namespace YouHuJun\Tool\App\Services\V1\Excel;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx as WriteXlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx as ReadXlsx;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Style;
use YouHuJun\Tool\App\Exceptions\CommonException;
class ExcelFacadeService
{
protected $cloumnLength = 0;
protected $rowLength = 0;
protected $firstCloumn;
protected $lastCloumn;
public $spreadsheet;
public $sheetNumber;
public $sheetName = [];
public $worksheet;
public $rowTotal;
public $cloumnTotal;
protected function getDataCloumnLength($data)
{
$this->cloumnLength = count($data[0]);
return $this->cloumnLength;
}
protected function getDataRowLength($data)
{
$this->rowLength = count($data) + 1;
return $this->rowLength;
}
protected function setCloumWidth($spreadsheet)
{
for($i=1; $i <= $this->cloumnLength; $i++)
{
$cloumn = Coordinate::stringFromColumnIndex($i);
$spreadsheet->getActiveSheet()->getColumnDimension($cloumn)->setAutoSize(true);
$spreadsheet->getActiveSheet()->getStyle($cloumn)->getNumberFormat()->setFormatCode(Style\NumberFormat::FORMAT_TEXT);
}
}
* 设置表格开始和结束列
*
* @param [type] $index 开始列的下标
* @param [type] $data 生成excel表得数据 根据数据长度得出列长度
* @return void
*/
protected function setExcelCloumn($index,$data)
{
$this->getDataCloumnLength($data);
$cloumn = Coordinate::stringFromColumnIndex($this->cloumnLength);
$this->lastCloumn = $cloumn;
$this->firstCloumn = Coordinate::stringFromColumnIndex($index);
}
* 导出excel表格数据
*
* @param array $cloumn [
['一年级','二年级','三年级']
];
* @param array $data [
[10,20,30],
[10,null,30],
[10,20,30],
];
* @param string $title "test"
* @param string $savePath 保存路径
* @return void
*/
public function exportExcelData(array $column = [[]], array $data = [], string $title = 'test', ?string $savePath = null)
{
if (empty($column[0]) || empty($data)) {
throw new CommonException('ExcelExportError');
}
$spreadsheet = new Spreadsheet();
$spreadsheet->setActiveSheetIndex(0);
$this->setExcelCloumn(1,$data);
$spreadsheet->getActiveSheet()->mergeCells($this->firstCloumn.'1:'. $this->lastCloumn.'1');
$styleArrayTitle = [
'font' => [ 'bold' => true, 'size' => 22 ],
'alignment' => [
'horizontal' => Style\Alignment::HORIZONTAL_CENTER,
],
'borders' => [
'diagonalDirection' => Style\Borders::DIAGONAL_BOTH,
'allBorders' => [
'borderStyle' => Style\Border::BORDER_THIN,
],
],
'fill' => [
'fillType' => Style\Fill::FILL_GRADIENT_LINEAR,
'rotation' => 90,
'startColor' => [
'argb' => 'FACC2E',
],
'endColor' => [
'argb' => 'FFFFFFFF',
],
],
];
$styleArrayCloumn = [
'font' => [ 'bold' => true, 'size' => 14 ],
'alignment' => [
'horizontal' => Style\Alignment::HORIZONTAL_CENTER,
],
'borders' => [
'top' => [
'borderStyle' => Style\Border::BORDER_THIN,
],
],
'fill' => [
'fillType' => Style\Fill::FILL_GRADIENT_LINEAR,
'rotation' => 90,
'startColor' => [
'argb' => '2ECCFA',
],
'endColor' => [
'argb' => 'FFFFFFFF',
],
],
];
$spreadsheet->getActiveSheet()->getStyle('A1')->applyFromArray($styleArrayTitle);
$spreadsheet->getActiveSheet()->getStyle( $this->firstCloumn.'2:'.$this->lastCloumn.'2')->applyFromArray($styleArrayCloumn);
$spreadsheet->getActiveSheet()->getCell('A1')->setValue($title);
$spreadsheet->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
$spreadsheet->getActiveSheet()->getRowDimension('2')->setRowHeight(20);
$this->setCloumWidth($spreadsheet);
$allData = \array_merge((array)$column, (array)$data);
$spreadsheet->getActiveSheet()->fromArray($allData,null,'A2');
->setCreator("王琛晔") //作者
->setLastModifiedBy("游鹄君") //最后修改者
->setTitle("测试表") //标题
->setSubject("小测试表") //副标题
->setDescription("哈哈哈哈") //描述
->setKeywords("噗噗") //关键字
->setCategory("1级"); //分类 */
$writer = new WriteXlsx($spreadsheet);
if($savePath)
{
$dir = dirname($savePath);
if (!is_dir($dir)) {
mkdir($dir, 0777, true);
}
$finalFilePath = rtrim($savePath, '/\\') . DIRECTORY_SEPARATOR . $title . '.xlsx';
$writer->save($finalFilePath);
}
else
{
ob_end_clean();
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header("Content-Disposition: attachment;filename={$title}.xlsx");
header('Cache-Control: max-age=0');
$writer->save('php://output');
exit;
}
}
public function testExcel()
{
['一年级','二年级','三年级']
];
$data = [
[10,20,30],
[10,null,30],
[10,20,30],
];
$title = "test";
$this->exportExcelData($cloumn, $data,$title,1); */
}
* Undocumented 读取表格初始化
*
* @param [type] $fileUrl 文件地址
* @return 表格对象
*/
public function initReadExcel($fileUrl)
{
set_time_limit(0);
ini_set("memory_limit",-1);
$reader = IOFactory::createReaderForFile($fileUrl);
$this->spreadsheet = $reader->load( $fileUrl);
$this->getExcelNumberName();
}
* Undocumented 获取工作表的数量和每个工作表的名称
*
* @param [type] $spreadsheet
* @return void
*/
protected function getExcelNumberName()
{
$this->sheetNumber = $this->spreadsheet ->getSheetCount();
$this->sheetName = $this->spreadsheet ->getSheetNames();
}
* Undocumented function 获取单张工作表的所有行数和列数
*
* @param [type] $worksheet
* @return void
*/
public function getRowColumnNumber()
{
$this->rowTotal = $this->worksheet->getHighestRow();
$colsString = $this->worksheet->getHighestColumn();
$this->cloumnTotal = Coordinate::columnIndexFromString($colsString);
}
* 设置当前工作表
*
* @param integer $index
* @return void
*/
public function setWorkSheet($index = null)
{
if(empty($index) || !is_numeric($index))
{
$index = 0;
}
$this->spreadsheet->setActiveSheetIndex((int)$index);
$this->worksheet = $this->spreadsheet->getActiveSheet();
$this->getRowColumnNumber();
}
* 获取当前工作表
*
* @param [type] $index
* @return void
*/
public function getWorkSheet($key = null)
{
if(empty($key))
{
$key = 0;
}
else
{
$key = func_get_arg(0);
}
if(\is_string($key) && \in_array($key,$this->sheetName))
{
$this->worksheet = $this->spreadsheet->getSheetByName($key);
}
else
{
if(\is_int($key))
{
$this->worksheet = $this->spreadsheet->getSheet($key);
}
}
$this->getRowColumnNumber();
}
* Undocumented function 获取一行的数据 (这一行的所有列)
*
* @param [type] $worksheet
* @return void
*/
public function getRowData($rowIndex = 1)
{
$data = [];
if(!empty($rowIndex) && \is_int($rowIndex) && $rowIndex > 0)
{
for ($i=1; $i <=$this->cloumnTotal ; $i++)
{
$value = $this->worksheet->getCell([$i, $rowIndex])->getFormattedValue();
$data[] = $value;
}
}
return $data;
}
* Undocumented function 获取一列的数据 (这一列所有的行)
*
* @param [type] $worksheet
* @param [type] $column
* @return void
*/
public function getColumnData($columnIndex)
{
$data = [];
if(!empty($columnIndex) && \is_int($columnIndex) && $columnIndex > 0)
{
for ($i=1; $i <= $this->rowTotal ; $i++)
{
$value = $this->worksheet->getCell([$columnIndex, $i])->getFormattedValue();
$data[] = $value;
}
}
return $data;
}
* Undocumented 通过表名按照行来获取一张表的数据
*
* @param [object] $worksheet 工作表队像
* @return [array] $row 返回列和行组成的二位数组
*/
public function getDataByRow()
{
$row = [];
for ($i=1; $i <= $this->rowTotal; $i++)
{
$col = [];
for ($j=1; $j <= $this->cloumnTotal; $j++)
{
$value = $this->worksheet->getCell([$j, $i])->getFormattedValue();
if(!empty($value))
{
$col[$j-1] = $value;
}
}
if(count($col)>0)
{
$row[$i-1] = $col;
}
}
unset($this->worksheet);
ob_flush();
flush();
return $row;
}
* Undocumented 通过表名按照列来获取一张表的数据
*
* @param [object] $worksheet 工作表队像
* @return [array] $rol 返回行和列组成的二位数组
*/
public function getDataByColumn()
{
$col = [];
for ($i=1; $i <= $this->cloumnTotal; $i++)
{
$row = [];
for ($j=1; $j <= $this->rowTotal; $j++)
{
$value = $this->worksheet->getCell([$i, $j])->getFormattedValue();
if(!empty($value))
{
$row[$j-1] = $value;
}
}
if(count($row)>0)
{
$col[$i-1] = $row;
}
}
unset($this->worksheet);
ob_flush();
flush();
return $col;
}
}