标签归档:phpexcel

PHPExcel 之 大表格导入

PHPExcel是PHP中用来处理Excel表格最流行的库,不过在导入大表格时,耗时比较长。以下测试程序:

<?php
///
$root_dir = realpath(__DIR__.'/..');
set_include_path(implode(PATH_SEPARATOR, array(
    $root_dir . '/library',
    get_include_path(),
)));

if(file_exists($root_dir.'/vendor/autoload.php')){
    $loader = include $root_dir.'/vendor/autoload.php';
}else{
    exit("Autoload Failed. ");
}
$loader->setUseIncludePath(true);

///
require_once realpath($root_dir. '/library/PHPExcel/Classes/PHPExcel.php');

///
$params = array(
    'host' => '127.0.0.1',
    'username' =>'root',
    'password' =>'',
    'dbname' =>'test',
    'charset' =>'utf8'
);
$db = Zend_Db::factory('MYSQLI', $params);
Zend_Db_Table_Abstract::setDefaultAdapter($db);

///
header("Content-type:text/html;charset=utf-8");

///
ini_set("display_errors","1");
ini_set("max_execution_time","7200");
ini_set("memory_limit","512M");

///
///导入任务是否完成
$today = date("Y-m-d");
$has = $db->fetchRow("SELECT * FROM job WHERE job_date='".$today."' ");
if(empty($has)) {
    $db->insert("job", array("job_date"=>$today));
}else{
    $job_product = (int)$has['job_product'];
    if($job_product > 0){
        exit;
    }
}

///
///预定文件是否存在
$file = $root_dir."/jobs/data/".$today."/product";
if(file_exists($file.".xls")){
    $file = $file.".xls";
}else if(file_exists($file.".xlsx")) {
    $file = $file.".xlsx";
} else {
    exit;
}

///
///导入产品表
try {
    $s = microtime(true);
    
    $objPHPExcel = PHPExcel_IOFactory::load($file);

    $currentSheet = $objPHPExcel->getSheet(0);
    $highestRow = $currentSheet->getHighestRow();
    $highestColumm = $currentSheet->getHighestColumn();
    $highestColumm= PHPExcel_Cell::columnIndexFromString($highestColumm);
    
    //读取表头
    $header = array(
        'A'=>'SKU',
        'B'=>'产品名称',
        'F'=>'采购单价',
        'I'=>'仓库名称',
        'O'=>'供应商名称',
        'Q'=>'采购链接',
        'AF'=>'采购员'
    );
    
    // 列是从0开始的,行是以1开始的  验证表头
    $validHeader = array();
    for ($column = 0; $column < $highestColumm; $column++) {
        $columnName = PHPExcel_Cell::stringFromColumnIndex($column);
        $cellValue = $currentSheet->getCellByColumnAndRow($column, 1)->getValue();
        $validHeader[strtoupper($columnName)] = trim($cellValue);
    }
    foreach($header as $hi=>$hv) {
        if(!isset($validHeader[$hi]) || ($validHeader[$hi] !== $hv)) {
            echo '表格格式错误......';
            exit;
        }
    }
    
    $e = microtime(true);
    echo "Read Excel:".(float)($e-$s)."\n";
    
    //清空表格
    $db->query("TRUNCATE TABLE product");
    
    //开始导入
    $db->update('job', array('job_product'=>1), "job_date='".$today."'");
   
    //使用原生API批量插入 
    $mysqli = $db->getConnection();

    // 循环读取每个单元格的数据  计算填充
    for ($row = 2; $row <= $highestRow; $row++) {
        $rd = array();
        $sku = '';
        foreach($header as $key=>$vvvv) {
            $column = PHPExcel_Cell::columnIndexFromString($key)-1;
            if($key === 'A') {
                $table_key = 'sku';
                $sku = trim($currentSheet->getCellByColumnAndRow($column, $row)->getValue());
            } else if($key === 'B') {
                $table_key = 'name';
            } else if($key === 'F') {
                $table_key = 'purchase_price';
                $rd[$table_key] = round(trim($currentSheet->getCellByColumnAndRow($column, $row)->getValue()),2);
                continue;
            }else if($key === 'I') {
                $table_key = 'warehouse_name';
            }else if($key === 'O') {
                $table_key = 'supplier_name';
            }else if($key === 'Q') {
                $table_key = 'purchase_link';
            }else if($key === 'AF') {
                $table_key = 'who_purchase';
            }
            
	    $rd[$table_key] = $mysqli->real_escape_string(trim($currentSheet->getCellByColumnAndRow($column, $row)->getValue()));
            
        }
        if(empty($sku)) {
            continue;
        }
        $valuess[$sku] = "('".$rd['sku']."', '".$rd['name']."', ".$rd['purchase_price'].", '".$rd['warehouse_name']."', '".$rd['supplier_name']."', '".$rd['purchase_link']."', '".$rd['who_purchase']."')";
    }
    
    $ee = microtime(true);
    echo "Get Excel Rows:".(float)($ee-$e)."\n";
    
    //批量插入
    $chunks = array_chunk($valuess, 5000);
    foreach($chunks as $chunk) {
	   $mysqli->query("INSERT INTO product (`sku`, `name`, `purchase_price`, `warehouse_name`, `supplier_name`, `purchase_link`, `who_purchase`) values".implode(",", $chunk));
    }
    
    $eee = microtime(true);
    echo "Insert to Db:".(float)($eee-$ee)."\n";

    //完成导入或更新
    $db->update('job', array('job_product'=>2), "job_date='".$today."'");
} catch (Exception $e) {
    $db->update('job', array('job_stock'=>0), "job_date='".$today."'");
}

