excel文件的上传与下载(vue3+ts)

1.api

// 下载数据字典全局变量

export const downloadGlobalVarImportTemplate = () =>

 

  request.post(

    {

      url: '/config-webapp/generic/global/export-template',

      responseType: 'blob', // 指定响应类型为 blob

    },

    { isTransformResponse: false },

  )

// 导出全集变量

export const exportGlobalVar = (data: any) =>

  request.post(

    {

      url: '/config-webapp/generic/global/export',

      data,

      responseType: 'blob', // 指定响应类型为 blob

    },

    { isTransformResponse: false },

  )

// 导入全集变量

export const importGlobalVar = (formData: any) =>

  request.post({

    url: '/config-webapp/generic/global/import',

    data: formData,

    headers: {

      'Content-Type': 'multipart/form-data',

    },

  })

2.结构

<div class="tableInfo">
      <el-card>
        <div class="mytable">
          <div class="tableHeader">
            <el-button class="save-button" @click="add">
              <svg-icon
                name="add"
                :iconStyle="{
                  width: '16px',
                  height: '16px',
                  marginRight: '8px',
                }"
              />
              新增数据项分类
            </el-button>
            <el-button class="save-button" @click="clickImportBtn">
              <svg-icon
                name="import"
                :iconStyle="{
                  width: '16px',
                  height: '16px',
                  marginRight: '8px',
                }"
              />
              导入数据项分类
            </el-button>
            <div class="table-header-right">
              <el-button class="save-button" @click="clickExportBtn">
                <svg-icon
                  name="export"
                  :iconStyle="{
                    width: '16px',
                    height: '16px',
                    marginRight: '8px',
                  }"
                />
                导出数据字典
              </el-button>
            </div>
          </div>
          <div class="table">
            <el-table
              border
              stripe
              :data="tableData"
              :header-cell-style="{
                background: '#f2f3f5',
                textAlign: 'center',
              }"
              :cell-style="{ textAlign: 'center' }"
              @selection-change="
                (selections) => {
                  rowSelections = selections
                }
              "
            >
              <el-table-column
                label="序号"
                type="index"
                align="center"
                width="60"
              ></el-table-column>
              <el-table-column type="selection"></el-table-column>
              <el-table-column prop="code" label="组编号"></el-table-column>
              <el-table-column prop="name" label="组名称"></el-table-column>
              <el-table-column prop="typeName" label="组分类"></el-table-column>
              <el-table-column
                prop="groupUserName"
                label="组成员"
              ></el-table-column>
              <el-table-column label="操作">
                <template #default="scope">
                  <edit-button @click="edit(scope.row)"></edit-button>
                  <delete-button
                    @click="handleDeleteData(scope.row)"
                  ></delete-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="footer">
            <el-pagination
              v-model:current-page="listQuery.pageNo"
              v-model:page-size="listQuery.pageSize"
              :page-sizes="[10, 20, 30, 40, 50]"
              layout="total, prev, pager, next, sizes"
              :total="listQuery.total"
              style="float: right; padding: 10px 0"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </el-card>
    </div>

<el-dialog

      :close-on-click-modal="false"

      title="上传操作"

      v-model="importDialogVisible"

      width="30vw"

      center

    >

      <el-upload

        drag

        action="#"

        :auto-upload="false"

        v-model:file-list="fileList"

        :on-change="uploadFile"

        style="padding: 0 30px"

      >

        <el-icon class="el-icon--upload">

          <upload-filled />

        </el-icon>

        <div class="el-upload__text">点击选择文件,或将文件拖拽到此处</div>

        <template #tip>

          <div class="el-upload__tip">

            点击此处下载模板:

            <el-link type="primary" :underline="false" @click="downloadTemplate"

              >数据字典导入模板

            </el-link>

          </div>

        </template>

      </el-upload>

      <template #footer>

        <div>

          <el-button type="primary" class="save-button" @click="handleUpload"

            >确认上传

          </el-button>

          <el-button

            type="primary"

            class="cancel-button"

            @click="importDialogVisible = false"

            >取消

          </el-button>

        </div>

      </template>

    </el-dialog>

3.js

import {ElMessage,ElLoading } from 'element-plus'

import { UploadFilled } from '@element-plus/icons-vue'

import { downloadDictionaryItemImportTemplate, importDictionaryItem,exportDictionaryItem } from 'API'



const importDialogVisible = ref(false)

const fileList = ref<any>([])

const rowSelections = ref<any[]>([])



const uploadFile = (file: any) => {

  const fileExtension = file.name.split('.').pop()

  const size = file.size / 1024 / 1024

  if (fileExtension !== 'xlsx' && fileExtension !== 'xls') {

    ElMessage.warning('只能上传excel文件')

    fileList.value = []

    return

  }

  if (size > 10) {

    ElMessage.warning('文件大小不得超过10M')

    fileList.value = []

    return

  }

  fileList.value = [file]

}

const downloadTemplate = () => {

  const loading = ElLoading.service({ text: '正在下载...' })

  downloadDictionaryItemImportTemplate()

    .then((data) => {

      const blob = new Blob([data])

      const url = window.URL.createObjectURL(blob)

      const link = document.createElement('a')

      link.href = url

      link.download = '数据字典导入模板.xlsx'

      link.click()

      window.URL.revokeObjectURL(url)

      loading.close()

    })

    .catch(() => {

      ElMessage.error('下载失败')

      loading.close()

    })

}

const handleUpload = () => {

  if (fileList.value.length === 0) {

    ElMessage.warning('未选择文件')

  } else {

    const formData = new FormData()

    formData.append('file', fileList.value[0].raw)

    importDictionaryItem(formData)

      .then(() => {

        importDialogVisible.value = false

      })

      .catch((e: any) => {

        console.log(e)

      })

  }

}

const clickExportBtn = () => {

  if (!rowSelections.value.length) {

    ElMessage.warning('请选择需要导出的数据字典')

    return

  }

  exportDictionaryItem(rowSelections.value.map((item: any) => item.id)).then(

    (res) => {

      if (!res) {

        ElMessage.error('导出失败')

        return

      }

      downLoadExcel(res, '数据字典')

    },

  )

}

const downLoadExcel = (data: any, name: string) => {

  const url = window.URL.createObjectURL(new Blob([data]))

  const link = document.createElement('a')

  link.href = url

  link.setAttribute('download', `${name}.xls`) // 替换成你想要的文件名

  document.body.appendChild(link)

  link.click()

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值