【php】PHPExcel文件如何导入成数组(选择指定的列)?
使用phpexcel导入成数组,但是目前无法选中指定的列导入(目前是全部列都会导入),希望只导入A列和C列的数据,求解?
以下代码输出效果
<?phpheader("Content-Type:text/html;charset=utf-8");
$dir=dirname(__FILE__);//找到当前脚本所在路径
require $dir."/PHPExcel/PHPExcel/IOFactory.php";//引入读取excel的类文件
$filename=$dir."/lang.xlsx";
$fileType=PHPExcel_IOFactory::identify($filename);//自动获取文件的类型提供给phpexcel用
$objReader=PHPExcel_IOFactory::createReader($fileType);//获取文件读取操作对象
$objReader->setLoadSheetsOnly($sheetName);//只加载指定的sheet
$objPHPExcel=$objReader->load($filename);//加载文件
$sheetCount=$objPHPExcel->getSheetCount();//获取excel文件里有多少个sheet
foreach($objPHPExcel->getWorksheetIterator() as $sheet){//循环取sheet
foreach($sheet->getRowIterator() as $row){//逐行处理
if($row->getRowIndex()<2){
continue;
}
foreach($row->getCellIterator() as $cell){//逐列读取
$data=$cell->getValue();//获取单元格数据
echo $data." ";
}
echo '<br/>';
}
echo '<br/>';
}
exit;
?>
目前excel的数据格式如下,如何导入成图二的效果?
图(1)
图(2)
回答
遍历后,重新赋值一次
在遍历行数据时通过cell获取当前单元格的列,加一个if 判断,如果不是第二列再获取 value
$dir=dirname(__FILE__);//找到当前脚本所在路径 require $dir."/PHPExcel/PHPExcel/IOFactory.php";//引入读取excel的类文件
$filename=$dir."/lang.xlsx";
$objReader = PHPExcel_IOFactory::createReader('Excel5');
$objPHPExcel = $objReader->load($file_name,$encode='utf-8');
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow(); // 取得总行数
$highestColumn = $sheet->getHighestColumn(); // 取得总列数
for($i=1;$i<=$highestRow;$i++)
{
$data=array();
$data['A']=$objPHPExcel->getActiveSheet()->getCell("A".$i)->getValue();
$data['A']=$this->geshihua($data['A']);
$data['B']=$objPHPExcel->getActiveSheet()->getCell("B".$i)->getValue();
$data['B']=$this->geshihua($data['B']);
$data['C']=$objPHPExcel->getActiveSheet()->getCell("C".$i)->getValue();
$data['C']=$this->geshihua($data['C']);
$data['D']=$objPHPExcel->getActiveSheet()->getCell("D".$i)->getValue();
$data['D']=$this->geshihua($data['D']);
$data['E']=$objPHPExcel->getActiveSheet()->getCell("E".$i)->getValue();
$data['E']=$this->geshihua($data['E']);
$data['F']=$objPHPExcel->getActiveSheet()->getCell("F".$i)->getValue();
$data['F']=$this->geshihua($data['F']);
$data['G']=$objPHPExcel->getActiveSheet()->getCell("G".$i)->getValue();
$data['G']=$this->geshihua($data['G']);
$data['H']=$objPHPExcel->getActiveSheet()->getCell("H".$i)->getValue();
$data['H']=$this->geshihua($data['H']);
$data['I']=$objPHPExcel->getActiveSheet()->getCell("I".$i)->getValue();
$data['I']=$this->geshihua($data['I']);
$data['J']=$objPHPExcel->getActiveSheet()->getCell("J".$i)->getValue();
$data['J']=$this->geshihua($data['J']);
$data['K']=$objPHPExcel->getActiveSheet()->getCell("K".$i)->getValue();
$data['K']=$this->geshihua($data['K']);
if(trim($data['A'])<>''){
$_data[]=$data;
}
}
$_data就是遍历的数组,你看着模仿就可以ABCD代表对应的行
以上是 【php】PHPExcel文件如何导入成数组(选择指定的列)? 的全部内容, 来源链接: utcz.com/a/106695.html