输出:
php import_products.php
Read Excel:49.7071270942688
Get Excel Rows:3.034592866897583
Insert to Db:0.4471859931945801
这个输出是CentOS 6.5,1G内存下的输出,如果放在Window下,Read Excel是以上数据的6倍。实际的Excel有多大呢,大概是9兆,1万5千数据,所以这个Excel读入确实差强人意,如果表格再大,PHP估计就要崩溃了(需要调大PHP每个进程所能用的内存数)。

为何读入表格那么耗时,我想大概是因为需要在内存中建立一个完整的映射,类似于浏览器解析HTML建立一个DOM数的过程一样,浏览器在遇到大数据时(比如服务端返回10M HTML代码),那么它也常常出现僵死的情况…

不过用Office Excel打开看起来就不会那么耗时。

PHPExcel之生成Excel文档实例

关于PHPExcel,可以参考:
PHPExcel 单元格格式操作对照表
PHPExcel用户文档

require_once dirname(__FILE__) . '/phpexcel/Classes/PHPExcel.php';


// General PHPExcel
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setCreator("vfeelit@qq.com")->setLastModifiedBy("vfeelit@qq.com");

$objPHPExcel->setActiveSheetIndex(0);
$objActSheet = $objPHPExcel->getActiveSheet();
$objActSheet->setTitle('采集表');

//涉及到的列
$colmns = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T');
//列宽
foreach($colmns as $cls){
	$objActSheet->getColumnDimension($cls)->setWidth(20);
}
$objActSheet->getColumnDimension('B')->setWidth(60);
$objActSheet->getColumnDimension('T')->setWidth(120);

$objActSheet->setCellValue('A1','编号');
$objActSheet->setCellValue('B1','名称');
$objActSheet->setCellValue('C1','图片');
$objActSheet->setCellValue('D1','颜色');
$objActSheet->setCellValue('E1','价格');
$objActSheet->setCellValue('F1','重量');
$objActSheet->setCellValue('G1','货号');
$objActSheet->setCellValue('H1','销售序列号');
$objActSheet->setCellValue('I1','材质');
$objActSheet->setCellValue('J1','风格');
$objActSheet->setCellValue('K1','品牌');
$objActSheet->setCellValue('L1','样式');
$objActSheet->setCellValue('M1','造型');
$objActSheet->setCellValue('N1','处理工艺');
$objActSheet->setCellValue('O1','尺寸');
$objActSheet->setCellValue('P1','电镀');
$objActSheet->setCellValue('Q1','材料');
$objActSheet->setCellValue('R1','包装');
$objActSheet->setCellValue('S1','链接');
$objActSheet->setCellValue('T1','图片');

