每次循环刷新变量值

Refresh variable value each loop

我在 PHP 中上传多个 Excel 文件时遇到了麻烦。我正在使用 for 循环来获取每个文件中特定单元格中的数据,但我得到的值与第一个文件的值相同。它没有为每个文件获取值,而是停留在第一个值上。

我试图从每个文件中的单元格 'N14' 中获取值。

<?php
include 'Classes/PHPExcel.php';
include 'Classes/PHPExcel/IOFactory.php';


$total=count($_FILES['files']['name']);
for($x=0;$x<$total;$x++){
    $file = $_FILES['files']['tmp_name'][$x];
    $fileName = $_FILES['files']['name'][$x];
    $load = PHPExcel_IOFactory::load($file);
    $num=$load->getSheetCount() ;

    echo $fileName."    ";

    $sheets =$load->setActiveSheetIndex(0);
    $sheets = $load->getActiveSheet()->toArray(null,true,true,true);

    $i = 1;
    foreach ($sheets as $sheet) {
        $c=$sheet['N'];
        if($i==14){echo $c."</br>";break;}

        $i++;
    }   
}

输出:

proses 15 Januari 2017.xlsx **308060**

proses 16 Januari 2017.xlsx **308060**

proses 17 Januari 2017.xlsx **308060**

有人可以向我解释为什么它重复第一个的值吗?

更简单的方法是 get the cell value directly:

<?php
include 'Classes/PHPExcel.php';
include 'Classes/PHPExcel/IOFactory.php';


$total = count($_FILES['files']['name']);

for($x = 0; $x < $total; $x++) {
    $file     = $_FILES['files']['tmp_name'][$x];
    $fileName = $_FILES['files']['name'][$x];
    $load     = PHPExcel_IOFactory::load($file);

    $sheet = $load->getSheet(0);
    $i = $sheet->getCell("N14")->getCalculatedValue();

    echo "$fileName : $i<br/>";
}

至于为什么你的原始代码不起作用,不知道涉及的文件很难说。看起来它应该可以工作,只要文件都具有不同的值。但是将Excel文件加载到一个数组中(库内存中已经有一个副本,然后你再制作一个)然后无缘无故地循环遍历前14行是非常低效的。

如果您的工作表有名称(比如 "sheetName"),您可以尝试:

$reader = PHPExcel_IOFactory::createReader("Excel2007");
$excelWorkbook = $reader->load($file);
$sheet = $excelWorkbook->getSheetByName("sheetName");
$c= $sheet->getCell("N14")->getValue();

这可能会使起点更简单。