PHP code example of dcat-x / easy-excel

1. Go to this page and download the library: Download dcat-x/easy-excel library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

dcat-x / easy-excel example snippets


use Dcat\EasyExcel\Excel;

$data = [
    ['id' => 1, 'name' => 'Tom', 'email' => '[email protected]'],
    ['id' => 2, 'name' => 'Jerry', 'email' => '[email protected]'],
];

// 自定义表头
$headings = ['id' => 'ID', 'name' => '姓名', 'email' => '邮箱'];

Excel::export($data)->headings($headings)->download('users.xlsx');
Excel::export($data)->headings($headings)->download('users.csv');
Excel::export($data)->headings($headings)->download('users.ods');

use Dcat\EasyExcel\Excel;
use League\Flysystem\Filesystem;
use League\Flysystem\Local\LocalFilesystemAdapter;

// 保存到本地路径
Excel::export($data)->store('/tmp/users.xlsx');

// 使用 Flysystem
$filesystem = new Filesystem(new LocalFilesystemAdapter(__DIR__));
Excel::export($data)->disk($filesystem)->store('users.xlsx');

use Dcat\EasyExcel\Excel;

$xlsx = Excel::xlsx($data)->raw();
$csv = Excel::csv($data)->raw();
$ods = Excel::ods($data)->raw();

use Dcat\EasyExcel\Excel;

$headings = ['id', 'name', 'email'];

$allSheets = Excel::import('/tmp/users.xlsx')->headings($headings)->toArray();
// 返回: ['Sheet1' => [['id' => 1, 'name' => 'Tom', ...], ...]]

use Dcat\EasyExcel\Excel;

// 第一个工作表
$data = Excel::import('/tmp/users.xlsx')->first()->toArray();

// 最后活动的工作表
$data = Excel::import('/tmp/users.xlsx')->active()->toArray();

// 按名称或索引获取
$data = Excel::import('/tmp/users.xlsx')->sheet('Sheet1')->toArray();
$data = Excel::import('/tmp/users.xlsx')->sheet(0)->toArray();

use Dcat\EasyExcel\Excel;
use Dcat\EasyExcel\Contracts\Sheet;
use Dcat\EasyExcel\Support\SheetCollection;

Excel::import('/tmp/users.xlsx')->each(function (Sheet $sheet) {
    $name = $sheet->getName();
    $index = $sheet->getIndex();

    $sheet->chunk(1000, function (SheetCollection $collection) {
        foreach ($collection as $row) {
            // 处理每一行
        }
    });
});

use Dcat\EasyExcel\Excel;
use Dcat\EasyExcel\Support\SheetCollection;

// 每次处理 1000 行,适合大文件
Excel::import('/tmp/users.xlsx')
    ->first()
    ->chunk(1000, function (SheetCollection $collection) {
        $data = $collection->toArray();
        // 批量处理数据...
    });