Laravel9 라라벨 액셀 다운로드 (Laravel-Excel)

2022. 8. 19. 17:31· PHP/Laravel
목차
  1. 라라벨 공부
  2. 개요
  3. 설치
  4. 사용법
  5. 활용

라라벨 공부

바로가기

 


개요

이전에 Fast-Excel 라이브러리를 이용해 액셀을 다운로드하여봤습니다

바로가기

 

하지만 사용해보니 다음과 같은 장점으로 기존에 쓰던 Laravel-Excel이 더 괜찮은 것 같습니다.

- 매우 잘된 튜토리얼

- 다양한 기능

- 어마 무시한 깃허브 스타가 주는 신뢰감

 

다음은 버전별 php의 권장 버전입니다.

이 부분을 참고하고 진행해주세요

 

저는 php 8.1.8, Laravel 9, Larvel-Excel 3.1을 사용했습니다.

설치

composer require maatwebsite/excel

위 commend로 설치 시 아래와 같은 에러가 발생할 경우

Info from https://repo.packagist.org: #StandWithUkraine
Using version ^3.1 for maatwebsite/excel
./composer.json has been updated
Running composer update maatwebsite/excel
Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - maatwebsite/excel[3.1.36, ..., 3.1.x-dev] require phpoffice/phpspreadsheet ^1.18 -> satisfiable by phpoffice/phpspreadsheet[1.18.0, ..., 1.24.1].
    - maatwebsite/excel[3.1.0, ..., 3.1.25] require php ^7.0 -> your php version (8.1.8) does not satisfy that requirement.
    - maatwebsite/excel[3.1.26, ..., 3.1.35] require illuminate/support 5.8.*|^6.0|^7.0|^8.0 -> found illuminate/support[v5.8.0, ..., 5.8.x-dev, v6.0.0, ..., 6.x-dev, v7.0.0, ..., 7.x-dev, v8.0.0, ..., 8.x-dev] but these were not loaded, likely because it conflicts with another require.
    - phpoffice/phpspreadsheet[1.18.0, ..., 1.22.0] require psr/simple-cache ^1.0 -> found psr/simple-cache[1.0.0, 1.0.1] but the package is fixed to 3.0.0 (lock file version) by a partial update and that version does not match. Make sure you list it as an argument for the update command.
    - phpoffice/phpspreadsheet[1.23.0, ..., 1.24.1] require psr/simple-cache ^1.0 || ^2.0 -> found psr/simple-cache[1.0.0, 1.0.1, 2.0.0, 2.x-dev] but the package is fixed to 3.0.0 (lock file version) by a partial update and that version does not match. Make sure you list it as an argument for the update command.
    - Root composer.json requires maatwebsite/excel ^3.1 -> satisfiable by maatwebsite/excel[3.1.0, ..., 3.1.x-dev].

Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions.
You can also try re-running composer require with an explicit version constraint, e.g. "composer require maatwebsite/excel:*" to figure out if any version is installable, or "composer require maatwebsite/excel:^2.1" if you know which you need.

아래 commend를 사용하시면 됩니다.

composer require psr/simple-cache:^2.0 maatwebsite/excel

config/app.php에 아래와 같이 수정합시다.

    'providers' => [
	...
        Maatwebsite\Excel\ExcelServiceProvider::class,

    ],


    'aliases' => Facade::defaultAliases()->merge([
        ...
        'Excel' => Maatwebsite\Excel\Facades\Excel::class,
    ])->toArray(),

이제 아래 명령어를 입력하면 export 세팅 파일을 만들 수 있습니다. config/excel.php

php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" --tag=config

 

사용법

이번에도 이전에 포스팅한 라라벨 CRUD를 사용하겠습니다.

이번 포스팅에 목적은 Laravel-Excel 이므로 필수는 아니지만 코드 이해가 필요하신 분은 참고하시면 되겠습니다.

바로가기

 

모든 액셀 다운로드 작업은 Export 객체를 통합니다, Export 클래스를 만들어줍시다.

php artisan make:export ProductsExport --model=Product

그러면 app/Exports/ProductsExport 파일이 생성된 것을 확인할 수 있습니다.

 

아래와 같은 코드로 생성되었습니다.

<?php

namespace App\Exports;

use App\Models\Product;
use Maatwebsite\Excel\Concerns\FromCollection;

class ProductsExport implements FromCollection
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return Product::all();
    }
}

이를 사용하기 위해 Controller를 아래로 바꾸어 줍시다

