Tuesday, October 4, 2022

[FIXED] How to get real number while importing on Laravel Excel maatwebsite?

Issue

I'd like to get numbers as the real value while importing a file, e.g:

When I open the csv, cell value: 198610012009011005

But when I import that using Laravel Excel, it'll be formatted to 1.98610012009011E+17

How can I get the real value of the number (198610012009011005) ? I tried bellow code but it didn't work

$data['excel'] = Excel::load($path, function ($reader) {
          $reader->sheet(0, function ($sheet) {
              $sheet->setColumnFormat(["A" => "@"]);
          });
      })->toArray();

Solution

Actually the value you get is true. 1.98610012009011E+17 is the form of exponential value. But if you want get it as string form try this approach.

You should create a ValueBinder class.

// MyValueBinderClass
use PHPExcel_Cell;
use PHPExcel_Cell_DataType;
use PHPExcel_Cell_IValueBinder;
use PHPExcel_Cell_DefaultValueBinder;

class MyValueBinder extends PHPExcel_Cell_DefaultValueBinder implements PHPExcel_Cell_IValueBinder
{
    public function bindValue(PHPExcel_Cell $cell, $value = null)
    {

        if (is_numeric($value))
        {
            $cell->setValueExplicit($value, PHPExcel_Cell_DataType::TYPE_STRING);

            return true;
        }

        // else return default behavior
        return parent::bindValue($cell, $value);
    }
}

And then bind it to while you load the csv file:

$myValueBinder = new MyValueBinder;
$data = Excel::setValueBinder($myValueBinder)
    ->load($path)->toArray();

reference: http://www.maatwebsite.nl/laravel-excel/docs/import#formatting



Answered By - Dharma Saputra
Answer Checked By - Mildred Charles (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.