PHP code example of maymeow / excel-importer

1. Go to this page and download the library: Download maymeow/excel-importer 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/ */

    

maymeow / excel-importer example snippets




use MayMeow\ExcelImporter\Models\BaseModel;

class ExampleModel extends BaseModel
{
    #[\MayMeow\ExcelImporter\Attributes\Column('A')]
    protected string $property;

    public function getProperty()
    {
        return $this->property;
    }
}

// ...

use MayMeow\ExcelImporter\Models\ExampleModel;
use MayMeow\ExcelImporter\Writers\ModelWriter;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;

// ...
public function testImportingFile()
{
    $xlsxReader = new Xlsx();
    $spreadsheet = $xlsxReader->load((new TestingDataLocator())->locateExcelFile());
    $writer = new ModelWriter();
    
    /** @var array<TestingModel> $modelArray */
    $modelArray = $writer->write(TestingModel::class, $spreadsheet);
}
// ...

class TestingModel extends BaseModel
{
    #[Column('A')]
    #[NotEmpty]
    protected string $colA;

// ...
}

$baseValidator = new BaseValidator(failFast: true, throwException: false);
// fast fail with fail on first error if set tot true otherwise will continue until end and return ValidatorBag
// throwExcpetion will throw ValidationException if set to true

// you can validate arrory of models
$e = $baseValidator->validateMany($this->modelArray, rule: NotEmpty::class);

// or just single model
$baseValidator->validate($this->modelArray[2], rule: NotEmpty::class);

//then you can get error messages as follows
if ($e->hasErrors()) {
    // return any first error for any field or any row (for both validate and validateMany)
    $e->getFirstError(); 

    // return any first error on index 2 (use this for indexed - for validateMany)
    $e->getFirstError(index: 2); 

    // return first error for field colA in any index (for both validate and validateMany)
    $e->getFirstError(field: 'colA'); 

    // return first error for field colA on index 2 (for validateMany)
    $e->getFirstError(field: 'colA', index: 2); 
}

$errors = new ValidatorErrorBag();

// Errors for multiple models (indexed)
$errors->addError('name', 'Name is 

// Non-indexed errors (single model)
$errors->addError('age', 'Age must be a number');

// 🔥 Get first error globally
echo $errors->getFirstError(); // Output: "Name is or a specific field across all indexed models
echo $errors->getFirstError('email'); // Output: "Invalid email format"

// 🔥 Get first error from any row for a **numeric field key**
echo $errors->getFirstError(0); // Output: "Name is 
bash
php application.php app:read-file -f ./path/to/file.xlsx