Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fputcsv display leading zeros

Tags:

php

csv

I'm using a PHP script to generate an excel CSV file from a result-set query. All works fine but when I read my excel file, I can not display leading zeros.

This is my code:

$rows = $this->Query($sql);

$filename = "/www/zendsvr/htdocs/Project/public/report.xls";
$realPath = realpath( $filename );

$filename = realpath( $filename );
$handle = fopen( $filename, "w" );
$finalData = array();

for( $i = 0; $i < count( $rows ); $i++ ) {
    $finalData[] = array( utf8_decode( $rows[$i]->CODE ) );
}

foreach ( $finalData AS $finalRow ) {
    fputcsv( $handle, $finalRow, "\t" );
}

fclose( $handle );

If I make a var_dump() of $finalData[] I see the correct value, for example '000198', '000199', '000200' but the same value in my XLS file is 198,199,200

How can I also display leading zeros in the XLS file?

like image 558
jack.cap.rooney Avatar asked Jun 18 '12 07:06

jack.cap.rooney


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 '"' .


2 Answers

To add to DemoUser's approach:

The \t approach worked for me however with a slight change

$column_data = "\t000543";

Adding the \t solved my problem of having the leading zero's disappear, even though the CSV was correct and Excel was 'wrong' the \t worked in keeping the leading zeros intact when displaying in excel.

like image 93
Ray Avatar answered Oct 25 '22 01:10

Ray


I was surprised after so many years no-one came with a working solution.

Here's what worked for me:

$records = [
    ['name' => 'John', 'phone' => '01234567'],
    ['name' => 'Jane', 'phone' => '01234569'],
];

$file = fopen('php://output', 'w');

fputcsv($file, ['Name', 'Phone N°']);

foreach ($records as $record) {
    fputcsv($file, [$record['name'], "=\"" . $record['phone'] . "\""]);
}
like image 38
SimonDepelchin Avatar answered Oct 25 '22 02:10

SimonDepelchin