dongsui0929 2012-11-29 13:15
浏览 151
已采纳

PHPExcel:如何检查XLS文件是否有效?

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.

  • 写回答

2条回答 默认 最新

  • dongyong8491 2012-11-29 13:25
    关注

    Each reader in PHPExcel has a canRead() method that validates the file passed in to the read is of the appropriate format for that reader - the method returns a simple boolean True or False. A return of True from a call to the canRead() method of the PHPExcel_Reader_Excel5 class will confirm that the file can be read by that reader, irrespective of the file extension.

    The IOFactory identify() method uses this call, testing against the Readers for each supported format in turn until it gets a true return from the canRead() call. The IOFactory load() method, in it's turn, uses identify() to determine which Reader should be used for the specified file.

    The ability to verify a filetype (without depending on the file extension which can often be misleading) is particularly useful when you want to set additional arguments for the reader.

    The fallback from identify()/load() is slightly less satisfactory: if canRead() returns false for all other Readers, then the file is treated as a CSV.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题