当前位置: 首页 > article >正文

vue3.0中实现excel文件的预览

最近开发了一个需求,要求实现预览图片、pdf、excel、word、txt等格式的文件;
每种格式的文件想要实现预览的效果需要使用对应的插件,如果要实现excel格式文件的预览,要用到哪种插件呢?

答案:xlsx.full.min.js

xlsx.full.min.js是由SheetJS出品的js-xlsx是一款非常方便的只需要纯JS即可读取和导出excel的工具库,功能强大,支持格式众多,支持xls、xlsx、ods(一种OpenOffice专有表格文件格式)等十几种格式。

那到底是怎么使用的呢?

  1. 获取excel内容;
  2. 加载到html中;
  3. 设置表格的样式;

整个代码如下,然后我们逐步进行分析。

<!--
 * excel文件预览组件封装
-->
<template>
    <div class="pageExcel">
        <div class="excelRegion">
            <div class="excelSheet">
                <span
                    v-for="(item, index) in sheetList"
                    :key="index"
                    v-html="item.sheetName"
                    :class="item.isSelected ? 'active' : ''"
                    @click="switchSheet(index)"
                ></span>
            </div>
            <div
                class="excelTable"
                v-for="(item, index) in sheetList"
                :key="index"
                v-html="item.content"
                v-show="item.isSelected"
            ></div>
        </div>
    </div>
</template>

<script setup>
import LoadScript from "./utils/loadScript";
import allRequestAPI from "./api/request.js";
import { onMounted, ref } from "vue";
import { getString } from './utils/util.js'
let id = getString('id')
let excelToken = getString('token')
let sheetList = ref([]);

onMounted(() => {
    getExcel();
});

// 获取excel
function getExcel() {
    sheetList.value = [];
    LoadScrpt.load([`public/xlsx.full.min.js`]).then(() => {
        getExcelFileContent();
    });
}

// 获取excel的内容
function getExcelFileContent() {
    allRequestAPI.getExcelFileStream(
        id
        {
            excelToken: excelToken
        },
        "arraybuffer"
    )
        .then((res) => {
            // 处理编码
            let ary = "";
            // 记住一点,res.data是文件流,所以这样写,如果返回的res是文件流,那么就写new Uint8Array(res)
            let bytes = new Uint8Array(res.data);
            let length = bytes.byteLength;
            for (let i = 0; i < length; i++) {
                ary += String.fromCharCode(bytes[i]);
            }
            // 读取excel内容   binary二进制
            let wb = XLSX.read(ary, { type: "binary" });

            // sheet列表
            let sheetFileList = wb.SheetNames;

            sheetFileList.forEach((item, index) => {
                let ws = wb.Sheets[item];
                let fileContent = "";
                try {
                    // 把excel文件流转化为html字符串,以便于v-html使用
                    fileContent = XLSX.utils.sheet_to_html(ws);
                } catch (error) {}
                sheetList.value.push({
                    name: item,
                    isSelected: index == 0,
                    content: fileContent,
                });
            });
            console.log(sheetFileList);
            console.log("表格内容");
            console.log(sheetList);
        })
        .catch((error) => {
            console.log(error);
        });
}

// 切换excel的sheet
function switchSheet(i) {
    sheetList.value.forEach((item, index) => {
        item.isSelected = index == i;
    });
}
</script>

<style scoped lang="less">
.excelRegion {
    flex: 1;
    overflow-x: scroll;
    align-items: center;
    padding: 12px;
    background-color: #f8f8f8;

    .excelSheet {
        display: flex;
        white-space: nowrap;
        padding-bottom: 15px;

        span {
            display: block;
            height: 36px;
            line-height: 36px;
            padding: 0 12px;
            background-color: #fff;
            font-size: 14px;
            box-shadow: 0px 2px 4px 3px rgba(204, 204, 204, 0.34);

            &.active {
                background-color: #ff6d00;
                color: #fff;
            }
        }
    }

    :deep(.excelTable) {
        table {
            border-collapse: collapse !important;
            background-color: #fff;

            td {
                word-break: keep-all;
                white-space: nowrap;
                border: 1px solid #000;
                padding: 0px 8px;
                font-size: 12px;
                color: #666;
            }
        }
    }
}
</style>

Uint8Array 数组类型表示一个 8 位无符号整型数组,创建时内容被初始化为 0。创建完后,可以以对象的方式或使用数组下标索引的方式引用数组中的元素。

String.fromCharCode() 静态方法返回由指定的 UTF-16 码元序列创建的字符串。

官方github:https://github.com/SheetJS/js-xlsx

本文配套demo在线演示地址:http://demo.haoji.me/2017/02/08-js-xlsx/

这篇文章对我帮助本大,如何使用JavaScript实现纯前端读取和导出excel文件


http://www.kler.cn/news/133981.html

相关文章:

  • 07-流媒体-RTMP推流
  • 实战项目:VB龟兔赛跑游戏+猜数字游戏
  • vue3安装vue-router
  • 云计算(Docker)
  • 文件转换,简简单单,pdf转word,不要去找收费的了,自己学了之后免费转,之后就复制粘贴就ok了
  • how to find gcc openbug
  • mysql 设置远程登录
  • 【数据结构&C++】二叉平衡搜索树-AVL树(25)
  • 系列五、怎么查看默认的垃圾收集器是哪个?
  • Java 语言关键字有哪些
  • 【0234】PgBackendStatus 记录当前postgres进程的活动状态
  • GDPU 数据结构 天码行空10
  • 华为OD机试 - 转盘寿司(Java JS Python C)
  • Springboot更新用户头像
  • 大语言模型的三阶段训练
  • vim指令
  • promise时效架构升级方案的实施及落地 | 京东物流技术团队
  • 【Go入门】 Go搭建一个Web服务器
  • 340条样本就能让GPT-4崩溃,输出有害内容高达95%?OpenAI的安全防护措施再次失效
  • 电路的基本原理
  • DeepStream--测试resnet50分类模型
  • 大数据-玩转数据-Centos7 升级JDK11
  • Flink之KeyedState
  • R语言——taxize(第二部分)
  • 036、目标检测-锚框
  • 集合的运算
  • uni-app下,页面跳转后wacth持续监听的问题处理
  • LeetCode:689. 三个无重叠子数组的最大和(dp C++)
  • Java基础- StringBuilder StringBuffer
  • Android图片涂鸦,Kotlin(1)