ExcelExporter.php
3.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?php
/**
* +-----------------------------------------------------------------------------------------------------------------------
* 扩展类:通用导出扩展类
* +-----------------------------------------------------------------------------------------------------------------------
*
* PHP version 7
*
* @category App\Admin\Extensions
* @package App\Admin\Extensions
* @author Richer <yangzi1028@163.com>
* @date 2021年8月30日10:57:09
* @copyright 2020-2022 Richer (http://www.Richer.com/)
* @license http://www.Richer.com/ License
* @link http://www.Richer.com/
*/
namespace App\Admin\Extensions;
use Encore\Admin\Grid\Exporters\AbstractExporter;
use Illuminate\Support\Arr;
use Maatwebsite\Excel\Facades\Excel;
use PHPExcel_Worksheet_Drawing;
/**
* Class CustomExporter
*
* @category App\Admin\Extensions
* @package App\Admin\Extensions
* @author Richer <yangzi1028@163.com>
* @date 2021年8月30日10:57:09
* @copyright 2020-2022 Richer (http://www.Richer.com/)
* @license http://www.Richer.com/ License
* @link http://www.Richer.com/
*/
class ExcelExporter extends AbstractExporter
{
protected $head = [];
protected $body = [];
public function setAttr($head, $body)
{
$this->head = $head;
$this->body = $body;
}
public function export()
{
//定义文件名称为日期拼上uniqid()
$fileName = date('YmdHis') . '-' . uniqid();
Excel::create($fileName, function ($excel) {
$excel->sheet('sheet1', function ($sheet) {
// 这段逻辑是从表格数据中取出需要导出的字段
$head = $this->head;
$body = $this->body;
//init列
$title_array = ['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'];
$rows = collect([$head]); //写入标题
$sheet->rows($rows);
collect($this->getData())->map(function ($item, $k) use ($body, $sheet, $title_array) {
foreach ($body as $i => $keyName) {
if ($keyName == 'url') { //判断图片列,如果是则放图片
// $objDrawing = new PHPExcel_Worksheet_Drawing;
// $v = public_path('/upload/'). Arr::get($item, $keyName); //拼接图片地址
// $objDrawing->setPath($v);
// $sp = $title_array[$i];
// $objDrawing->setCoordinates($sp . ($k+2));
// $sheet->setHeight($k+2, 65); //设置高度
// $sheet->setWidth(array( $sp =>12)); //设置宽度
// $objDrawing->setHeight(80);
// $objDrawing->setOffsetX(1);
// $objDrawing->setRotation(1);
// $objDrawing->setWorksheet($sheet);
} else { //否则放置文字数据
$v = Arr::get($item, $keyName);
$sheet->cell($title_array[$i] . ($k+2), function ($cell) use ($v) {
$cell->setValue($v);
});
}
}
});
});
})->export('xls');
}
}