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:
.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.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.