...

use Maatwebsite\Excel\Facades\Excel;
use App\Exports\ProductsExport;


class ProductController extends Controller
{

	...
    
    /* Laravel-Excel */
    public function export(){
        return Excel::download(new ProductsExport(), 'products.xlsx');
    }
    
    ...
}

web.php에 아래 코드를 추가합니다.

Route::get('products/export/', [ProductController::class, 'export'])->name('products.export');

기본 액셀에 경우 Fast-Excel과 달리 아무리 내용이 길어도 한 줄로 나오네요

 

활용

위에서 나온 액셀은 긴 데이터양이 작은 셀 안에 갇히므로 보기 어려웠는데 이를 조정해봅시다.

<?php

namespace App\Exports;

use App\Models\Product;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithColumnWidths;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class ProductsExport implements FromCollection, WithHeadings, WithColumnWidths, WithStyles
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return Product::all();
    }

    // 해딩 row 추가, 이차원 배열로 2행으로 만들 수도 있습니다.
    public function headings(): array
    {
        return [
            'ID',
            'Name',
            'Content',
            'Created At',
            'Updated At',
            'Call'
        ];
    }

    // 각 컬럼의 width 설정.
    public function columnWidths(): array
    {
        return [
            'A' => 10,
            'B' => 30,
            'C' => 45,
            'D' => 30,
            'E' => 30,
            'F' => 20,
        ];
    }

    // 스타일도 변경할 수 있습니다.
    public function styles(Worksheet $sheet)
    {
        $sheet->getStyle('A1:F1')->getFont()->setBold(true);
    }
}

아래와 같은 결과물을 얻을 수 있습니다.

확실히 Fast-Excel 보다는 자유롭게 커스텀이 가능하네요

 

반응형

'PHP > Laravel' 카테고리의 다른 글

Laravel9 이미지 업로드 (with Dropzone) 1부 : Setting & Create & Image Upload  (0) 2022.08.29
Laravel9 라라벨 난수 액셀 다운로드 (Laravel-Excel)  (2) 2022.08.22
Laravel9 라라벨 액셀 다운로드 (Fast-Excel)  (0) 2022.08.19
Laravel 9 CRUD 예제 4부 : 유효성 검사(Validation)  (0) 2022.08.11
Laravel 9 CRUD 예제 3부 : 페이지네이션(Pagination)  (0) 2022.08.10
  1. 라라벨 공부
  2. 개요
  3. 설치
  4. 사용법
  5. 활용
'PHP/Laravel' 카테고리의 다른 글
  • Laravel9 이미지 업로드 (with Dropzone) 1부 : Setting & Create & Image Upload
  • Laravel9 라라벨 난수 액셀 다운로드 (Laravel-Excel)
  • Laravel9 라라벨 액셀 다운로드 (Fast-Excel)
  • Laravel 9 CRUD 예제 4부 : 유효성 검사(Validation)
DSeung
DSeung
DSeung
Dev log
DSeung
  • 분류 전체보기 (193)
    • PHP (62)
      • Laravel (31)
      • Error (5)
      • Setting (11)
      • Modern PHP (15)
    • Go Lang (51)
      • Study (30)
      • Algorithm (17)
      • Setting (1)
      • Error (3)
    • Java (11)
      • Spring (3)
      • JSP (0)
      • Error (2)
      • Setting (2)
      • 단축키 (2)
    • JavaScript (6)
      • Modern JavaScript (4)
      • Node (1)
    • Android Kotlin (5)
      • Study (4)
      • Error (1)
    • 컴퓨팅 기술 (12)
      • 데이터베이스시스템 (4)
      • Docker (2)
      • 크롤링 & 스크래핑 (1)
      • API (1)
      • 클라우드 (1)
      • 네트워크 (1)
    • MySQL (7)
    • AWS (1)
    • Git (5)
      • GItLab (1)
      • GitHub (4)
    • 도메인 (2)
      • 안과 (2)
    • 자격증 (7)
      • SQLD (1)
      • 정보처리기사 (6)
    • Mac os (1)
    • 나머지 (13)
      • tistory (1)
      • 기타 (9)
      • 일기 (3)
    • 독서 (10)

인기 글

최근 글

블로그 메뉴

  • 홈
  • 태그
전체
오늘
어제
hELLO · Designed By 정상우.v4.2.0
DSeung
Laravel9 라라벨 액셀 다운로드 (Laravel-Excel)
상단으로

티스토리툴바

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.