$jj=2;
foreach($craw_items as $idx=>$data){
	//if($jj>3){ break; }
	$iidx = $data["id"];
	$imgss = $data["tupian"];
	$to = $new_base."/".$iidx;
	@mkdir($to,0777,true);
	$i=0; $the_main_pic=''; $mainimgs='';
	foreach($data["tupian"]["main"] as $igs){
		if(in_array($igs,$excude)){ continue; }
		if($i == 0){
			$the_main_pic = $to."/main_".$i.".jpg";
		}
		$mainimgs .= $igs."\r\n\r\n";
		$i++;
	}
	$i=0; $desimgs='';
	foreach($data["tupian"]["des"] as $igs){
		if(in_array($igs,$excude)){ continue; }
		$desimgs .= $igs."\r\n\r\n";
		$i++;
	}
	//行高	
	$objActSheet->getRowDimension($jj)->setRowHeight(95);

	//单元格对齐
	foreach($colmns as $c){
		$align = $objActSheet->getStyle($c.$jj)->getAlignment();
		$align->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
		$align->setVertical(PHPExcel_Style_Alignment::VERTICAL_TOP);
		$align->setWrapText(TRUE);
	}
	
	$objActSheet->getStyle('A'.$jj)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER);
	$objActSheet->setCellValue('A'.$jj,$data["id"]);

	$objActSheet->setCellValue('B'.$jj,$data["mingchen"]);
	
	//主图
	$fsig = $the_main_pic;
	if(file_exists($fsig)){
		//添加图片
		$objDrawing = new PHPExcel_Worksheet_Drawing();
		$objDrawing->setName('Product Image');			//设置名字
		$objDrawing->setDescription('');			//图片描述
			
		$objDrawing->setPath($fsig);				//图片路径
			
		//$objDrawing->setHeight(120);				//图片宽度 像素
		$objDrawing->setWidth(120);				//图片宽度 像素
		$objDrawing->setCoordinates('C'.$jj); 			//坐标 放入哪个单元格
		//$objDrawing->setOffsetX(10);				//针对单元格 水平偏移量
		//$objDrawing->setOffsetY(10);				//针对单元格 垂直偏移量
		//$objDrawing->setRotation(15);   			//旋转
		$objDrawing->setWorksheet($objActSheet);		//应用到工作表
	}else{
		$objActSheet->setCellValue('C'.$jj,"主图没有下载");	
	}	
	
	$colors = '';
	foreach($data["yanse"] as $color){
		$colors .= $color."\r\n";
	}
	$objActSheet->setCellValue('D'.$jj,$colors);
	
	$objActSheet->setCellValue('E'.$jj,$data["jiage"]);
	$objActSheet->setCellValue('F'.$jj,$data["zhongliang"]);
	$objActSheet->setCellValue('G'.$jj,$data["huohao"]);
	$objActSheet->setCellValue('H'.$jj,$data["xiaoshouxuliehao"]);
	$objActSheet->setCellValue('I'.$jj,$data["caizhi"]);
	$objActSheet->setCellValue('J'.$jj,$data["fengge"]);
	$objActSheet->setCellValue('K'.$jj,$data["pinpai"]);
	$objActSheet->setCellValue('L'.$jj,$data["yangshi"]);
	$objActSheet->setCellValue('M'.$jj,$data["zaoxing"]);
	$objActSheet->setCellValue('N'.$jj,$data["chuligongyi"]);
	$objActSheet->setCellValue('O'.$jj,$data["dchicun"]);
	$objActSheet->setCellValue('P'.$jj,$data["ddiandu"]);
	$objActSheet->setCellValue('Q'.$jj,$data["dcailiao"]);
	$objActSheet->setCellValue('R'.$jj,$data["dbaozhuang"]);
	$objActSheet->setCellValue('S'.$jj,$data["url"]);
	$objActSheet->setCellValue('T'.$jj,$mainimgs."\r\n\r\n".$desimgs);
	
	$jj++;
}
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel5');
$objWriter->save($base."/".$shop."_".$offlist.".xls");

生成一个Excel文档程序框架,在最后如果需要直接下载文档,可以改为:

	header("Content-Type: application/force-download");
	header("Content-Type: application/octet-stream");
	header("Content-Type: application/download");
	header('Content-Disposition:inline;filename="'.$outputFileName.'"');
	header("Content-Transfer-Encoding: binary");
	header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
	header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
	header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
	header("Pragma: no-cache");
	
	$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel5');
	$objWriter->save('php://output');

此文为备忘….

原创文章,转载务必保留出处。
永久链接:http://blog.ifeeline.com/1183.html

PHPExcel 单元格格式操作对照表

$B1_Style = $objActSheet->getStyle('B1');

