maatwebsite/excel使用:导出——插图

插图#

通过使用 WithDrawings ,你可以向工作表中添加一个或多个插图。

创建插图实例#

首先,你需要实例化一个新的 \PhpOffice\PhpSpreadsheet\Worksheet\Drawing,并为其属性分配有意义的值。

$drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
$drawing->setName('Logo');
$drawing->setDescription('这是我的标志');
$drawing->setPath(public_path('/img/logo.jpg'));
$drawing->setHeight(90);

你可以在 PhpSpreadsheet 文档 中查看 Drawing 的所有可用属性。

添加单个插图#

当你实例化了插图后,可以在导出类中添加 WithDrawings ,并在 drawings 方法中返回插图实例。

<?php

namespace App\Exports;

use Maatwebsite\Excel\Concerns\WithDrawings;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;

class InvoicesExport implements WithDrawings
{
    public function drawings()
    {
        $drawing = new Drawing();
        $drawing->setName('Logo');
        $drawing->setDescription('这是我的标志');
        $drawing->setPath(public_path('/img/logo.jpg'));
        $drawing->setHeight(90);
        $drawing->setCoordinates('B3');

        return $drawing;
    }
}

添加多个插图#

你可以通过在 drawings 方法中返回一个数组来向工作表中添加多个插图。

<?php

namespace App\Exports;

use Maatwebsite\Excel\Concerns\WithDrawings;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;

class InvoicesExport implements WithDrawings
{
    public function drawings()
    {
        $drawing = new Drawing();
        $drawing->setName('Logo');
        $drawing->setDescription('这是我的标志');
        $drawing->setPath(public_path('/img/logo.jpg'));
        $drawing->setHeight(50);
        $drawing->setCoordinates('B3');

        $drawing2 = new Drawing();
        $drawing2->setName('其他图片');
        $drawing2->setDescription('这是第二张图片');
        $drawing2->setPath(public_path('/img/other.jpg'));
        $drawing2->setHeight(120);
        $drawing2->setCoordinates('G2');

        return [$drawing, $drawing2];
    }
}

添加远程图片的插图#

你可以通过实例化一个新的 \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing,并从外部 URL 获取二进制图像数据,然后将其赋值给 setImageResource。在 drawings 方法中返回插图实例。

<?php

namespace App\Exports;

use Maatwebsite\Excel\Concerns\WithDrawings;
use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing;

class InvoicesExport implements WithDrawings
{
    public function drawings()
    {
        if (!$imageResource = @imagecreatefromstring(file_get_contents('http://example.jpg'))) {
            throw new \Exception('无法将图片 URL 转换为图像资源。');
        }

        $drawing = new MemoryDrawing();
        $drawing->setName('Logo');
        $drawing->setDescription('这是我的标志');
        $drawing->setImageResource($imageResource);
        $drawing->setHeight(90);
        $drawing->setCoordinates('B3');

        return $drawing;
    }
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。