vue 实现前端处理 “数组数据“ 转excel格式文件,并导出excel表格

发布时间:2024年01月17日

一、安装插件?XLSX

npm install XLSX --save

二、页面引入

<button @click="getDownList()">导出</button>

<script setup lang="ts">
import { ref } from "vue"
import * as XLSX from 'xlsx'

const datas = ref([
  {jobName:'作业1',studentName:'李佳',subjectName:'数学',schoolName:'重庆八中',gradeName:'高2023级',className:'1班'},
  {jobName:'作业1',studentName:'李佳',subjectName:'数学',schoolName:'重庆八中',gradeName:'高2023级',className:'1班'},
  {jobName:'作业1',studentName:'李佳',subjectName:'数学',schoolName:'重庆八中',gradeName:'高2023级',className:'1班'},
  {jobName:'作业1',studentName:'李佳',subjectName:'数学',schoolName:'重庆八中',gradeName:'高2023级',className:'1班'},
  {jobName:'作业1',studentName:'李佳',subjectName:'数学',schoolName:'重庆八中',gradeName:'高2023级',className:'1班'},
  {jobName:'作业1',studentName:'李佳',subjectName:'数学',schoolName:'重庆八中',gradeName:'高2023级',className:'1班'}
])
// 导出接口
const getDownList = async () => {
  const modifiedData = datas.value.map((item:any) => {
    return {
      '作业名称': item.jobName,
      '学生姓名': item.studentName,
      '科目': item.subjectName,
      '学校': item.schoolName,
      '年级': item.gradeName,
      '班级': item.className
    }
  })
  const worksheet = XLSX.utils.json_to_sheet(modifiedData)
  const workbook = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')
  const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })
  saveAsExcelFile(excelBuffer, downGropParams.group + '(' + downGropParams.student + ')')
}
//保存下载文件
const saveAsExcelFile = (buffer:any, fileName:string) => {
  const data = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
  const link = document.createElement('a')
  link.href = window.URL.createObjectURL(data)
  link.download = fileName + '.xlsx'
  link.click()
}

</script>

? ? ? ?希望我的愚见能够帮助你哦~,若有不足之处,还望指出,你们有更好的解决方法,欢迎大家在评论区下方留言支持,大家一起相互学习参考呀~

文章来源:https://blog.csdn.net/weixin_50450473/article/details/135641029
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。