获取单元格格式对象,如下图:
Excel单元格格式
这里面一共有6个Tab,分别对应如下:

getNumberFormat()
getAlignment()
getFont() 
getBorders()
getFill()
getProtection() 

调用举例:

$objActSheet->getStyle('B1')-> getAlignment();

每个Tab对应的辅助类在PHPExcel_Style中对应,比如要应用一个格式:

$objActSheet->getStyle('B1')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER);

以下针对6个Tab可用操作作对比:

//getNumberFormat()			
setFormatCode() 

Excel单元格格式 - 数字格式

//getAlignment()
setHorizontal() 
setVertical() 
setTextRotation() 
setWrapText() 
setShrinkToFit() 
setIndent() 

Excel单元格格式 - 对齐

//getFont()
setName() 
setBold() 
setItalic() 
setUnderline() 
setStrikethrough()
getColor() 
setSize() 
setSuperScript() 
setSubScript() 

Excel单元格格式 - 字体

//getBorders()
getLeft() 
getRight() 
getTop() 
getBottom() 
getDiagonal() 
getVertical() 
getHorizontal() 
setDiagonalDirection() 
setOutline() 

Excel单元格格式 - 边框

//getFill()
setFillType() 
setRotation() 
getStartColor() 
getEndColor() 
getStartColor() 

Excel单元格格式 - 填充

//getProtection() 
setLocked() 
setHidden() 

Excel单元格格式 - 保护

PHPExcel用户文档_部分中文

1 Spreadsheet File Formats 电子表格文件格式

PHPExcel 支持以下的文件格式:

Excel5
The Microsoft Excel™ Binary file format (BIFF5 and BIFF8) is a binary file format that was used by Microsoft Excel™ between versions 95 and 2003. The format is supported (to various extents) by most spreadsheet programs. BIFF files normally have an extension of .xls. Documentation describing the format can be found online at http://msdn.microsoft.com/en-us/library/cc313154(v=office.12).aspx or from http://download.microsoft.com/download/2/4/8/24862317-78F0-4C4B-B355-C7B2C1D997DB/[MS-XLS].pdf (as a downloadable PDF).

Excel2003XML
Microsoft Excel™ 2003 included options for a file format called SpreadsheetML. This file is a zipped XML document. It is not very common, but its core features are supported. Documentation for the format can be found at http://msdn.microsoft.com/en-us/library/aa140066%28office.10%29.aspx though it’s sadly rather sparse in its detail.

Excel2007
Microsoft Excel™ 2007 shipped with a new file format, namely Microsoft Office Open XML SpreadsheetML, and Excel 2010 extended this still further with its new features such as sparklines. These files typically have an extension of .xlsx. This format is based around a zipped collection of eXtensible Markup Language (XML) files. Microsoft Office Open XML SpreadsheetML is mostly standardized in ECMA 376
(http://www.ecma-international.org/news/TC45_current_work/TC45_available_docs.htm) and ISO 29500.

……

2 Security
3 Loading a Spreadsheet File加载电子表格文件
The simplest way to load a workbook file is to let PHPExcel’s IO Factory identify the file type and load it, calling the static load() method of the PHPExcel_IOFactory class.(最简单的加载一个工作薄文件的方法是让 PHPExcel’s IO Factory验证文件类型和加载它,通过调用PHPExcel_IOFactory类的静态方法load来实现这个过程)

$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);

The load() method will attempt to identify the file type, and instantiate a loader for that file type方法load()将试图验证文件的类型,并且会针对文件类型实例化一个装载器; using it to load the file and store the data and any formatting in a PHPExcel object 使用它来装载文件和存储任意格式的数据到一个PHPExcel对象中.
The method makes an initial guess at the loader to instantiate based on the file extension 这个方法根据文件的扩展名来初步猜测要实例化的加载器; but will test the file before actually executing the load但是在实际执行加载之前会测试文件: so if (for example) the file is actually a CSV file that has been given a .xls extension (quite a common practise)所以如果文件实际是CSV文件但是用了xls作为扩展名, it will reject the Excel5 loader that it would normally use for a .xls file那么它会拒绝使用在正常情况下为xls文件使用的Excel5加载器; and test the file using the other loaders until it finds the appropriate loader然后使用其它的装载器测试文件直到找到合适的装载器, and then use that to read the file然后使用找到的装载器读取文件.
While easy to implement in your code, and you don’t need to worry about the file type这样当在你的快速实现的代码中,你不需要担心文件的类型; this isn’t the most efficient method to load a file但是这不是一个最高效率的装载文件的方法; and it lacks the flexibility to configure the loader in any way before actually reading the file into a PHPExcel object并且在实际读取文件到一个PHPExcel对象中之前,缺乏了可以在任何情况下去配置一个装载器的灵活性。

