2017-03-14 15 views
0

私は以下のコードを持っていますが、インポートプロセスでCSVを実行すると先行ゼロはなくなります。たとえば、 "0010"のような数字のフィールドがありますが、下のコードから来た後の数字は "10"です。誰でも提案がありますか?PHPexcelで先行ゼロを削除するときの問題

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

答えて

1

先頭のゼロを持っていない数字。 PHPExcelのCSV Readerは数値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()); 
関連する問題