rap2hpoutre / fast-excel

🦉 Fast Excel import/export for Laravel
MIT License
2.09k stars 245 forks source link

Limit on how many rows should be inserted. #240

Open p1xel007 opened 2 years ago

p1xel007 commented 2 years ago

Is it possible to set a limit on how many rows can be imported?

mcolominas commented 2 years ago

It would not make sense to limit imports, if you want to import something, the normal thing is to import the whole sheet, also, you can limit the maximum size of the file that is uploaded to the server..

If you really want to limit imports, you can have a global variable that increases and when it reaches a certain amount call an exception, in this case, I advise you to create your own exception:

$current_imports= 0;
$limit_imports = 1;
try {
    (new FastExcel())->import($file_name, function ($row) use (&$current_imports, $limit_imports) {
        if ($current_imports++ >= $limit_imports) throw new \Exception("Maximum imports reached");

        //Import
    });
} catch (\Throwable $th) {
    //Do something
}

Another alternative you have, is that the import returns a collection of all the data, you can perform a count to know how many records there are:

$results = (new FastExcel())->import($file_name, function($row){
    //parse row but don't insert
    return $row;
});
//Or
$results = (new FastExcel())->import($file_name);

$count_results = count($results);

EDIT: I advise you to use the second option, since using the first, it will not call:

$reader->close();

EDIT2: In the first example, the following could also apply:

(new FastExcel())->import($file_name, function ($row) use (&$current_imports, $limit_imports) {
    if ($current_imports++ >= $limit_imports) return null;

    //Import
});
atymic commented 2 years ago

This should be a feature, would you accept a PR? Use case, preview first x lines of file for the purpose of choosing data mapping

atymic commented 2 years ago

.https://github.com/rap2hpoutre/fast-excel/pull/248