How to left align mobile number in php for excel

hi
This below code generates excel file.
But when i open it, the mobile number is right aligned in column in excel.
How can i left align it in excel through php ?
Also how do i increase column width in excel through php ?
thanks
vineet

while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {
        $output.= $row['firstname'] . "\t". $row['mobile'] ."\t". $row['user_date'] ."\n";
          }
               header('Content-Type: application/xls');
               header('Content-Disposition: attachment; filename=users-'.'.xls');
               echo $output;

Do you have a way to make sure that it’s being taken as a string - perhaps put single quotes around it? If Excel sees that it’s just a number, it will treat it as such and right-align it.

As for anything else, you’re not actually outputting an Excel spreadsheet as far as I can tell, you’re outputting tab-delimited text and giving it an XLS header. If you want to add formatting I think you’ll have to provide more information in your download. Of course, if you can do enough formatting to change column width, you can probably force left-alignment for the mobile number too.

hi droopsnoot

ok i was able to change mobile number to string and its now left aligning correctly.
Can you tell me how to change the column width ?
what more information do i have to provide in my download in addition to headers ?
thanks
vineet

hi droopsnoot

i just noticed that mobile number is left aligning
BUT i am getting single quotes around mobile number in excel.
like this below

'1234567890'

what am i doing wrong ?
here is the code

while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {
                $mob =  $row['mobile'];
                $mob2 = "'".$mob."'";
               $output.= $row['firstname'] . "\t". $mob2 ."\t". $row['user_date'] ."\n";
               }

if i remove the single quotes then the mobile number dont left aligns in excel.
thanks
vineet

I suggest you insert a space character in the mobile number instead.

hi Archibald

i tried replacing single quotes with space character
But then mobile number doesnot left align in excel

$mob2 = " ".$mob." ";
$output.= $row['firstname'] . "\t". $mob2 ."\t". $row['user_date'] ."\n";

Insert a space character somewhere within the number, not at the start or end.

hi Archibald
The mobile number has to remain 10 characters without spaces between.

I think you might be able to make it a string by starting with a single quote mark but not one at the end. I may be wrong. I try to avoid Excel.

You’re probably better off using a package to write actual excel files, rather than hacking CSV files disguised as excel files.

Have a look at https://github.com/PHPOffice/PhpSpreadsheet

1 Like