php做EXCEL資料匯出匯入開發的一些小問題

草木本心發表於2015-11-11

前兩天剛剛做開發CRM系統專案,在做要做EXCEL匯出匯入功能,因為以前做.NET開發用的是NPOI,但可是沒找到PHP版本的,所以就網搜找了個國外的開源PHPEXCEL ,

一開始只是做了簡單的匯入匯出,還沒有出現做什麼問題,一切順利(因為那是EXCEL的單元格都沒有設定什麼資料型別的情況下),

在做匯入讀取EXCEL資料時,而且單元格里的資料型別改成文字型別時,在PHPEXCEL讀出來的是PHPExcel_RichText型別的,這型別使getValue()是不管用了,因為這時候getValue()返回的PHPExcel_RichText(下面是PHPExcel_RichText資料儲存格式)是一個Object型別了,所以在搜入資料的時候肯定出錯了。

 PHPExcel_RichText Object
(
    [_richTextElements:PHPExcel_RichText:private] => Array
        (
            [0] => PHPExcel_RichText_TextElement Object
                (
                    [_text:PHPExcel_RichText_TextElement:private] => l
                )

            [1] => PHPExcel_RichText_Run Object
                (
                    [_font:PHPExcel_RichText_Run:private] => PHPExcel_Style_Font Object
                        (
                            [_name:protected] => Calibri
                            [_size:protected] => 11
                            [_bold:protected] => 
                            [_italic:protected] => 
                            [_superScript:protected] => 
                            [_subScript:protected] => 
                            [_underline:protected] => none
                            [_strikethrough:protected] => 
                            [_color:protected] => PHPExcel_Style_Color Object
                                (
                                    [_argb:protected] => FF000000
                                    [_parentPropertyName:protected] => 
                                    [_isSupervisor:protected] => 
                                    [_parent:protected] => 
                                )

                            [_isSupervisor:protected] => 
                            [_parent:protected] => 
                            [colorIndex] => 8
                        )

                    [_text:PHPExcel_RichText_TextElement:private] => isimin
                )

        )

)

用var_dump()輸出一看蒙了,不過也沒關係,既然是PHPExcel_RichText型別的資料,經過查文件,發現該物件有getPlainText()方法獲取單元格的值,這回笑了^_^

在這裡要做個判斷

if(getValue() instanceof \PHPExcel_RichText) 

{

  //處理PHPExcel_RichText讀取

}else{

  //直接讀取getValue()

}

oK,注意有些網上用new PHPExcel_RichText($cell) 轉換的,會出現 Call to undefined method PHPExcel_CachedObjectStorage_Memory::getStyle()這個錯誤的

這個是PHPExcel的一個BUG或是遺漏吧,這錯誤解決方案是:

在CacheBase.php中的PHPExcel_CachedObjectStorage_Memory加一個getStyle()方法,

public function getStyle($pCellCooldinate='A1')
{
  return $this->_parent->getStyle($pCellCooldinate) ;
}

相關文章