公司后台网站怎么做/口碑营销公司
PHP程序媛 2019-11-28 17:54:23

今天,给大家分享一下,如何在laravel框架中,实现导出Excel功能。同时,在导出的Excel中把链接地址转化成图片。
需要用到的工具及扩展
- laravel版本为5.5,可到官网根据自己的需要下载相应版本
- PHP7及以上
- excel扩展用的是 maatwebsite/excel,版本为2.1及以上
- 安装后的laravel框架目录如下图所示:

laravel框架目录结构
核心代码laravel excel有三种导出方式:Exportables、From Query、From View,我这里用的是From View1.创建导出类 app/Exports,可以通过使用make:export命令来执行此操作。如下:
php artisan make:export OrderExport --model=User
生成都目录结构如下:
.
├── app
│ ├── Exports
│ │ ├── OrderExport.php
│
└── composer.json2.OrderExport.php文件中的代码如下:
<?php
namespace AppExports;
use MaatwebsiteExcelConcernsFromView;
use IlluminateContractsViewView;
class OrderExport implements FromView
{
protected $imgPosition = [];//图片插入位置
public function __construct(array $data)
{
$this->data = $data;//要导出的数据
}
public function view(): View
{
return view('export', ['data' => $this->data]); //export为导出视图模板
}
}

3.上面代码中,导出视图模板export的文件为 export.blade.php,具体位置如下:
.
├── resources
│ ├── views
│ │ ├── export.blade.php
│
└── composer.json
该模板定义了导出excel的格式,具体代码如下:
<table>
<thead>
</thead>
<tbody>
<tr>
<?php foreach ($data['header'] as $key => $val) { ?>
<td style="vertical-align: center;"><b>{{$val}}</b></td>
<?php } ?>
</tr>
<?php foreach ($data['rows'] as $key => $val) { ?>
<tr>
<?php foreach ($val as $k => $v) { ?>
<?php if (is_array($v)) {?>
{{--@foreach($v as $i => $img)
<td style="vertical-align: center;"><b>{{$img}}</b></td>
@endforeach--}}
<?php } else { ?>
<td style="vertical-align: center;"><b>{{$v}}</b></td>
<?php } ?>
<?php } ?>
</tr>
<?php } ?>
</tbody>
</table>4.好啦,接下来就可以直接在controller中导出文件到excel了。
public function export($data)
{
$orderExport = new OrderExport($data);//$data为需要导出到excel中的数据
return Excel::download($orderExport, 'test.xlsx');
}
以上就是导出excel的全部过程啦!下面我们来讲一讲如何把图片链接地址转换成图片并导出到excel中。

链接地址转换成图片
导出的数据格式需要在 app/Exports/OrderExport.php 文件中设置1.通过使用 WithDrawings 添加图片到excel中,实例化工程图(Drawing),并设置相应的值:
$drawing = new PhpOfficePhpSpreadsheetWorksheetDrawing();
$drawing->setName('Logo');//图片名称
$drawing->setDescription('This is my logo');//图片描述
$drawing->setPath(public_path('/img/logo.jpg'));//图片路径
$drawing->setHeight(90);//图片高度2.实例化之后,需要添加到导出类中,添加一个图纸:
<?php
namespace AppExports;
use MaatwebsiteExcelConcernsFromView;
use IlluminateContractsViewView;
use MaatwebsiteExcelConcernsWithDrawings;
class OrderExport implements FromView, WithDrawings
{
public function __construct(array $data)
{
$this->data = $data;//要导出的数据
}
public function view(): View
{
return view('export', ['data' => $this->data]); //export为导出视图模板
}
public function drawings()
{
$drawing = new Drawing();
$drawing->setName('Logo');
$drawing->setDescription('This is my logo');
$drawing->setPath(public_path('/img/logo.jpg'));
$drawing->setHeight(90);
$drawing->setCoordinates('B3');//图片位于excel中的单元格位置
return $drawing;
}
}
如果想要导出多张图片,只需在 drawings()方法中,实例化多个工程图类并设置相应参数即可。导出结果如下图:

除了以上介绍的功能,还有许多其他设置excel的方法,如导出不同格式文件、格式化列、自定义格式值、单元格颜色、字体大小、位置都可以设置。
laravel框架中,导出数据到excel,并且把链接地址转换成图片的功能,已经完整的介绍完啦。是不是感觉很简单,功能很强大,动手试一试吧!