vue 实现 excel 的导入功能

161 篇文章 16 订阅

一 后端

1 创建监听器

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baiyee.sdgt.cmn.mapper.DictMapper;
import com.baiyee.sdgt.model.cmn.Dict;
import com.baiyee.sdgt.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;

public class DictListener extends AnalysisEventListener<DictEeVo> {
    private DictMapper dictMapper;

    public DictListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    // 一行一行读取
    @Override
    public void invoke(DictEeVo dictEeVo, AnalysisContext analysisContext) {
        // 调用方法添加数据库
        Dict dict = new Dict();
        BeanUtils.copyProperties(dictEeVo, dict);
        dictMapper.insert(dict);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
    }
}

2 接口

// 导入数据字典
void importDictData(MultipartFile file);

3 实现

// 导入数据字典
@Override
@CacheEvict(value = "dict", allEntries = true)
public void importDictData(MultipartFile file) {
    try {
        EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(baseMapper)).sheet().doRead();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

4 控制器

// 导入数据字典
@PostMapping("importData")
public Result importDict(MultipartFile file) {
    dictService.importDictData(file);
    return Result.ok();
}

二 前端

1 页面部分

<template>
  <div class="app-container">
    <!-- 导出功能 -->
    <div class="el-toolbar">
      <div class="el-toolbar-body" style="justify-content: flex-start;">
        <!-- 导出功能 -->
        <el-button type="text" @click="exportData">
          <i class="fa fa-plus" /> 导出
        </el-button>
        <!-- 导入功能 -->
        <el-button type="text" @click="importData">
          <i class="fa fa-plus" /> 导入
        </el-button>
      </div>
    </div>
    <!-- 列表功能 -->
    <el-table
      :data="list"
      style="width: 100%"
      row-key="id"
      border
      lazy
      :load="getChildrens"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="名称" width="230" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="编码" width="220">
        <template slot-scope="{row}">{{ row.dictCode }}</template>
      </el-table-column>
      <el-table-column label="值" width="230" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.value }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
    </el-table>
    <!-- 导入弹框 -->
    <el-dialog title="导入" :visible.sync="dialogImportVisible" width="480px">
      <el-form label-position="right" label-width="170px">
        <el-form-item label="文件">
          <el-upload
            :multiple="false"
            :on-success="onUploadSuccess"
            :action="'http://localhost:8202/admin/cmn/dict/importData'"
            class="upload-demo"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传Excel文件,且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogImportVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dict from "@/api/dict";
export default {
  data() {
    return {
      list: [], // 数据字典列表数组
      listLoading: true,
      dialogImportVisible: false
    };
  },
  created() {
    this.getDictList(1);
  },
  methods: {
    // 弹出导入弹窗
    importData() {
      this.dialogImportVisible = true;
    },

    // 导入成功后的提醒
    onUploadSuccess(response, file) {
      this.$message.info("上传成功");
      this.dialogImportVisible = false;
      this.getDictList(1);
    },

    // 数据字典列表
    getDictList(id) {
      dict.dictList(id).then(response => {
        this.list = response.data;
      });
    },
    getChildrens(tree, treeNode, resolve) {
      dict.dictList(tree.id).then(response => {
        resolve(response.data);
      });
    },
    // 导出功能
    exportData() {
      window.location.href = "http://localhost:8202/admin/cmn/dict/exportData";
    }
  }
};
</script>

三 测试

1 清空数据

DROP table dict

CREATE TABLE `dict` (
  `id` bigint(20) NOT NULL DEFAULT '0' COMMENT '主键id',
  `parent_id` bigint(20) NOT NULL DEFAULT '0' COMMENT '上级id',
  `name` varchar(100) NOT NULL DEFAULT '' COMMENT '名称',
  `value` bigint(20) DEFAULT NULL COMMENT '值',
  `dict_code` varchar(20) DEFAULT NULL COMMENT '编码',
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `is_deleted` tinyint(3) unsigned zerofill NOT NULL DEFAULT '0' COMMENT '删除标记(0:可用 1:已删除)',
  PRIMARY KEY (`id`),
  KEY `idx_dict_code` (`dict_code`),
  KEY `idx_parent_id` (`parent_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='数据字典';

2 准备表格

3 上传该表格的结果

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue实现 Excel 导入并处理 Excel 中的时间,可以使用 js-xlsx 库来处理 Excel 文件的读取和解析,然后使用 Moment.js 库对时间进行格式化和处理。 首先,安装所需的依赖: ```bash npm install xlsx moment --save ``` 然后,在你需要处理 Excel 导入的组件中,引入 js-xlsx 和 Moment.js: ```javascript import XLSX from 'xlsx'; import moment from 'moment'; ``` 接下来,编写一个方法来处理导入Excel 文件。假设你有一个按钮点击事件来触发导入操作,可以在该事件中调用以下方法: ```javascript // 处理导入Excel 文件 handleExcelImport(event) { const file = event.target.files[0]; // 读取 Excel 文件 const reader = new FileReader(); reader.onload = (e) => { const data = new Uint8Array(e.target.result); const workbook = XLSX.read(data, { type: 'array' }); // 获取第一个 Sheet const sheetName = workbook.SheetNames[0]; const worksheet = workbook.Sheets[sheetName]; // 将 Excel 数据转换为 JSON const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 }); // 处理日期格式 const formattedData = jsonData.map(row => { return row.map(cell => { // 如果单元格内容是日期格式,则进行格式化 if (moment(cell, moment.ISO_8601, true).isValid()) { return moment(cell).format('YYYY-MM-DD'); // 根据需求进行日期格式化 } return cell; }); }); // 在控制台输出处理后的数据 console.log(formattedData); }; reader.readAsArrayBuffer(file); } ``` 在上面的代码中,我们首先使用 FileReader 对象读取 Excel 文件,并将其转换为 Uint8Array 格式。然后,使用 js-xlsx 的 `XLSX.read` 方法解析 Excel 数据,并获取第一个 Sheet。接下来,使用 `XLSX.utils.sheet_to_json` 将 Sheet 数据转换为 JSON 格式。 然后,我们对日期格式的单元格进行处理。使用 Moment.js 对日期进行格式化,你可以根据需求自定义日期格式。 最后,我们将处理后的数据输出到控制台进行验证。你可以根据实际需求将数据保存到 Vuex 状态管理或发送到后端进行进一步处理。 最后,在模板中添加一个文件选择器和按钮来触发导入操作: ```html <template> <div> <input type="file" @change="handleExcelImport" accept=".xlsx, .xls"> <button @click="handleExcelImport">导入Excel</button> </div> </template> ``` 这样,当用户选择 Excel 文件并点击导入按钮时,就会触发 `handleExcelImport` 方法,进行 Excel 导入和时间处理的操作。 希望对你有所帮助!如有任何问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值