4 Creating a Reader and Loading a Spreadsheet File 创建一个阅读器并且装载一个电子表格

If you know the file type of the spreadsheet file that you need to load如果你知道你需要装载的电子表格的文件的文件类型, you can instantiate a new reader object for that file type你可以为这种文件类型实例化一个新的阅读器对象, then use the reader’s load() method to read the file to a PHPExcel object然后使用阅读器的load()方法来读取文件到一个PHPExcel对象中. It is possible to instantiate the reader objects for each of the different supported filetype by name可实例化的阅读器对象为每个不同的被支持的文件类型的名字. However, you may get unpredictable results if the file isn’t of the right type 但是,如果文件不是给定正确的类型,你可能会获取一个不可预知的结果(e.g. it is a CSV with an extension of .xls), although this type of exception should normally be trapped 尽管这种类型的异常能正确被扑捉到.

/** Create a new Excel5 Reader **/ 
$objReader = new PHPExcel_Reader_Excel5();
// $objReader = new PHPExcel_Reader_Excel2007(); 
// $objReader = new PHPExcel_Reader_Excel2003XML(); 
// $objReader = new PHPExcel_Reader_OOCalc(); 
// $objReader = new PHPExcel_Reader_SYLK(); 
// $objReader = new PHPExcel_Reader_Gnumeric(); 
// $objReader = new PHPExcel_Reader_CSV(); 

/** Load $inputFileName to a PHPExcel Object **/ 
$objPHPExcel = $objReader->load($inputFileName);

Alternatively, you can use the IO Factory’s createReader() method to instantiate the reader object for you, simply telling it the file type of the reader that you want instantiating也可以使用IO工厂的createRead()方法实例一个阅读器对象:

$inputFileType = 'Excel5'; 
// $inputFileType = 'Excel2007'; 
// $inputFileType = 'Excel2003XML'; 
// $inputFileType = 'OOCalc'; 
// $inputFileType = 'SYLK'; 
// $inputFileType = 'Gnumeric'; 
// $inputFileType = 'CSV'; 

$inputFileName = './sampleData/example1.xls'; 

/** Create a new Reader of the type defined in $inputFileType **/ 
$objReader = PHPExcel_IOFactory::createReader($inputFileType); 

/** Load $inputFileName to a PHPExcel Object **/ 
$objPHPExcel = $objReader->load($inputFileName);

.

If you’re uncertain of the filetype, you can use the IO Factory’s identify() method to identify the reader that you need, before using the createReader() method to instantiate the reader object. 如果你不确定文件类型,在使用createReader()方法实例化阅读器对象之前,你可以使用IO工厂的identify()方法去确定你需要的阅读器(这个是最好的方法):

$inputFileName = './sampleData/example1.xls'; 

/** Identify the type of $inputFileName **/ 
$inputFileType = PHPExcel_IOFactory::identify($inputFileName); 

/** Create a new Reader of the type that has been identified **/ 
$objReader = PHPExcel_IOFactory::createReader($inputFileType); 

/** Load $inputFileName to a PHPExcel Object **/ 
$objPHPExcel = $objReader->load($inputFileName);

5 Spreadsheet Reader Options 电子表格阅读器选项
Once you have created a reader object for the workbook that you want to load, you have the opportunity to set additional options before executing the load() method.一旦你已经为一个你想加载的工作薄创建了一个阅读器对象,在执行load()方法之前,你有机会去设置附加的选项。

5.1 Reading Only Data from a Spreadsheet File 从电子表格文件中只读取数据

If you’re only interested in the cell values in a workbook, but don’t need any of the cell formatting information, then you can set the reader to read only the data values and any formulae from each cell using the setReadDataOnly() method. 如果你只对工作薄中的单元格的值感兴趣,对单元格的任何格式信息都不需要,你可以通过使用setReadDataOnly()方法来设置阅读器从单元格中仅仅读取数据值和所有公式表单。

