PHPExcel类下载:
链接:https://share.weiyun.com/SLMllhrv 密码:5h7wsh
demo.php
<?php
//返回数据
$retAjax = array('code'=>200, 'data'=>'');
//加载函数库
require_once "functions.php";
//搜索关键词
$keyword = isset($_POST['name']) ? trim($_POST['name']) : '';
//excel文件地址
$filepath = "./annex/2021_jgcx.xlsx";
//获取excel值
$data = importExcel($filepath, 'xlsx', true);
if ( !empty($data) && !empty($keyword) && !is_shield_keyword($keyword) )
{
unset($data[0]);
$data = array_merge($data); //重组下标
//筛选结果
$result = search_key($data, $keyword);
$retAjax['data'] = $result;
}
echo json_encode($retAjax);
?>
funcitons.php
<?php
/* 函数库 */
/**
* @package 读取Excel文件并返回数组
* @author 自然
* @e-mail c1516k@163.com
* @date 2020-12-23
* @param 变量注释
* @param string $file [文件路径]
* @param string $file_type [文件类型]
* @param boole $is_title [是否存在标题,存在则删除,默认不删除]
* @return Array
*/
function importExcel($file = '', $file_type = 'xls', $is_title = false)
{
require_once "./library/PHPExcel.php";
require_once "./library/PHPExcel/IOFactory.php";
switch ($file_type)
{
case 'xls':
$type = 'Excel5';
break;
case 'xlsx':
$type = 'Excel2007';
break;
}
$objReader = \PHPExcel_IOFactory::createReader($type);
$obj_PHPExcel =$objReader->load($file, $encode = 'utf-8'); // 加载文件
$excel_array = $obj_PHPExcel->getsheet(0)->toArray(); //转换为数组格式
if ($is_title) array_shift($excel_array); //删除第一个数组(标题);
foreach ($excel_array as $key => $value) {
if (empty($value[0])) unset($excel_array[$key]);
}
return $excel_array;
}
/**
* @package 关键词搜索数组
* @author 自然
* @e-mail c1516k@163.com
* @date 2021-12-14
* @param 变量注释
* @param arr $data 被搜索的数组(一维数组)
* @param string $keywords 关键词
* @return Array
*/
function search_key(array $data, $keywords)
{
$arr = array();
foreach($data as $key => $values)
{
foreach ($values as $v)
{
if (strstr( $values[1] , $keywords ) !== false ) {
$v = explode("\n",$v);
$res = array('title'=>$values[1],'data'=>$v);
$arr[$key] = $res;
}
}
}
return $arr;
}
//是否是屏蔽关键词
function is_shield_keyword($keywords)
{
$shield_arr = array('有限公司','科技有限公司','咨询有限公司','培训学校','职业培训学校','心理咨询');
$res = array_search($keywords, $shield_arr) !== FALSE ? true : false;
return $res;
}
?>