全速加载中...
登录
首页
文章
随笔
留言
友链
订阅
关于
更多
湘ICP备2021007748号-4
湘公网安备案湘公网安备43052202000137号
又拍云

Vue3前端轻松导入Excel表格,解析成HTML展示

在线演示地址: Excel表格解析邮件发送

一,安装xlsx

xlsx是一款非常方便的只需要纯JS即可读取和导出excel的工具库,功能强大,支持格式众多。

language 复制代码
npm install xlsx --save

二,页面中使用

language 复制代码
<template>
 <div style="margin: 10px">
   <n-upload
       multiple
       @before-upload="onBeforeUpload" @finish="onFinish"
       directory-dnd
       action=""
       :max="5"
   >
     <n-upload-dragger>
       <div style="margin-bottom: 12px">
         <n-icon size="48" :depth="3">
           <archive-icon />
         </n-icon>
       </div>
       <n-text style="font-size: 16px">
         点击或者拖动Excel文件到该区域来上传
       </n-text>
       <n-p depth="3" style="margin: 8px 0 0 0">
         请不要上传敏感数据,比如你的银行卡号和密码,信用卡号有效期和安全码
       </n-p>
     </n-upload-dragger>
   </n-upload>
   <n-h2 prefix="bar">
     转换后内容
   </n-h2>
     {{fileStr}}

 </div>
</template>

<script lang="ts" setup>
import {ref,computed} from  'vue';
import {read,utils} from 'xlsx';
import { ArchiveOutline as ArchiveIcon } from '@vicons/ionicons5'


const fileStr=ref('');
const isFile=ref(null);

//上传前
const onBeforeUpload = ((file: any, fileList: any) => {
  return new Promise((resolve, reject) => {
  isFile.value = file.file.file;
  let reader = new FileReader()
  reader.readAsArrayBuffer(isFile.value)
  reader.onload = function () {
    let buffer = reader.result as any
    let bytes = new Uint8Array(buffer)
    let length = bytes.byteLength
    let binary = ''
    for (let i = 0; i < length; i++) {
      binary += String.fromCharCode(bytes[i])
    }
    let wb =read(binary, {
      type: 'binary'
    })
    //解析成HTML
    let outdata = utils.sheet_to_html(wb.Sheets[wb.SheetNames[0]]);
    // 使用正则表达式匹配table标签,并添加样式
    fileStr.value=outdata.replace(/<table>/, '<table style="border-collapse: collapse; width: 100.014%; height: 62.4px;" border="1">');;
    console.log(outdata)
  }
  })

})
//上传后
const onFinish = ((file: any) => {
  let data2 = (file.event?.target as XMLHttpRequest).response;
  console.log(data2)
})
</script>

效果图

效果图
本文作者:ZhangApple ,转载请注明并附上本文链接。

上一篇 下一篇

评论一下

评论列表

 
暂无评论
ZhangApple
更多
发布日期:2024年03月12日