This code works fine until it gets to the open workbook line and then it fails.
<?PHP
$file = "C:\\xampp\\htdocs\\php\\test.xls";
openWorkbook($file);
function openWorkbook($file)
{
$excel = new COM("Excel.Application") or die ("ERROR: Unable to instantaniate COM!\r\n");
echo "Application name: {$excel->Application->value}\r\n";
echo "Loaded version: {$excel->Application->version}\r\n";
// FAILS ON THIS LINE!
$Workbook = $excel->Workbooks->Open($file) or die("ERROR: Unable to open " . $file . "!\r\n");
}
Does anyone have any suggestions to why this may be happening? I've looked though a lot of other posts, but no one seems to have this specific issue.
I shall assume that there is some reason why you need to use COM and not a 3rd-party library like PHPExcel. If there isn't a specific reason for this, consider switching to one these tried, tested and considerably better supported alternatives.
Your code seems to be correct, I can only imagine you have some kind of permissions problem.
It can be quite difficult to extract sensible error messages from MSO applications in PHP via COM, so here's a couple of things you can try:
- Verify that the file extension (
.xls
in you case) matches the data inside the file - make sure you don't have a CSV file with the wrong file extension, for example. Excel (even when accessed via COM) should be able to handle this, but it will throw up a warning if you open the file in the Excel application.
- Open the file in Excel, type in an empty cell, delete what you just typed, and save it. This will cause Excel to re-encode and write the entire file back to disk, which may also help resolve any corrupt file issues.
- Make sure the file has the appropriate permissions on it. The best way to do this would be to set the file as full permissions for the "Everyone" group, and if this fixes the problem you can then adjust the permissions to the required restrictions.
This is highly unlikely to fix this specific problem (the file open code appears to be identical) but it may assist you a little: some time ago I wrote a very small wrapper library for Excel accessed via COM, which can be found here. Its functionality is very limited, but more methods could be added quite easily; what it mostly brings to the party is a slightly cleaner API and slightly better error handling.