php layui实现ajax上传excel表格到系统中,下面小编为您讲解实现方法:
前端代码:
<div class="layui-input-inline">
<div class="layui-upload">
<button type="button" name="myfile" class="layui-btn" id="myfile"><i class="layui-icon"></i>上传文件</button>
</div>
</div>
<script type="text/javascript">
layui.use(['form','upload'],function(){
var form=layui.form;
var upload=layui.upload;
upload.render({ //允许上传的文件后缀
elem: '#myfile'
,url: "{:url('import')}"
,accept: 'file' //普通文件
,exts: 'xls|excel|xlsx'
,done: function(res){
if(res == true){
layer.msg('开通成功',{icon:6});
}else{
layer.msg('解析失败',{icon:5});
}
}
});
});
</script>
PHP端代码:
public function import()
{
//接收上传文件
$file = $_FILES;
if (!$file) {
return '缺少file';
}
$filename = $file['file']['tmp_name'];
//调用导入excel方法
$data = Base::instance()->importExcel($filename);
$result_data = [];
foreach ($data as $k => $v){
if ($k === 0){
}else{
foreach ($v as $kk => $vv){
$result_data[$k-1][$data[0][$kk]] = $vv;
}
}
}
}
base类(php需安装phpexcel扩展):
class Base extends Service
{
//excel文件导入
public function importExcel($file){
include(__DIR__.'/../../../vendor/PHPExcel/Classes/PHPExcel.php');
$cacheMethod = \PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;
$cacheSettings = array('memoryCacheSize' => '16MB');
\PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);//文件缓存
//当前空间不用\,非当前空间要加\
$PHPExcel = new \PHPExcel();//创建一个excel对象
$PHPReader = new \PHPExcel_Reader_Excel2007(); //建立reader对象,excel—2007以后格式
if (!$PHPReader->canRead($file)) {
$PHPReader = new \PHPExcel_Reader_Excel5();//建立reader对象,excel—2007以前格式
if (!$PHPReader->canRead($file)) {
$msg = '不是excel格式文件';
//$this->apiReturn(303,$msg);
return '不是excel格式文件';
}
}
$PHPExcel = $PHPReader->load($file); //加载excel对象
$sheet = $PHPExcel->getSheet(0); //获取指定的sheet表
$rows = $sheet->getHighestRow();//行数
$cols = $sheet->getHighestColumn();//列数
$data = array();
for ($i = 1; $i <= $rows; $i++){ //行数是以第1行开始
$count = 0;
for ($j = 'A'; $j <= $cols; $j++) { //列数是以A列开始
$value = $sheet->getCell($j . $i)->getValue();
if ($value) {
$data[$i - 1][$count] = (string)$sheet->getCell($j . $i)->getValue();
$count += 1;
}
}
}
return $data;
}
}