$inputFileType = 'Excel5'; 
$inputFileName = './sampleData/example1.xls'; 

/** Create a new Reader of the type defined in $inputFileType **/ 
$objReader = PHPExcel_IOFactory::createReader($inputFileType);

/** Advise the Reader that we only want to load cell data **/ 
$objReader->setReadDataOnly(true); 

/** Load $inputFileName to a PHPExcel Object **/ 
$objPHPExcel = $objReader->load($inputFileName);

It is important to note that Workbooks (and PHPExcel) store dates and times as simple numeric values: they can only be distinguished from other numeric values by the format mask that is applied to that cell. 工作薄(和PHPExcel)存储日期和时间作为简单数字值:它们和其它数字值的区别是当它应用了格式掩码时 When setting read data only to true, PHPExcel doesn’t read the cell format masks, so it is not possible to differentiate between dates/times and numbers. 当设置为只读数据为真时,PHPExcel不会读取单元格的格式掩码,所以它不可能区分日期/时间和数字之间的不同。
The Gnumeric loader has been written to read the format masks for date values even when read data only has been set to true, so it can differentiate between dates/times and numbers; but this change hasn’t yet been implemented for the other readers. Gnumeric加载器在读取日期值是被重写要求去读取格式掩码,就算是它被为只读数据位真是时,所以就可以区分日期/时间和数字的不同; 但是这个改变对其它阅读器还没有实现(就是其它的阅读器如果设置了只读数据,那么无法区分日期时间和数字的区别)。


5.2 Reading Only Named WorkSheets from a File 从文件中只读被命名的工作表

If your workbook contains a number of worksheets, but you are only interested in reading some of those, then you can use the setLoadSheetsOnly() method to identify those sheets you are interested in reading. 如果你的工作薄包含一系列的工作表,但你只有兴趣去读取其中的一些,这样你就可以使用setLoadSheetsOnly()方法去验证那些你感兴趣读取的表格。

To read a single sheet, you can pass that sheet name as a parameter to the setLoadSheetsOnly() method. 如果只读取单个表格,你可以把表格的名字作为参数传递到setLoadSheetsOnly()方法。

$inputFileType = 'Excel5'; 
$inputFileName = './sampleData/example1.xls'; 
$sheetname = 'Data Sheet #2'; 
// $sheetnames = array('Data Sheet #1','Data Sheet #3');

/** Create a new Reader of the type defined in $inputFileType **/ 
$objReader = PHPExcel_IOFactory::createReader($inputFileType); 

/** Advise the Reader of which WorkSheets we want to load **/ 
$objReader->setLoadSheetsOnly($sheetname); 

/** Load $inputFileName to a PHPExcel Object **/ 
$objPHPExcel = $objReader->load($inputFileName);

To reset this option to the default, you can call the setLoadAllSheets() method. 为了重置这个选项到默认,你可以调用setLoadAllSheets()方法。

5.3 Reading Only Specific Columns and Rows from a File (Read Filters) 从文件中只读取指定的列和行

If you are only interested in reading part of a worksheet, then you can write a filter class that identifies whether or not individual cells should be read by the loader. 如果你只有兴趣读取工作表的一部分,你可以写一个过滤类用来是否验证单独的单元格通过加载器读取 A read filter must implement the PHPExcel_Reader_IReadFilter interface, and contain a readCell() method that accepts arguments of $column, $row and $worksheetName, and return a boolean true or false that indicates whether a workbook cell identified by those arguments should be read or not. 一个阅读器过滤器必须实现PHPExcel_Reader_IReadFilter接口,并且包含readCell()方法并且接受$column, $row and $worksheetName参数,返回true or false。

$inputFileType = 'Excel5'; 
$inputFileName = './sampleData/example1.xls'; 
$sheetname = 'Data Sheet #3'; 

/** Define a Read Filter class implementing PHPExcel_Reader_IReadFilter */ 
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(); 

/** Create a new Reader of the type defined in $inputFileType **/ 
$objReader = PHPExcel_IOFactory::createReader($inputFileType); 

/** Tell the Reader that we want to use the Read Filter **/ 
$objReader->setReadFilter($filterSubset); 

/** Load only the rows and columns that match our filter to PHPExcel **/ 
$objPHPExcel = $objReader->load($inputFileName);

