Laravel-excel: Como inserir hiperlink clicĂĄvel no excel?

Criado em 8 set. 2016  Â·  16ComentĂĄrios  Â·  Fonte: Maatwebsite/Laravel-Excel

Tentei inserir hiperlink na planilha, mas estĂĄ apenas no formato de texto. Como posso inserir um hiperlink clicĂĄvel?

ComentĂĄrios muito Ășteis

quando usar v3.*, vocĂȘ pode gostar disso para definir o hiperlink.

<?php
namespace App\Exports;

use Excel;
use Maatwebsite\Excel\Sheet;
use Maatwebsite\Excel\Events\AfterSheet;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use PhpOffice\PhpSpreadsheet\Cell\Hyperlink;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class CommentsExport implements FromCollection, WithHeadings, WithMapping, ShouldAutoSize
{
    // ...
    public function custom()
    {
        Excel::extend(static::class, function (CommentsExport $export, Sheet $sheet) {
            /** <strong i="7">@var</strong> Worksheet $sheet */
            foreach ($sheet->getColumnIterator('H') as $row) {
                foreach ($row->getCellIterator() as $cell) {
                    if (str_contains($cell->getValue(), '://')) {
                        $cell->setHyperlink(new Hyperlink($cell->getValue(), 'ç‚čć‡»æŸ„çœ‹ć›Ÿç‰‡'));
                    }
                }
            }
        }, AfterSheet::class);
    }
    // ...
}

(new CommentsExport)->custom()); Excel::download(CommentsExport::class);

Solução Ăștil, mas vocĂȘ pode fazer isso de forma mais compreensĂ­vel com refatoração

<?php
namespace App\Exports;

use Excel;
use Maatwebsite\Excel\Sheet;

// add event support
use Maatwebsite\Excel\Concerns\WithEvents;

use Maatwebsite\Excel\Events\AfterSheet;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use PhpOffice\PhpSpreadsheet\Cell\Hyperlink;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class CommentsExport implements FromCollection, WithHeadings, WithMapping, ShouldAutoSize, WithEvents
{
    // ...
    /**
     * <strong i="13">@return</strong> array
     */
    public function registerEvents(): array
    {
        return [
            AfterSheet::class    => function(AfterSheet $event) {
                /** <strong i="14">@var</strong> Worksheet $sheet */
                foreach ($event->sheet->getColumnIterator('H') as $row) {
                    foreach ($row->getCellIterator() as $cell) {
                        if (str_contains($cell->getValue(), '://')) {
                            $cell->setHyperlink(new Hyperlink($cell->getValue(), 'Read'));

                             // Upd: Link styling added
                             $event->sheet->getStyle($cell->getCoordinate())->applyFromArray([
                                'font' => [
                                    'color' => ['rgb' => '0000FF'],
                                    'underline' => 'single'
                                ]
                            ]);
                        }
                    }
                }
            },
        ];
    }
    // ...
}

Uso, apenas:

Excel::download(CommentsExport::class);

Todos 16 comentĂĄrios

Mostre-nos como vocĂȘ tentou por favor e nos dĂȘ o modelo de problema do github como fornecido automaticamente.

   `$candidate; //Collection object from model
    foreach ($candidates as $key => $model) {
        if($model->grade == 'Z') {
            $model->grade="Reject";
        }
        $model->access_token=url('static-access/'.$model->access_token);`

Estou apenas substituindo o access_token pelo URL completo. Em seguida, convertendo o objeto de coleção em array como abaixo,

    `foreach ($candidates as $candidate) {
        $candidatesArray[] = $candidate->toArray();
    }`

Em seguida, criando a planilha da matriz como abaixo,

   `$sheet=$excel->sheet('sheet1', function($sheet) use ($candidatesArray,$jd) {
            $sheet->fromArray($candidatesArray, null, 'A1', false, false);
    });`

a partir desse script, ele exporta dados conforme necessĂĄrio, mas o hiperlink Ă© exportado como formato de texto e nĂŁo como link clicĂĄvel. @patrickbrouwers

Eu acho que vocĂȘ tem que fazer assim com os mĂ©todos nativos do PHPExcel:

$sheet->getCell('E26')
    ->getHyperlink()
    ->setUrl('http://examle.com/uploads/cv/' . $cellValue)
    ->setTooltip('Click here to access file');

https://github.com/PHPOffice/PHPExcel/blob/develop/Documentation/markdown/Overview/08-Recipes.md#change -a-cell-into-a-clickable-url

Obrigado @patrickbrouwers , mas setTooltip não estå funcionando (célula vazia).
Pelo menos para a versĂŁo "maatwebsite/excel": "~2.1.0" .

Estou usando setValue para mostrar algo como um texto.

Além disso, meu texto é um ID e foi interpretado como um campo numérico (com notação E). Para corrigir estou usando:

->setValueExplicit($fbId, PHPExcel_Cell_DataType::TYPE_STRING)

setTooltip Ă© o texto que Ă© mostrado se vocĂȘ passar o mouse sobre a cĂ©lula. VocĂȘ realmente precisa fazer setValue ou setValueExplicit antes de usar isso.

