fputcsv display leading zeros

后端 未结 4 2069
轮回少年
轮回少年 2021-01-04 17:57

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

相关标签:
4条回答
  • 2021-01-04 18:21

    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.

    0 讨论(0)
  • 2021-01-04 18:21

    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'] . "\""]);
    }
    
    0 讨论(0)
  • 2021-01-04 18:34

    Your data is saved correctly, it is Excel who is trying to be smart.

    Use the Excel import data wizard instead of opening the file directly (rename the .csv file to .txt if necessary). On the import wizard, choose the data type of the column as "text" instead of "general":

    Text import wizard step 3

    0 讨论(0)
  • 2021-01-04 18:43

    Try casting it to string like:

    fputcsv($fp, (string) $val);
    

    OR, Opening XLS file will truncate leading 0 so try adding /t before zero to avoid 0 truncation while creating your row values.

    0 讨论(0)
提交回复
热议问题