## phpexcel导入
# 首先下载phpexcel包放入如下文件
![](https://box.kancloud.cn/c4a49bedb88f1bd87fc41207f9457221_233x304.png)
### 在controller.php需要使用的
use PHPExcel_IOFactory;
use PHPExcel;
use PHPExcel_Shared_Date;
use PHPExcel_Cell_DataType;
###
导入功能
$yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
$orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -6) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 999));//入库单号18位
vendor("PHPExcel.PHPExcel");
$objPHPExcel = new PHPExcel();
if (! empty ( $_FILES ['file'] ['name'] ))
{
$tmp_file = $_FILES ['file'] ['tmp_name'];
$file_types = explode ( ".", $_FILES ['file'] ['name'] );
$file_type = $file_types [count ( $file_types ) - 1];
/*判别是不是.xls文件,判别是不是excel文件*/
if (strtolower ( $file_type ) != "xls"&&strtolower ( $file_type ) != "xlsx")
{
$this->error ( '不是Excel文件,重新上传' );
}
/*设置上传路径*/
$savePath = ROOT_PATH. '/public/excel/';
/*以时间来命名上传的文件*/
$str = date ( 'Ymdhis' );
$file_name = $str . "." . $file_type;
/*是否上传成功*/
if (! copy ( $tmp_file, $savePath . $file_name ))
{
$this->error ( '上传失败' );
}
}
$extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));//判断导入表格后缀格式
if($extension == 'xlsx') {
$objReader =\PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel =$objReader->load($savePath.$file_name, $encode = 'utf-8');
}else if($extension == 'xls'){
$objReader =\PHPExcel_IOFactory::createReader('Excel5');
$objPHPExcel =$objReader->load($savePath.$file_name, $encode = 'utf-8');
}
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();//取得总行数
$highestColumn = $sheet->getHighestColumn(); //取得总列数
for($i = 2; $i <= $highestRow; $i++){
$score=array();
$cell = $sheet->getCellByColumnAndRow(0, $i);
$value = $cell->getValue();
$score['create_time']=$objPHPExcel->getActiveSheet()->getCell("G".$i)->getValue();
$score['standard_time'] =$objPHPExcel->getActiveSheet()->getCell("K".$i)->getValue();
if ($cell->getDataType()==PHPExcel_Cell_DataType::TYPE_NUMERIC) {
$cellstyleformat=$cell->getStyle()->getNumberFormat(); //获取cell类型
$formatcode=$cellstyleformat->getFormatCode(); //获取cell格式代码,时间格式为mm-dd-yy
if (preg_match('/^(/[/$[A-Z]*-[0-9A-F]*/])*[hmsdy]/i', $formatcode)){
$score['create_time'] = gmdate("Y-m-d", PHPExcel_Shared_Date::ExcelToPHP($value));
$score['standard_time'] = gmdate("Y-m-d", PHPExcel_Shared_Date::ExcelToPHP($value));
}else{
$score['create_time'] = PHPExcel_Style_NumberFormat::toFormattedString($value,$formatcode);
$score['standard_time'] = gmdate("Y-m-d", PHPExcel_Shared_Date::ExcelToPHP($value));
}
}
}
### 业务逻辑自己根据项目需求去写