实现导入功能需用到插件中的读取文件功能
官方文档:https://xlswriter-docs.viest.me/zh-cn/reader
本文使用vue(element插件) + tp6
前端代码
<template>
<div>
<el-upload
ref="upload"
class="upload-demo"
name="files"
:action="file_url"
:before-upload="BeforeUpload"
:on-change="changeFiles"
:limit="1"
:file-list="fileList"
:on-exceed="handleExceed"
:data="file_data"
accept=".xlsx"
>
<el-link>点击导入</el-link>
<!-- <template #tip>
<div class="el-upload__tip">请先下载左侧模板</div>
</template> -->
</el-upload>
</div>
</template>
<script>
export default {
data(){
return {
file_url: 'http://127.0.0.1/tp6/public/import_xls_data', // 文件上传地址
file_data: {},
fileList: [],
}
},
methods: {
// 文件上传之前
BeforeUpload(file){
// console.log('上传之前:', file);
var validate_type = ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
if(validate_type.indexOf(file.type) == -1){
this.$message.error('您上传的文件错误,请重新上传!');
return false;
}
},
// 文件上传
changeFiles(file, fileList) {
if(file.status == 'success'){
var res = file.response;
console.log(res);
if (res.state) {
this.$message.success("数据导入成功!");
this.fileList = [];
} else {
this.$message.error(res.message);
}
}
},
// 文件超出
handleExceed(files, fileList) {
this.$refs.upload.clearFiles()
this.$refs.upload.handleStart(files[0])
this.$refs.upload.submit()
this.form_result = false;
},
}
}
</script>
后端代码
public function import_xls_data(){
## 上传文件错误或者文件验证不通过时,都会抛出异常,所以要使用try来捕捉异常
try {
// 获取上传的文件,如果有上传错误,会抛出异常
$file = \think\facade\Request::file('files');
// 如果上传的文件为null,手动抛出一个异常,统一处理异常
if (null === $file) {
return show(false, '请上传文件');
}
$file_name = 'datas.xlsx';
$savename = \think\facade\Filesystem::disk('public')->putFileAs('xls_data', $file, $file_name);
$fiels_info = explode('/', $savename);
$res = $this->excel_data('./uploads/'.$fiels_info[0], $fiels_info[1]);
// if($res['state']){
// return show(true, '数据导入成功!');
// }else{
// return show(false, $res['message']);
// }
return show(true, '', $res);
} catch (\Exception $e) { ## 如果上传时有异常,会执行这里的代码,可以在这里处理异常
return show(false, $e->getMessage());
}
}
public function excel_data($path, $file_name){
// 读取文件内容
$ex_config = ['path' => $path];
$excel = new \Vtiful\Kernel\Excel($ex_config);
$data = $excel->openFile($file_name)
->openSheet('Sheet1', \Vtiful\Kernel\Excel::SKIP_EMPTY_ROW) // 只读取sheet1中内容,并忽略空白行
->setSkipRows(0) // 跳过第一行
->setType([
1 => \Vtiful\Kernel\Excel::TYPE_STRING,
3 => \Vtiful\Kernel\Excel::TYPE_STRING,
5 => \Vtiful\Kernel\Excel::TYPE_STRING,
6 => \Vtiful\Kernel\Excel::TYPE_STRING,
7 => \Vtiful\Kernel\Excel::TYPE_TIMESTAMP,
8 => \Vtiful\Kernel\Excel::TYPE_TIMESTAMP,
])
->getSheetData();
// return $data;
if(count($data) > 0){
foreach($data as &$val){
$val[7] = date('Y-m-d', $val[7]);
$val[8] = date('Y-m-d', $val[8]);
// 处理数据...
}
// 将处理好的数据,写入数据表...
$res = Db::name('user')->insertAll($data);
return $res;
}else{
return array('state'=>false, 'message'=>'请填写信息后重新上传!');
}
}