[BD2.0] 初步完成文件导入

71 阅读1分钟

准备工作

  • 1.首先下载安装模块市场的数据导入, 它会自动安装phpoffice
"phpoffice/phpspreadsheet": "^1.29.0"
"topthink/think-filesystem": "^1.0",

image.png

前端页面

  • 1.封装TS
import { useAdminInfo } from "../stores/adminInfo"
import { getUrl } from '/@/utils/axios'
const adminInfo = useAdminInfo()
const url = getUrl()

// 商品导入
export const importGoods = url + '/index.php/admin/goods/importGoods?batoken=' + adminInfo.getToken()
  • 2.前端页面
<template>
    <div class="centered-container">
      <el-form :model="form">
        <el-form-item label="备注">
          <el-input v-model="form.remark" autocomplete="off" />
        </el-form-item>
        <el-form-item label="文件">
          <el-upload ref="upload" :action="importGoods" :auto-upload="false" :data="form" :on-success="onSuccess">
            <el-button type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <span class="dialog-footer">
        <el-button type="warning" @click="submitUpload">开始导入</el-button>
        <el-button>清空</el-button>
      </span>
    </div>
  </template>
  
  <script setup lang="ts">
  import { useAdminInfo } from '/@/stores/adminInfo';
  import { reactive, ref} from 'vue';
  
  import type { UploadInstance } from 'element-plus';
  import { ElNotification } from 'element-plus';
  import {importGoods} from '/@/api/controllerUrls'
  
  const upload = ref<UploadInstance>();
  
  const submitUpload = () => {
    upload.value!.submit();
  };
  const form = reactive({
    remark: ''
  });

  // 上传成功的回调
  const onSuccess = (res: any) => {
    console.log(res);
    if (res.code === 1) {
      ElNotification({message: '导入成功'});
    } else {
      ElNotification({message: res.msg});
    }
  };
  </script>
  
 <style scoped>
/* 将元素居中 */
.centered-container {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 50%; /* 宽度占用50% */
    margin: 100px auto; /* 水平居中 */
}
</style>

控制器

<?php

namespace app\admin\controller;

use ba\Filesystem;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\facade\Db;
use Throwable;
use app\common\controller\Backend;

class Goods extends Backend
{
    
    /**
     * 商品导入
     */
    public function importGoods()
    {
        $file = $this->request->file('file');
        if (!$file) {
            $this->error('请上传导入数据!');
        }
        // 读取xls文件内容
        // $filePath    = Filesystem::fsFit(public_path() . $file);
        $filePath = $file->getPathname();
        $spreadsheet = IOFactory::load($filePath);
        $sheet       = $spreadsheet->getSheet(0);
        $data        = $sheet->toArray();
        if (empty($data)) {
            $this->error('文件内容不能为空!');
        }
        array_shift($data); // 去掉表头
        $memberModel = new Member();

        Db::startTrans();
        try {
            // 执行数据库操作
            foreach ($data as $item) {
                $seller_id = $memberModel->getSellerId(trim($item[2]));
                if (! $seller_id) {
                    throw new \Exception("销售不存在" . $item[2]);
                }
                $insert = [
                    'code'    => trim($item[0]),
                    'title' => trim($item[1]),
                    'seller_id' => $seller_id,
                    'weight'    => trim($item[3])
                ];
                $this->model->create($insert);
            }

            // 如果所有操作都成功,提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 如果出现异常,回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success("导入成功");
    }

}