Passei muito tempo tentando descobrir por que os links nĂŁo estavam sendo gerados no meu arquivo do Excel. Acontece que $sheet->cell("A1") e $sheet->getCell("A1") nĂŁo sĂŁo a mesma coisa. Eu tive muitos casos em que eu estava fazendo algo como o seguinte:

$sheet->cell($cellLetter.$rowIndex, $url)
->getHyperlink()
->setUrl($url);

O que não estava funcionando, mas também não estava gerando nenhum erro, como Method [...] doesn't exist for ... . Mudando meu código para:

$sheet->getCell($cellLetter.$rowIndex) // A1, B2
->setValueExplicit("Click Here", \PHPExcel_Cell_DataType::TYPE_STRING);

$sheet->getStyle($cellLetter.$rowIndex)
->applyFromArray($urlStyle); // Blue, Bold

$sheet->getCell($cellLetter.$rowIndex)
->getHyperlink()
->setUrl($url);

Resolveu meu problema. Pode ajudar alguém no futuro com o mesmo problema.

resolver meu problema, este meu cĂłdigo

$sheet->getCell($cell) ->getHyperlink() ->setUrl($url); $sheet->getStyle($cell) ->applyFromArray(array( 'font' => array( 'color' => ['rgb' => '0000FF'], 'underline' => 'single' ) ));

screen shot 2017-07-19 at 2 47 40 pm

obrigado mano @TimothyDLewis

@TimothyDLewis ou @herarya posso incomodĂĄ-lo por como vocĂȘ estĂĄ iterando na planilha? - talvez apenas poste um pouco mais de cĂłdigo sobre o mĂ©todo completo que vocĂȘ usou? (ou seja, recebendo $cellLetter.$rowIndex ou $cell ?)

Estou exportando uma matriz simples que possui 5 colunas de um banco de dados, - esta é uma planilha e possui uma linha de cabeçalho. Depois de pegå-lo, tenho este código que funciona, é claro:

