最近需要讲excel导入到php数组进行操作
就看网上说用thinkphp+phpexcel来做比较好,
之前做过用phpexcel来讲数据导出到excel, 今天反过来,要将excel导入到PHP数组里。
关键的几个步骤都没问题,比如:
1. 导入phpexcel到vendor库:class ExcelToArray {
public function __construct() {
Vendor("PHPExcel.PHPExcel");//引入phpexcel类(注意你自己的路径)
Vendor("PHPExcel.PHPExcel.IOFactory");
}
public function read($filename,$encode,$file_type){
if(strtolower ( $file_type )=='xls')//判断excel表类型为2003还是2007
{
Vendor("PHPExcel.PHPExcel.Reader.Excel5");
$objReader = PHPExcel_IOFactory::createReader('Excel5');
}elseif(strtolower ( $file_type )=='xlsx')
{
Vendor("PHPExcel.PHPExcel.Reader.Excel2007");
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
}
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($filename);
$objWorksheet = $objPHPExcel->getActiveSheet();
$highestRow = $objWorksheet->getHighestRow();
$highestColumn = $objWorksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$excelData = array();
for ($row = 1; $row <= $highestRow; $row++) {
for ($col = 0; $col < $highestColumnIndex; $col++) {
$excelData[$row][] =(string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
}
}
return $excelData;
}
}2. 实例化这个类,调用其read()方法:class PhbookAction extends Action{
public function index(){
import('ORG.Util.ExcelToArray');//导入excelToArray类
$excelUrl = "http://localhost/ui2/web/Uploads/phbook/1377180574.xlsx";
$filetype = "xlsx";
$ExcelToArray=new ExcelToArray();//实例化
//dump($excelUrl);
//dump($filetype);
$res=$ExcelToArray->read($excelUrl,"UTF-8",$filetype);
dump($res);
$this->display();
}
}结果显示:
Could not open http://localhost/ui2/web/Uploads/phbook/1377180574.xlsx for reading! File does not exist.
少了个这个,用这个试试enctype="multipart/form-data"