
如图,在Excel导入插件中,当上传Excel表时,如何判断已有表中,指定某字段的重复数据,最终该数据只导入新数据,并提示重复数据数量与明细?附相关代码。
public function import() {
if (IS_POST) {
$table = $this->input->post('table');
if ($_FILES["file"]["error"] > 0) {
$this->admin_msg('文件上传失败: '.$_FILES["file"]["error"]);
} else {
$ext = substr(strrchr($_FILES["file"]["name"], '.'), 1);
$file = APPPATH.'cache/'.SYS_TIME.'.'.$ext;
if (move_uploaded_file($_FILES["file"]["tmp_name"], $file)) {
if (!is_file($file)) {
$this->admin_msg('上传文件移动失败');
}
// 提交参数
$ids = $this->input->post('ids');
$post = $this->input->post('data');
/** Include PHPExcel */
require APPPATH.'Classes/Init.php';
//建立reader对象
$PHPReader = new PHPExcel_Reader_Excel2007();
if(!$PHPReader->canRead($file)){
$PHPReader = new PHPExcel_Reader_Excel5();
if(!$PHPReader->canRead($file)){
$this->admin_msg('不是Excel文件');
}
}
$sheet = max(0, intval($post['id']) - 1);
$PHPExcel = $PHPReader->load($file); //建立excel对象
$currentSheet = $PHPExcel->getSheet($sheet); //**读取excel文件中的指定工作表*/
$allColumn = $currentSheet->getHighestColumn(); //**取得最大的列号*/
$allRow = $currentSheet->getHighestRow(); //**取得一共有多少行*/
$data = array();
for($rowIndex=1;$rowIndex<=$allRow;$rowIndex++){ //循环读取每个单元格的内容。注意行从1开始,列从A开始
for($colIndex='A';$colIndex<=$allColumn;$colIndex++){
$addr = $colIndex.$rowIndex;
$cell = $currentSheet->getCell($addr)->getValue();
if($cell instanceof PHPExcel_RichText){ //富文本转换字符串
$cell = $cell->__toString();
} elseif (is_float($cell)) {
$time = PHPExcel_Shared_Date::ExcelToPHP($cell);
if ($time > 0) {
$cell = gmdate("Y-m-d H:i:s", $time);
}
}
$data[$rowIndex][$colIndex] = $cell;
}
}
if (!$data) {
@unlink($file);
$this->admin_msg('Excel文件解析数据失败');
}
$count = 0;
// 数据处理
foreach ($data as $i => $t) {
// 验证行数
if ($post['ks'] && $i<$post['ks']) {
continue;
}
// 验证不能为空
$yz = 0;
$insert = array();
foreach ($ids as $id) {
if (is_null($t[$post[$id]['excel']])) {
$yz = 1;
continue;
}
$value = $t[$post[$id]['excel']];
if (isset($post[$id]['func']) && $post[$id]['func'] && function_exists($post[$id]['func'])) {
$value = call_user_func($post[$id]['func'], $value);
}
$insert[$id] = $value;
}
if ($yz) {
continue;
}
if ($insert) {
$this->db->insert($table, $insert);
$count ++;
}
}
@unlink($file);
$this->admin_msg('共导入'.$count.'个', '', 1);
} else {
@unlink($file);
$this->admin_msg('上传失败');
}
}
}
$this->template->assign(array(
'table' => $_GET['table'],
'abcd' => str_split(strtoupper('abcdefghijklmnopqrstuvwxyz'), 1),
));
$this->template->display('import.html');
}
