0

I want to read an excel file with Phpexcel and insert data into database, i can read everything and it's work fine but i can't read phone number with leading zero by Phpexcel when i see my database all the phone numbers saved without the leading zero like this:0212365498 saved as 212365498

Mo Saeedi
  • 575
  • 1
  • 5
  • 15
  • Have you tried reading them as strings instead of integers? – Peon Mar 06 '13 at 07:51
  • I think you cannot store number begin with zero in DB (assuming your DB field is INT) . Try changing the type of field from INT to VARCHAR. This may help : http://stackoverflow.com/questions/2786193/allow-number-to-start-with-zero-when-stored-in-mysql-integer-field – Makesh Mar 06 '13 at 07:55
  • i have tried to reading as string but it's not work – Mo Saeedi Mar 06 '13 at 08:07
  • As I mentioned problem is at your DB side – Makesh Mar 06 '13 at 08:29

1 Answers1

4

If you are importing from a CSV file you can use a value binder to retain any leading zero. This is how I implemented my fix.

Created a class called 'BindValueAsString'

class BindValueAsString extends PHPExcel_Cell_DefaultValueBinder implements PHPExcel_Cell_IValueBinder
{
    public function bindValue(PHPExcel_Cell $cell, $value = null)
    {
        $cell->setValueExplicit($value, PHPExcel_Cell_DataType::TYPE_STRING);
        return true;
    }
} 

Set value binder before loading the CSV file

$objReader    = PHPExcel_IOFactory::createReader('CSV');
PHPExcel_Cell::setValueBinder(new BindValueAsString());
$objPHPExcel  = $objReader->load('file.csv');
$worksheet    = $objPHPExcel->getActiveSheet();
$dataAsString = $worksheet->toArray();

And that's it. Or you can just upgrade to version 1.8.1 where leading zeros are fixed here

OsvyG
  • 335
  • 2
  • 9