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
Use this. It will show the .xlsx
$inputFileName = public_path('asset/docs/Filename.xlsx');
/** Load $inputFileName to a Spreadsheet Object **/
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($inputFileName);
$writer = IOFactory::createWriter($spreadsheet, 'Html');
$message = $writer->save('php://output');
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.
From my understanding, you are missing a piece. Why don't you first create a reader and then load the file.
Try the following code. It can identify the extension and create the reader of that type accordingly.
$inputFileName = "Text.xlsx";
/** Identify the type of $inputFileName **/
$inputFileType = \PhpOffice\PhpSpreadsheet\IOFactory::identify($inputFileName);
/** Create a new Reader of the type that has been identified **/
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
/** Load $inputFileName to a Spreadsheet Object **/
$spreadsheet = $reader->load($inputFileName);
/** Convert Spreadsheet Object to an Array for ease of use **/
$schdeules = $spreadsheet->getActiveSheet()->toArray();
Now you can simply run a foreach loop on the result array.
foreach( $schdeules as $single_schedule )
{
echo '<div class="row">';
foreach( $single_schedule as $single_item )
{
echo '<p class="item">' . $single_item . '</p>';
}
echo '</div>';
}
This is tested and working code.
I had the same issue, after adding .xlsx files to a git repository on my Mac.
The problem was that git auto-converted the line endings.
The solution was to add these lines to the .gitattributes
file:
*.xls binary
*.xlsx binary