How to get phpexcel to keep leading 0s in phone numbers?

Bogdan picture Bogdan · Mar 9, 2012 · Viewed 31k times · Source

Here's the code i'm using right now to set the cell values. It works alright if the number has separators like . or / but when there's no separator it gets saved as int and the leading 0 is stripped

$sheet->setCellValue($letter[$j].$row_nr,$entity['Phone'], PHPExcel_Cell_DataType::TYPE_STRING);

Answer

Mark Baker picture Mark Baker · Mar 9, 2012

Either:

// Set the value explicitly as a string
$objPHPExcel->getActiveSheet()->setCellValueExplicit('A1', '0029', PHPExcel_Cell_DataType::TYPE_STRING);

or

// Set the value as a number formatted with leading zeroes
$objPHPExcel->getActiveSheet()->setCellValue('A3', 29);
$objPHPExcel->getActiveSheet()->getStyle('A3')->getNumberFormat()->setFormatCode('0000');

Note that in the first case I'm calling the setCellValueExplicit() method, not the setCellValue() method. In your code, passing PHPExcel_Cell_DataType::TYPE_STRING to setCellValue() has no meaning, and the argument is simply ignored.