duanre4421
2016-05-20 07:35
浏览 51
已采纳

PHPExcel在xls和xlsx之间切换

I am writing a script that reads .xls and .xlsx files from mail attachments. I'm trying to make the script switch between readers based on the file extension using the identify method.

$strSheetNameResult = 'QA Result';
$strSheetNameComments = 'QA Comments'; 

foreach($aPaths as $strPath) {
    try {
        $strFileType = PHPExcel_IOFactory::identify($strPath);
        echo $strFileType;

        $oReader = PHPExcel_IOFactory::createReader($strFileType);

        $oReader->setLoadSheetsOnly($strSheetNameResult);

        $oSheetData = $oReader->load($strPath)->getActiveSheet();

.xls works just fine, but as soon as it encounters an .xlsx file it doesn't use the right reader and gives me an error: `Fatal error:

Call to a member function getCell() on a non-object in C:\xampp\htdocs\cronjob\Test.php on line 37`

line 37:

$aSheetData['strProjectName'] = $oSheetData->getCell('B4')->getValue();

I think this error is caused because it's not using the right reader.

$aPaths:

Array(
    [0] => C:\xampp\tmp\105943-632345.xls
    [1] => C:\xampp\tmp\112047-634744.xlsx
    [2] => C:\xampp\tmp\112069-634917.xls
    [3] => C:\xampp\tmp\113840-634955.xls
    [4] => C:\xampp\tmp\115760-635374.xlsx
    [5] => C:\xampp\tmp\120294-637780.xls
    [6] => C:\xampp\tmp\120801-638144.xls
    [7] => C:\xampp\tmp\121098-638118.xls
    [8] => C:\xampp\tmp\124831-641137.xlsx
    [9] => C:\xampp\tmp\127680-642962.xls
    [10] => C:\xampp\tmp\127689-642665.xls
    [11] => C:\xampp\tmp\127692-642784.xls
    [12] => C:\xampp\tmp\127700-643048.xls
    [13] => C:\xampp\tmp\127708-643096.xls
    [14] => C:\xampp\tmp\128771-642241.xls
    [15] => C:\xampp\tmp\129082-647219.xls
    [16] => C:\xampp\tmp\129629-647241.xls
    [17] => C:\xampp\tmp\134488-647334.xls
    [18] => C:\xampp\tmp\134500-646313.xls
    [19] => C:\xampp\tmp\134508-644581.xls
    [20] => C:\xampp\tmp\134511-646521.xls
    [21] => C:\xampp\tmp\134512-646136.xls
    [22] => C:\xampp\tmp\134561-650010.xls

)

Does anybody have an idea why this isn't working, or a different way to switch between readers?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duaevb1511 2016-05-20 08:17
    已采纳

    There was a corrupt file in the list that identified as an xls file but was an xlsx file. I deleted the file and it works perfectly now!

    已采纳该答案
    打赏 评论
  • drogon982007 2016-05-20 07:56

    you can try:

    
    
        $file_types = explode(".", 'C:\xampp\tmp\105943-632345.xls');
        $file_type = strtolower($file_types [count($file_types) - 1]);
    
        if($file_type=='xls') {
            $objReader = PHPExcel_IOFactory::createReader('Excel5');
        }elseif($file_type=='xlsx'){
            $objReader = PHPExcel_IOFactory::createReader('Excel2007');
        }else{
            echo 'file type error!';
            exit;
        }
    
    
    
    打赏 评论

相关推荐 更多相似问题