00 Votes

PHPExcel: Leading Zeros

Question by WebHorn | 2016-12-20 at 23:58

I am using the library PHPExcel for creating and offering for download an Excel file created with PHP.

It is working quite well, but I would like to write the months from 01 till 12 into my table. Although I am passing the values "01", "02" and so on, there are appearing only "1" and "2" in the corresponding cells when opening the file in Excel without any zero in front.

What can I do to make Excel show those leading zeros?

0Best Answer0 Votes

When Excel is detecting a "01" within a cell, Excel interprets this content as a number and it only displays the integer 1 instead of the string "01".

In order to change this behavior, there are two possibilities in general. The first possibility is to format the cell no longer as number but as string instead. You can do that like the following:

    ->setCellValueExplicit('A1', '01', PHPExcel_Cell_DataType::TYPE_STRING);

If it is important for you that the number is further processed as a number by Excel, you can also change the number formatting of the corresponding set. In the following example, first, we are setting the cell A1 to 1, afterwards we are adjusting the formatting.

$php->getActiveSheet()->setCellValue('A1', 1);

In your case, you have to specify "00". If the numbers are longer or if you want more zeros to be displayed, you have to pass "000", "0000" or your desired number of digits accordingly.
2016-12-21 at 11:40

ReplyPositive Negative

Related Topics

PHPExcel: Change Font Size

Question | 1 Answer

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.


Ask your own question or write your own article on askingbox.com. That’s how it’s done.