fast-excel icon indicating copy to clipboard operation
fast-excel copied to clipboard

Limit on how many rows should be inserted.

Open p1xel007 opened this issue 3 years ago • 3 comments

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

p1xel007 avatar Oct 18 '21 22:10 p1xel007

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
});

mcolominas avatar Oct 19 '21 12:10 mcolominas

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 avatar Dec 27 '21 01:12 atymic

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

atymic avatar Dec 27 '21 01:12 atymic