Search code examples
phpphpexcel

exporting php data into excel in text data type


I want to export my php web page to excel.

For that, I have found the following code which works but it has an issue.

Values in a column start with something like '00003421' in php but when it is exported in excel, it shows only '3421' in the cell. It ignores the zero values. Moreover, I want them in text data type.

How can I export the data in plain text format as it is (including zeroes)?

header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=export.xls");
header("Content-Transfer-Encoding: BINARY");

It's tabular data with 4 columns and around 20,000 rows.


Solution

  • A possible solution is to create a new value Binder method to override the PHPExcel method. (PHPExcel tries to guess the datatype we insert in the cells. So, following the advice of markBaker, I created this class to override this method:

    class PHPExcel_Cell_MyValueBinder extends PHPExcel_Cell_DefaultValueBinder
    implements PHPExcel_Cell_IValueBinder 
    { 
        public function bindValue(PHPExcel_Cell $cell, $value = null) { 
            // sanitize UTF-8 strings 
            if (is_string($value)) { 
                $value = PHPExcel_Shared_String::SanitizeUTF8($value); 
            } 
    
            // if it is a string and starts with 0, the value will be converted into string 
            if (is_string($value) && $value[0] == '0') { 
                $cell->setValueExplicit($value, PHPExcel_Cell_DataType::TYPE_STRING); 
                return true; 
            } 
            return parent::bindValue($cell, $value); 
        } 
    } 
    

    this was a tip that markbaker recommended to me in this question.