phpexcel选择表和列

时间:2011-07-20 19:38:24

标签: php memory phpexcel

我目前正在进行一项任务,我需要循环浏览一个巨大的excel文件。我正在使用phpexcel完成这项工作。我在这个项目中有两个问题

  1. 问题是我加载文件时出现内存已满错误。甚至 在使用setActiveSheetIndex('')函数时,我正在尝试阅读 代码逐页,但目前我不能。

  2. 我需要只选择选定的列而不是整行,I 已经尝试实现phpexcel用户指南中显示的示例但是 没有这样做,我必须实现这个来减少 处理时间。

  3. 以下是我正在使用的代码

    set_time_limit (6000);
    require_once('classes/phpexcel.php');
    $objReader = PHPExcel_IOFactory::createReader('Excel2007');
    $objReader->setReadDataOnly(true);
    $objPHPExcel = $objReader->load("2.xlsx");
    $objWorksheet = $objPHPExcel->setActiveSheetIndex('0') ;
    $i=0;$dum=false;$sum=0;
    foreach ($objWorksheet->getRowIterator() as $row) 
    {
    $cellIterator = $row->getCellIterator();
    $cellIterator->setIterateOnlyExistingCells(false); 
    if($dum) //to ignore first cell 
    {                                                  .
    foreach ($cellIterator as $cell) 
    {    if($i==2||$i==3||$i==4||$i==9)
        {
              if($i==2)
              {
              $value[$i]=$cell->getValue();
              $num1=$value[$i]; // get the starting date and time
              }
              if($i==3)
              {
              $value[$i]=$cell->getValue();
              $num2=$value[$i]; // get the ending date and time
              }
              if($i==4)
              { 
              $value[$i]=$cell->getValue(); 
              $asd=preg_split('#(?=\d)(?<=[a-z])#i',$value[$i] ); //convert strings as asd12321 to asd , 12321
              $value[$i]=$asd[1]; // to read only digit
              }
              if($i==9)
              {
              $value[$i]=$cell->getValue(); // read a string
              $value[$i+1]=$num2-$num1; //to take diff in minutes between the two 
              }
    
        }$i++;
    
    }$i=0;
    
    $con =  mysql_connect("localhost","root","");
    if (!$con)
    {$value[0]=$value[2];
     die('Could not connect: ' . mysql_error());
    }mysql_select_db("mobilink", $con);
    $sql="INSERT INTO my query ....";
    if (!mysql_query($sql,$con))
    {
    die('Error: ' . mysql_error());
    }
    $sum++;
    
    
     mysql_close($con);
       }
     $dum=true;
    
    }
    

    我必须只读取特定列,因为我在文件中总共有26列,而我只需要4列。帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

在文档中

http://phpexcel.codeplex.com/downloads/get/504328

在第4.3页第7节中,它介绍了如何选择特定列而不是整个电子表格。

class MyReadFilter implements PHPExcel_Reader_IReadFilter {

 public function readCell($column, $row, $worksheetName = '') { 
// Read rows 1 to 7 and columns A to E only 
if ($row >= 1 && $row <= 7) {
 if (in_array($column,range('A','E'))) {
 return true; 
   }
 } 
  return false;
 } 
} 
/** Create an Instance of our Read Filter **/

 $filterSubset = new MyReadFilter();
 [...]

希望它有所帮助。