我最近在 PHP 中编写了一个脚本,使用 COM 对象将 Excel 2007 电子表格中的单元格中的数据剥离到一个数组中。这一切都是在带有 Office 2007 的 XP 系统上本地完成的。一旦我启用了 Apache 服务器与桌面交互,脚本就像一个绝对的梦想一样工作,允许我通过 PHP 用数组值填充我的 HTML。
现在我们刚刚升级到 Win 7 x64 和 Office 2010 32 位 - 相同的脚本现在向我抛出了 COM_exception:
'Microsoft Excel 无法访问' xml/xmlx 文件(它以前对两者都有效)。“有几个可能的原因:
- 文件名或路径不存在。
- 该文件正被另一个程序使用。
- 您尝试保存的工作簿与当前打开的工作簿具有相同的名称”......显然。
我已经禁用 UAC 认为这是罪魁祸首,当然允许 Apache 与桌面交互,但 Excel 进程甚至没有尝试启动。我猜 Windows 7 根本不允许脚本与 Excel 交互。使用类(例如 PHPExcel)还有其他可用的脚本,但是我宁愿避免编写收件人代码,而且我什至不知道这些类是否适用于 Excel 2010。
我怎样才能克服这个com_exception?
代码:
<?php
error_reporting(E_ALL);
function getDataFromExcel($file, $sheet, $rows, $cols)
{
// COM CREATE
fwrite(STDOUT, "----------------------------------------\r\n");
$excel = new COM("Excel.Application") or die ("ERROR: Unable to instantaniate COM!\r\n");
$excel->Visible = true; // so that we see the window on screen
fwrite(STDOUT, "Application name: {$excel->Application->value}\r\n") ;
fwrite(STDOUT, "Loaded version: {$excel->Application->version}\r\n");
fwrite(STDOUT, "----------------------------------------\r\n\r\n");
// DATA RETRIEVAL
$Workbook = $excel->Workbooks->Open($file) or die("ERROR: Unable to open " . $file . "!\r\n");
$Worksheet = $Workbook->Worksheets($sheet);
$Worksheet->Activate;
$i = 0;
foreach ($rows as $row)
{
$i++; $j = 0;
foreach ($cols as $col)
{
$j++;
$cell = $Worksheet->Range($col . $row);
$cell->activate();
$matrix[$i][$j] = $cell->value;
}
}
// COM DESTROY
$Workbook->Close();
unset($Worksheet);
unset($Workbook);
$excel->Workbooks->Close();
$excel->Quit();
unset($excel);
return $matrix;
}
// define inputs
$xls_path = "D:\\xampp\\htdocs\\path_to_document\\test.xls"; // input file
$xls_sheet = 1; // sheet #1 from file
$xls_rows = range(3, 20, 1); // I want extract rows 3 - 20 from test.xls with 1 row stepping
$xls_cols = array("B", "D", "E", "G"); // I want to extract columns B, D, E and G from the file
// retrieve data from excel
$data = getDataFromExcel($xls_path, $xls_sheet, $xls_rows, $xls_cols);
?>
<html>
<pre>
<?php print_r ($data);?>
</pre>
</html>