Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

phpexcel

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);
like image 373
Bogdan Avatar asked Mar 09 '12 13:03

Bogdan


People also ask

How do I keep zeros in cells when exporting from PHP to Excel?

You can type an apostrophe (') in front of the number, and Excel will treat it as text. So: echo '"' .

How to get cell value in PhpSpreadsheet?

To retrieve the value of a cell, the cell should first be retrieved from the worksheet using the getCell() method. A cell's value can be read using the getValue() method. // Get the value from cell A1 $cellValue = $spreadsheet->getActiveSheet()->getCell('A1')->getValue();


2 Answers

For me this did the trick

// Set the value explicitly as a string
$objPHPExcel->getActiveSheet()->setCellValueExplicit('A1', '0029', PHPExcel_Cell_DataType::TYPE_STRING);
like image 102
Alex Avatar answered Oct 14 '22 06:10

Alex


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.

like image 36
Mark Baker Avatar answered Oct 14 '22 07:10

Mark Baker