Read Xlsx file in PhpSpreadsheet

前端 未结 4 2199
眼角桃花
眼角桃花 2020-12-15 10:43

I want to read an xlsx file that was created in Microsoft Excel, but when I run the following code...

$Source_File = \"test.xlsx\";
$Spreadsheet         


        
4条回答
  •  清歌不尽
    2020-12-15 11:21

    I ran into this same exact error when trying to load in an XLSX file. For me personally, I discovered a very easy fix that fixed my issue. I was manually grabbing the extension off the filename as xlsx. I noticed some other code of mine using the old PHP Spreadsheet library was taking in the extension Xls. So I tried loading in Xlsx and it worked perfectly.

    Here is the code I am using to correctly load in the extension. It simply grabs all the characters after the last period and then captilizes the first character of that substring. ucfirst simply uppercases the first letter of the string passed into it. substr returns a substring where the first parameter is the string to grab from and the second parameter is what index to start the substring at in the given string. And finally strrpos finds the last occurrence of a substring in the given string.

    https://www.php.net/manual/en/function.ucfirst.php

    https://www.php.net/manual/en/function.strrpos

    https://www.php.net/manual/en/function.substr.php

    $inputFileType = ucfirst(substr($cccFile, strrpos($cccFile, '.') + 1));
    
    /**  Create a new Reader of the type defined in $inputFileType  **/
    $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
    

    Once, I added in the ucfirst command, it solved the issue for me.

提交回复
热议问题