我使用PHPExcel库开发了一个PHP Web应用程序。一切正常,除了一些Excel文档奇怪地无法识别为Excel文档。当我用Microsoft Excel打开这些文件并将它们保存为xls,csv,xlsx时,一切都运行良好。 所以...我认为一些Excel文件并不完全是他们的扩展所说的。也许他们是伪装的XML?是否可以通过PHPExcel获得XML支持?
这是错误:
Fatal error: Uncaught exception 'PHPExcel_Reader_Exception' with message 'The filename /tmp/phphrnIR2 is not recognised as an OLE file' in /home/www/text/excel/reader/Classes/PHPExcel/Shared/OLERead.php:89 Stack trace: #0 /home/test/excel/reader/Classes/PHPExcel/Reader/Excel5.php(1164): PHPExcel_Shared_OLERead->read('/tmp/phphrnIR2') #1 /home/www/text/excel/reader/Classes/PHPExcel/Reader/Excel5.php(612): PHPExcel_Reader_Excel5->_loadOLE('/tmp/phphrnIR2') #2 /home/www/test/excel/actions.php(60): PHPExcel_Reader_Excel5->load('/tmp/phphrnIR2') #3 /home/www/test/excel/index.php(77): include_once('/home/www/test/ex...') #4 {main} thrown in /home/www/test/excel/reader/Classes/PHPExcel/Shared/OLERead.php on line 89
用于文件识别的php代码:
$name = $_FILES['file']['name'];
$tname = $_FILES['file']['tmp_name'];
$type = $_FILES['file']['type'];
if($type == 'application/vnd.ms-excel')
{
// Excel 97 extension
$ext = 'xls';
}
else if($type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
{
// Excel 2007 and 2010 extension
$ext = 'xlsx';
}
else if($type == 'text/csv')
{
// Excel CSV extension
$ext = 'csv';
}else{
// Invalid Extension
?>
<script languaje="javascript">
swal("Bad file...", "A valid extension must be XLS, XLSX o CSV!", "error");
</script>
<?php
exit();
}
//reader creation
$objReader = PHPExcel_IOFactory::createReader($$ext);
//uploading file
$objPHPExcel = $objReader->load($tname);
$dim = $objPHPExcel->getActiveSheet()->calculateWorksheetDimension();
答案 0 :(得分:2)
好吧,尽管它有一个.xls
扩展名,但它完全有可能不是BIFF格式的xls文件。
很多人在csv格式文件中给文件添加xls扩展名,甚至HTML标记.....永远不要信任扩展名;并且由于mime类型将基于文件扩展名,因此您也不能将其视为面值。
而不是基于扩展/ mime类型专门创建Reader ....使用PHPExcel IOFactory identify()方法来查看PHPExcel认为该文件的文件格式。或者调用IOFactory的load()方法,以便它可以尝试识别自己的文件格式。
显然,这个文件不是BIFF格式(或者是在版本5之前使用早期版本的BIFF格式创建的),否则它将被识别为OLE文件
答案 1 :(得分:1)
我遇到了您遇到的同样问题,匿名用户。这就是我修复它的方法:
require_once('Classes'.DIRECTORY_SEPARATOR.'PHPExcel.php');
// Tell PHPExcel to load this file and make its best guess as to its type.
$objPHPExcel = PHPExcel_IOFactory::load($_FILES['uploaded_file']['tmp_name']);
require_once('Classes'.DIRECTORY_SEPARATOR.'PHPExcel.php');
// Tell PHPExcel that you will be loading a file.
$objReader = PHPExcel_IOFactory::createReaderForFile($_FILES['uploaded_file']['tmp_name']);
// Set your options.
$objReader->setReadDataOnly(true);
// Tell PHPExcel to load this file and make its best guess as to its type.
$objPHPExcel = $objReader->load($_FILES['uploaded_file']['tmp_name']);
现在你有了一个PHPExcel对象,你可以用这种方式处理工作表:
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$worksheets[] = $worksheet->toArray();
}
foreach($worksheets as $sheet) {
foreach($sheet as $row) {
print_r($row);
}
}