//$trademark = [an array of data with 5 columns and a header row];
Excel::create('trademarks', function($excel) use($trademarks) {
  $excel->sheet('trademarks', function($sheet) use($trademarks) {
     $sheet->fromArray($trademarks,null,'A1',false,false);
     //need to iterate over $sheet, get each row, and find column 1 in that row and set a URL
})->export('xlsx');

Gostaria de iterar em $sheet e alterar uma célula em cada linha (diferente da primeira linha) com um URL. Eu tentei até 3 loops foreach profundos (eu continuo recebendo um erro de que o resultado é um objeto, uma matriz ou recebo "PHPExcel_Exception Coordenada de célula invålida CREATOR in Cell.php (linha 590)", e tentei $sheet- >each (que aparentemente é um método disponível apenas no carregamento em um arquivo, pois é um erro não haver método each).

setUrl("sheet://'test'!A1")
mas o link do arquivo Ă© sheet://test!A1
Por quĂȘ?

quando usar v3.*, vocĂȘ pode gostar disso para definir o hiperlink.

<?php
namespace App\Exports;

use Excel;
use Maatwebsite\Excel\Sheet;
use Maatwebsite\Excel\Events\AfterSheet;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use PhpOffice\PhpSpreadsheet\Cell\Hyperlink;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class CommentsExport implements FromCollection, WithHeadings, WithMapping, ShouldAutoSize
{
    // ...
    public function custom()
    {
        Excel::extend(static::class, function (CommentsExport $export, Sheet $sheet) {
            /** <strong i="6">@var</strong> Worksheet $sheet */
            foreach ($sheet->getColumnIterator('H') as $row) {
                foreach ($row->getCellIterator() as $cell) {
                    if (str_contains($cell->getValue(), '://')) {
                        $cell->setHyperlink(new Hyperlink($cell->getValue(), 'ç‚čć‡»æŸ„çœ‹ć›Ÿç‰‡'));
                    }
                }
            }
        }, AfterSheet::class);
    }
    // ...
}
(new CommentsExport)->custom());
Excel::download(CommentsExport::class);

quando usar v3.*, vocĂȘ pode gostar disso para definir o hiperlink.

<?php
namespace App\Exports;

use Excel;
use Maatwebsite\Excel\Sheet;
use Maatwebsite\Excel\Events\AfterSheet;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use PhpOffice\PhpSpreadsheet\Cell\Hyperlink;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class CommentsExport implements FromCollection, WithHeadings, WithMapping, ShouldAutoSize
{
    // ...
    public function custom()
    {
        Excel::extend(static::class, function (CommentsExport $export, Sheet $sheet) {
            /** <strong i="7">@var</strong> Worksheet $sheet */
            foreach ($sheet->getColumnIterator('H') as $row) {
                foreach ($row->getCellIterator() as $cell) {
                    if (str_contains($cell->getValue(), '://')) {
                        $cell->setHyperlink(new Hyperlink($cell->getValue(), 'ç‚čć‡»æŸ„çœ‹ć›Ÿç‰‡'));
                    }
                }
            }
        }, AfterSheet::class);
    }
    // ...
}

(new CommentsExport)->custom()); Excel::download(CommentsExport::class);

Solução Ăștil, mas vocĂȘ pode fazer isso de forma mais compreensĂ­vel com refatoração

<?php
namespace App\Exports;

use Excel;
use Maatwebsite\Excel\Sheet;

// add event support
use Maatwebsite\Excel\Concerns\WithEvents;

use Maatwebsite\Excel\Events\AfterSheet;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use PhpOffice\PhpSpreadsheet\Cell\Hyperlink;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class CommentsExport implements FromCollection, WithHeadings, WithMapping, ShouldAutoSize, WithEvents
{
    // ...
    /**
     * <strong i="13">@return</strong> array
     */
    public function registerEvents(): array
    {
        return [
            AfterSheet::class    => function(AfterSheet $event) {
                /** <strong i="14">@var</strong> Worksheet $sheet */
                foreach ($event->sheet->getColumnIterator('H') as $row) {
                    foreach ($row->getCellIterator() as $cell) {
                        if (str_contains($cell->getValue(), '://')) {
                            $cell->setHyperlink(new Hyperlink($cell->getValue(), 'Read'));

                             // Upd: Link styling added
                             $event->sheet->getStyle($cell->getCoordinate())->applyFromArray([
                                'font' => [
                                    'color' => ['rgb' => '0000FF'],
                                    'underline' => 'single'
                                ]
                            ]);
                        }
                    }
                }
            },
        ];
    }
    // ...
}

Uso, apenas:

Excel::download(CommentsExport::class);

VocĂȘ estĂĄ certo. esta Ă© uma solução melhor do que eu. @AlexMcDee

@TimothyDLewis ou @herarya posso incomodĂĄ-lo por como vocĂȘ estĂĄ iterando na planilha? - talvez apenas poste um pouco mais de cĂłdigo sobre o mĂ©todo completo que vocĂȘ usou? (ou seja, recebendo $cellLetter.$rowIndex ou $cell ?)

Estou exportando uma matriz simples que possui 5 colunas de um banco de dados, - esta é uma planilha e possui uma linha de cabeçalho. Depois de pegå-lo, tenho este código que funciona, é claro:

//$trademark = [an array of data with 5 columns and a header row];
Excel::create('trademarks', function($excel) use($trademarks) {
  $excel->sheet('trademarks', function($sheet) use($trademarks) {
     $sheet->fromArray($trademarks,null,'A1',false,false);
     //need to iterate over $sheet, get each row, and find column 1 in that row and set a URL
})->export('xlsx');

Gostaria de iterar em $sheet e alterar uma célula em cada linha (diferente da primeira linha) com um URL. Eu tentei até 3 loops foreach profundos (eu continuo recebendo um erro de que o resultado é um objeto, uma matriz ou recebo "PHPExcel_Exception Coordenada de célula invålida CREATOR in Cell.php (linha 590)", e tentei $sheet- >each (que aparentemente é um método disponível apenas no carregamento em um arquivo, pois é um erro não haver método each).

CONSEGUI ISSO HOJE apĂłs descobertas ....

https://stackoverflow.com/questions/41053636/laravel-excel-export-each-cell-style

como retornar o mĂłdulo de coleta de mensagens de erro?

Apenas uma nota råpida para quem vem aqui do google, obrigado @mouyong @AlexMcDee pela solução fornecida.

Ao usar $sheet->getColumnIterator('H') , Ă© importante especificar o segundo parĂąmetro, que Ă© a coluna final $sheet->getColumnIterator('H', 'H') .

Sem a coluna final, o iterador irĂĄ iterar sobre cada coluna atĂ© a Ășltima coluna .

Percebi isso quando queria fazer um hiperlink para uma coluna no meio da planilha e nĂŁo na Ășltima coluna, como de costume.

Outra abordagem, que acabei seguindo, é usar a função de hiperlink do Excel.
Por exemplo, eu queria criar um hiperlink da planilha2 para as células da planilha1 (intervalo A1:A20) com o mesmo texto:
Na minha folha2
public function array(): array { $data = [ ['Id'], ]; foreach ($this->data as $id) { $idformula = '=HYPERLINK("#"&CELL("address", INDEX(Sheet1!A1:A20, MATCH("'.$id.'",Sheet1!A1:A20,0), 1)),"'.$id.'")'; array_push($data, [$idformula]); } return $data; }
e para estilizĂĄ-los:
public function styles(Worksheet $sheet) { return [ 'A' => ['font' => [ 'color' => ['rgb' => '0000FF'], 'underline' => 'single', ]], ]; }

Esta pĂĄgina foi Ăștil?
0 / 5 - 0 avaliaçÔes

QuestÔes relacionadas

matthewslouismarie picture matthewslouismarie  Â·  3ComentĂĄrios

kurianic picture kurianic  Â·  3ComentĂĄrios

alejandri picture alejandri  Â·  3ComentĂĄrios

thearabbit picture thearabbit  Â·  3ComentĂĄrios

muhghazaliakbar picture muhghazaliakbar  Â·  3ComentĂĄrios