安装PHPEXCEL
1.安装命令:composer require phpoffice/phpexcel
引入
- 在使用时,需要引入classes目录下的PHPExcel.php的PHPExcel类以及classes\PHPExcel\IOFactory.php的PHPExcel_IOFactory类。
- 如果使用thinkphp5.1框架,则直接use即可
use PHPExcel_IOFactory;
use PHPExcel;
我这里使用的TP3.2
vendor('PHPExcel.PHPExcel');
vendor('PHPExcel.PHPExcel_IOFactory');
代码
/**
* 导入excel数据
*/
public function excelAction(){
$file = $_FILES['excel_file']; //获取文件
header("Content-type:text/html;charset=utf-8");
set_time_limit(0);
vendor('PHPExcel.PHPExcel');
vendor("PHPExcel.PHPExcel.Shared.Date");
$upload = new \Think\Upload();// 实例化上传类
$upload->maxSize = 3145728;// 设置附件上传大小
$upload->autoSub = false;
$upload->exts = array('xlsx', 'xls', 'csv');// 设置附件上传类型
$upload->rootPath = __ROOT__ . 'Public/Upload/excel/'; // 设置附件上传根目录
// 上传单个文件
$info = $upload->uploadOne($file);
if (!$info) {// 上传错误提示错误信息
throw new Exception($upload->getError());
} else {// 上传成功 获取上传文件信息
$file_name = __ROOT__ . 'Public/Upload/excel/' . $info['savepath'] . $info['savename'];
}
$type = $info['ext'];
if ($type == 'xls') {
$objReader = \PHPExcel_IOFactory::createReader('Excel5');
$objPHPExcel = $objReader->load($file_name, $encode = 'utf-8');
} elseif ($type == 'xlsx') {
$objReader = \PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load($file_name, $encode = 'utf-8');
} elseif ($type == 'csv') {
$objReader = \PHPExcel_IOFactory::createReader('CSV')
->setDelimiter(',')
->setInputEncoding('GBK')
->setEnclosure('"')
// ->setLineEnding("\r\n") //报错
->setSheetIndex(0);
$objPHPExcel = $objReader->load($file_name);
}
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow(); // 取得总行数
$highestColumn = $sheet->getHighestColumn(); // 取得总列数
//开启事务
$row_str = array('A','B','C','D','E','F','G');
$row_count = count($row_str);
//组数据 数据库的字段
$data_str = array('department','process','content','source','storage','custodian','position');
$error = '';
$error_save = '';
for ($i = 4; $i <= ($highestRow-1); $i++)//这个地方根据需要,一般第一行是名称,所以从第二行开始循环,也可以从第一行开始
{
//数据库字段和excel列相对应
$data_start = 0;
$sava_data = array();
for ($r = 0;$r<$row_count;$r++){
$sava_data[$data_str[$data_start]] = (string)$objPHPExcel->getActiveSheet()->getCell("$row_str[$r]". $i)->getValue();
$data_start++;
}
if (!in_array("",$sava_data)){
//判断是否存在,存在则修改
$replace = M('Knowledge')->where(['content'=>$sava_data['content']])->find();
if ($replace){
$result_rep = M('Knowledge')->where(['id'=>$replace['id'],'f_id'=>0])->save($sava_data);
if ($result_rep){
$error_save .= $i.',';
}
continue 1;
}
//添加
$result = M('Knowledge')->add($sava_data);
if (!$result){
$error .= $i.',';
}
}else{
$error .= $i.',';
}
}
if ($error_save != ''){
$error_save .= ' 行修改成功';
}
if ($error != ''){
$error .= ' 行添加失败';
}
//删除文件
unlink($file_name);
if ($error != '' || $error_save != ''){
$this->errorReturn($error_save.$error);
}
$this->successReturn('添加成功');
}