簡體   English   中英

PHPexcel刪除前導零的麻煩

[英]Trouble with PHPexcel removing leading zeros

我有下面的代碼,但是當我通過導入過程運行CSV時,我的前導零消失了。 例如,我有一個帶有數字的字段,例如“ 0010”,但是在來自以下代碼的字段之后,該數字為“ 10”。 有人有建議嗎?

  $objPHPExcel = new PHPExcel(); function ci_import($inputFileName){ //echo "calling....";exit; try { $inputFileType = PHPExcel_IOFactory::identify($inputFileName); $objReader = PHPExcel_IOFactory::createReader($inputFileType); $objPHPExcel = $objReader->load($inputFileName); } catch (Exception $e) { die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME) . '": ' . $e->getMessage()); } $sheets = count($objPHPExcel->getAllSheets()); //echo $sheets; //echo "<pre>"; $arr=array(); foreach($objPHPExcel->getAllSheets() as $sheet){ $title = $sheet->getTitle(); $arr[$title]=array(); $rows= array(); // fetch the data foreach ($sheet->getRowIterator() as $row) { $cols= array(); $cellIterator = $row->getCellIterator(); $cellIterator->setIterateOnlyExistingCells(false); // This loops all cells, foreach ($cellIterator as $cell) { $cols[]=$cell->getValue(); } $rows[] = $cols; } $arr[$title]=$rows; } return $arr; print_r( $arr); } 

數字沒有前導零。 但是PHPExcel的CSV閱讀器將識別出值0010為數字,並將其轉換為數字10 ,這是完全正確的,並且(僅供參考)與MS Excel CSV Reader完全相同。

如果要將此值視為字符串,或將其格式化為帶有前導零的4位數字,則需要創建一個自定義活頁夾,將其指定為導入值的規則。

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); 
        } 

        // Implement your own override logic 
        if (is_string($value) && $value[0] == '0') { 
            // Here, we're just enforcing that the value should be treated
            //   as a string, but we could convert it to a numeric and apply
            //   a format mask to the cell instead
            $cell->setValueExplicit($value, PHPExcel_Cell_DataType::TYPE_STRING); 
            return true; 
        } 

        // Not bound yet? Use default value parent... 
        return parent::bindValue($cell, $value); 
    } 
} 

為避免自動裝帶器出現任何問題,請在/ Classes / PHPExcel / Cell目錄中創建此裝帶器。 否則,給該類您自己的非PHPExcel名稱,並確保它是獨立加載的。

然后,在加載文件之前,指示應使用您的自定義活頁夾:

PHPExcel_Cell::setValueBinder( new PHPExcel_Cell_MyValueBinder() );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM