30

I'm trying to use PHP to create a file containing a list of phone numbers. It's working OK however if the phone number begins with zero, the digit is dropped from the Excel file.

Does anyone know how to set the formatting correctly so that it remains in place?

pnuts
  • 58,317
  • 11
  • 87
  • 139
Dan
  • 387
  • 2
  • 5
  • 8

6 Answers6

69

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');
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
16

Set the type to string explicitly:

$type = PHPExcel_Cell_DataType::TYPE_STRING;
$sheet->getCellByColumnAndRow($column, $rowno)->setValueExplicit($value, $type);
Sjoerd
  • 74,049
  • 16
  • 131
  • 175
1

This is an old question but I was recently struggling with this issue and I thought it may help someone in the future if I post some additional info here:

Whilst the above answers are correct, the formatting gets lost when you remove a column or row that is located before the formatted cell.

The solution that seems to be resistand to that is:

$cellRichText = new \PHPExcel_RichText($worksheet->getCell($cell));                        
$cellRichText->createText($cellValue);
Tomasz
  • 151
  • 5
  • I think format is not lost but kept in the original cell position, i.e I set the format in the column E, remove column B, column E is now column D, but the format remains in column E. I'm just dealing with this issue, because I need to remove columns after setting the format. – morgar Mar 22 '20 at 02:49
1

If for some reason the answers above don't work, you can simply try to wrap your data in quotes, something like this:

setCellValue('A1, '"' . $phone . '" ')

But your value will be surrounded by quotes in your file as well.

keepthepeach
  • 1,621
  • 2
  • 20
  • 27
1

Use \t with the value like "$phone\t"

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Nishad Aliyar
  • 77
  • 1
  • 3
0

In My case, I'm using

->setCellValue('A3', ' '0000123456789000' ');

And it's work perfectly.

Dorian Turba
  • 3,260
  • 3
  • 23
  • 67