Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

php - PHPExcel: How to check whether a XLS file is valid or not?

I'm using PHPExcel 1.7.8 to read .xls files, uploaded by a radom user. All is working properly with a valid .xls file, but now I wanted to make some tests with invalid files to check if the program displays good error messages.

So I took a .csv file, and renamed it with .xls (without converting anything, just changing the name) to the end, just to check...
Broken! :)

DOM ELEMENT: HTML
DOM ELEMENT: BODY
DOM ELEMENT: P
START OF PARAGRAPH: 
END OF PARAGRAPH:
FLUSH CELL: A1 => block,date,hour...

array
  1 =>
    array
      'A' => string  'block,date,hour...' (length=2777)

{"step":"error","errors":[],"warnings":[]}

Like you can see, there's an error message displaying, I didn't ask for that, and then the JSON that I usually write.

It happens on this line :

<?php
echo "Loading file
";
try {
    if (!($objPHPExcel = PHPExcel_IOFactory::load('path'))) {
        echo "Failed
";
        return;
        // ...
    }
} catch(Exception $e) {
    echo 'Exception !';
}
echo "Done
";

And this code displays:

Loading file
/! ERROR MESSAGE ABOVE /!
Done

My question is, is there a way with PHPExcel or anything else to check whether a file is a valid XLS file before I try to parse it?

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Even if it's more than a year question, I still find it cumbersome to figure it out how to deal with this issue, I'll try to post my answer here.

If using try/catch block doesn't work (in my case, I renamed a jpg file to xls and the error handler doesn't work, instead of throwing error, invalid file just throws a warning), you can consider a manual checking using canRead() as Mark said, here's an example of how to use this function.

If you know what your filetypes are, you can define it manually and check against them:

$valid = false;
$types = array('Excel2007', 'Excel5');
foreach ($types as $type) {
    $reader = PHPExcel_IOFactory::createReader($type);
    if ($reader->canRead($file_path)) {
        $valid = true;
        break;
    }
}

if ($valid) {
  // TODO: load file
  // e.g. PHPExcel_IOFactory::load($file_path)
} else {
  // TODO: show error message
}

Hope this help anyone with the same problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...