Excel文件导入

89 阅读1分钟

一.后端

    public function upload()
    {
       
        // 获取表单上传文件
        $file = request()->file('file');
        if(empty($file)){
            return json(['info'=>'请选择上传文件!','status'=>0]);
        }
        // 移动到框架应用根目录/storage/public 目录下,并修改文件名为时间戳
        $savename = \think\facade\Filesystem::disk('public')->putFile('files', $file, 'time');
        $res = \think\facade\Filesystem::disk('public');
        $info = explode('/', $savename);
        $file_extension = strtolower(pathinfo($savename, PATHINFO_EXTENSION));//获取文件扩展名
        //实例化PHPExcel类
        if ($file_extension == 'xlsx'){
            $objReader =\PHPExcel_IOFactory::createReader('Excel2007');
        } else if ($file_extension == 'xls') {
            $objReader =\PHPExcel_IOFactory::createReader('Excel5');
        }
        // $objReader =\PHPExcel_IOFactory::createReader('Excel2007');
        $obj_PHPExcel =$objReader->load($file, $encode = 'utf-8');  // 加载文件内容,编码utf-8
        $list = $obj_PHPExcel->getsheet(0)->toArray();  // 转换为数组格式
        $highestRow = $obj_PHPExcel->getSheet(0)->getHighestRow() - 1; //取得总行数
        array_shift($list);  // 删除第一个数组(标题);

        // 继续完善导入的业务逻辑
        dd($list);
    }

可能遇到的问题: 1.# 报错 Class 'think\facade\Filesystem' not found 解决: 删掉composer.lock, composer.json的require中增加:

    "topthink/think-filesystem":"^1.0"

然后执行composer install

2.路径问题, load文件不存在, 因为\think\facade\Filesystem::disk('public')的目录实际在storage下, 按照上面代码即可

postman中测试:

image.png

二.前端

            <el-upload
                ref="uploadRef"
                class="upload-demo"
                action="http://localhost:8000/index.php/admin/api/upload"
                :auto-upload="false"
                :headers="headerObj"
            >
                <template #trigger>
                <el-button type="primary">select file</el-button>
                </template>

                <el-button class="ml-3" type="success" @click="submitUpload">
                upload to server
                </el-button>

                <template #tip>
                <div class="el-upload__tip">
                    jpg/png files with a size less than 500kb
                </div>
                </template>
            </el-upload>
            ...
<script setup>         
const headerObj = {
    batoken: '4015f0fc-21c1-4c44-bc3d-1da82ffd6bf1'
}
</script>

下一步, 如何传入batoken? 搭,配置header, 定义headerObj不用return也能直接用,然后定义的方法是写在带setup的script里, 也就是和baTable的写在一起