导入excel文件

上传 excel 文件导入数据库

1 前端 html 代码部分

<div class="layui-form-item layui-inline">
    <button class="layui-btn layui-btn-primary"><i class="layui-icon">&#xe615;</i> 搜 索</button>

    <!-- 上传按钮放在搜索按钮后面,可根据自己的需求调整位置 -->
    <!--{if auth("import")}-->
    <button class='layui-btn layui-btn-sm layui-btn-active' data-file data-type="xlsx,xls" data-uptype='local' data-field="topic_excel">上传题库</button>
    <!--{/if}-->
</div>

data-uptype 设置上传文件存储方式,这里设置的是local,后端读取文件内容会用到 (未测试云存储方式)

2 前端 js 代码部分
{block name='script'}
<script>
    window.form.render();
    $(function () {
        /*!文件上传过程事件处理 */
        $('[data-file]').on('upload.done', function (file, obj) {
            // obj.file 当前完成的文件对象
            // obj.data 当前文件上传后服务端返回的内容
            console.log(file);
            console.log(obj);
            /*! 提交数据并返回结果 */
            $.form.load('{:url("import")}', {file: obj.data.url}, 'post');
        })
    });
</script>
{/block}

文件上传js部分可参考:前端-文件上传

data-uptype 设置上传文件存储方式,这里设置的是local,后端读取文件内容会用到 (未测试云存储方式)

3 后端代码部分

composer require phpoffice/phpspreadsheet


	use \PhpOffice\PhpSpreadsheet\IOFactory;


	public function import()
    {
        $file = $this->app->request->post('file');
        if (!$file) $this->error('文件不能为空');
        $file = '.' . str_replace($this->app->request->domain(), '', $file);
        //表格字段对应
        $cellName = [
            'A' => 'no',//序号
            'B' => 'name',//题目
        ];
        //加载文件
        $spreadsheet = IOFactory::load($file);

        $sheet = $spreadsheet->getActiveSheet();               // 获取表格
        $highestRow = $sheet->getHighestRow();                 // 取得总行数
        $sheetData = [];
        for ($row = 2; $row <= $highestRow; $row++) {          // $row表示从第几行开始读取
            foreach ($cellName as $cell => $field) {
                $value = $sheet->getCell($cell . $row)->getValue();
                $value = trim($value);
                $sheetData[$row][$field] = $value;
            }
        }
        $sheetData = array_values($sheetData);
        $count = count($sheetData);
        //TO DO 入库
        $this->app->db->name($this->table)->data($sheetData)->strict(false)->insertAll();
        $this->success('导入成功');
    }

简单demo仅供参考,多sheet、表格格式等未做校验,可根据自己要求完善

如有更可行的方式,可随时联系 L ,如有不严谨或者不规范的地方欢迎指正。

Last Updated:
Contributors: 邹景立