vue3导出 excel、word

import axios from 'axios'
import { http } from '@/plugins/axios'
import { useMessage } from 'naive-ui'
const message = useMessage()
const instance = axios.create({
  responseType: 'arraybuffer',
  onDownloadProgress: function (ProgressEvent) {
    // console.log('ProgressEvent', ProgressEvent)
    // const load = ProgressEvent.loaded
    // const total = ProgressEvent.total
    // const progress = (load / total) * 100
    // console.log(progress)
  }
})

export async function downloadFile(url: string, fileName: string) {
  const result = await instance.get(url)
  if (result.data.byteLength > 0) {
    const url = window.URL.createObjectURL(
      new Blob([result.data], {
        type: 'application/vnd.ms-excel'
      })
    )
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', fileName)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link) // 下载完成移除元素
    window.URL.revokeObjectURL(url) // 释放掉blob对象
    return 1
  } else {
    return 0
    message.error('数据不存在,下载失败')
  }
}
export function exportExcel(url: string, query: any, fileName: string) {
  http
    .request({
      url: url,
      method: 'get',
      params: query,
      responseType: 'blob'
    })
    .then((res) => {
      const data = res as any
      if (data) {
        const url = window.URL.createObjectURL(
          new Blob([data], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
          })
        )
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', fileName)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link) // 下载完成移除元素
        window.URL.revokeObjectURL(url) // 释放掉blob对象
        return 1
      } else {
        return 0
        message.error('数据不存在,下载失败')
      }
    })
}
export function exportWord(url: string, query: any, fileName: string) {
  http
    .request({
      url: url,
      method: 'get',
      params: query,
      responseType: 'blob'
    })
    .then((res) => {
      const data = res as any
      if (data) {
        const url = window.URL.createObjectURL(
          new Blob([data], {
            type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
          })
        );
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', fileName);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link); // 下载完成移除元素
        window.URL.revokeObjectURL(url); // 释放掉blob对象
        return 1;
      } else {
        message.error('数据不存在,下载失败');
        return 0;
      }
    })
    .catch((error) => {
      console.error('Error exporting Word:', error);
      message.error('导出Word失败');
    });
}

你可能感兴趣的:(excel,word,javascript)