This example is not particularly useful, because it can only be used in a very specific circumstance (when you only want cells in the range A1:E7 from your worksheet. A generic Read Filter would probably be more useful(更加有用的方法如下)

/** Define a Read Filter class implementing PHPExcel_Reader_IReadFilter */ 
class MyReadFilter implements PHPExcel_Reader_IReadFilter { 
private $_startRow = 0; 
private $_endRow = 0; 
private $_columns = array(); 

/** Get the list of rows and columns to read */ 
public function __construct($startRow, $endRow, $columns) { 
$this->_startRow = $startRow; 
$this->_endRow = $endRow; 
$this->_columns = $columns; 
}
public function readCell($column, $row, $worksheetName = '') { 
// Only read the rows and columns that were configured 
if ($row >= $this->_startRow && $row <= $this->_endRow) { 
if (in_array($column,$this->_columns)) { return true; } }
return false; 
}
} 
/** Create an Instance of our Read Filter, passing in the cell range **/ 
$filterSubset = new MyReadFilter(9,15,range('G','K'));
}

5.4 Combining Multiple Files into a Single PHPExcel Object
5.5. Combining Read Filters with the setSheetIndex() method to split a large CSV file across multiple Worksheets
5.6. Pipe or Tab Separated Value Files
5.7. A Brief Word about the Advanced Value Binder
When loading data from a file that contains no formatting information, such as a CSV file, then data is read either as strings or numbers (float or integer). This means that PHPExcel does not automatically recognise dates/times (such as “16-Apr-2009” or “13:30”), booleans (“TRUE” or “FALSE”), percentages (“75%”), hyperlinks (“http://www.phpexcel.net”), etc as anything other than simple strings. However, you can apply additional processing that is executed against these values during the load process within a Value Binder.
A Value Binder is a class that implement the PHPExcel_Cell_IValueBinder interface. It must contain a bindValue() method that accepts a PHPExcel_Cell and a value as arguments, and return a boolean true or false that indicates whether the workbook cell has been populated with the value or not. The Advanced Value Binder implements such a class: amongst other tests, it identifies a string comprising “TRUE” or “FALSE” (based on locale settings) and sets it to a boolean; or a number in scientific format (e.g. “1.234e-5”) and converts it to a float; or dates and times, converting them to their Excel timestamp value – before storing the value in the cell object. It also sets formatting for strings that are identified as dates, times or percentages. It could easily be extended to provide additional handling (including text or cell formatting) when it encountered a hyperlink, or HTML markup within a CSV file.
So using a Value Binder allows a great deal more flexibility in the loader logic when reading unformatted text files.

6. Error Handling
Of course, you should always apply some error handling to your scripts as well. PHPExcel throws exceptions, so you can wrap all your code that accesses the library methods within Try/Catch blocks to trap for any problems that are encountered, and deal with them in an appropriate manner.
The PHPExcel Readers throw a PHPExcel_Reader_Exception.

$inputFileName = './sampleData/example-1.xls'; 
try { 
/** Load $inputFileName to a PHPExcel Object **/ 
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName); 
} catch(PHPExcel_Reader_Exception $e) { 
die('Error loading file: '.$e->getMessage()); 
}

注意抛出异常的类型。

7. Helper Methods
You can retrieve a list of worksheet names contained in a file without loading the whole file by using the Reader’s listWorksheetNames() method; similarly, a listWorksheetInfo() method will retrieve the dimensions尺寸 of worksheet in a file without needing to load and parse the whole file.

The listWorksheetNames() method returns a simple array listing each worksheet name within the workbook:

The listWorksheetInfo() method returns a nested array, with each entry listing the name and dimensions for a worksheet:

$objReader = PHPExcel_IOFactory::createReader($inputFileType); 
$worksheetData = $objReader->listWorksheetInfo($inputFileName); 

echo '<h3>Worksheet Information</h3>'; 
echo '<ol>'; 
foreach ($worksheetData as $worksheet) { 
echo '<li>', $worksheet['worksheetName'], '<br />'; 
echo 'Rows: ', $worksheet['totalRows'], 
' Columns: ', $worksheet['totalColumns'], '<br />'; 
echo 'Cell Range: A1:', 
$worksheet['lastColumnLetter'], $worksheet['totalRows']; 
echo '</li>'; 
} 
echo '</ol>';

这个worksheetName和totalRows和totalColumns是非常有用的。