Implement preview of excel files in vue3.0

Recently developed a requirement to preview files in image, pdf, excel, word, txt and other formats;
To achieve the preview effect of files in each format, you need to use the corresponding plug-in. If you want to achieve the preview of excel format files, you must Which plug-in to use?

答案:xlsx.full.min.js

xlsx.full.min.js is js-xlsx produced by SheetJS. It is a very convenient tool library that only requires pure JS to read and export excel. It has powerful functions and supports many formats, including xls, xlsx, ods (an OpenOffice proprietary table file format) and more than a dozen formats.

So how is it used?

  1. Get excel content;
  2. Load into html;
  3. Set the style of the table;

The entire code is as follows, and then we analyze it step by step.

<!--
 * 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>

The Uint8Array array type represents an 8-bit unsigned integer array whose contents are initialized to 0 when created. After creation, the elements in the array can be referenced as objects or using array subscript indexing.

String.fromCharCode() Static method returns a string created from the specified sequence of UTF-16 code elements. For specific usage, please see:JavaScript String.fromCharCode() function detailed explanation

Official github:https://github.com/SheetJS/js-xlsx

The online demonstration address of the demo accompanying this article:http://demo.haoji.me/2017/02/08-js-xlsx/

This article helped me a lot,How to use JavaScript to read and export excel files with a pure front-end

Guess you like

Origin blog.csdn.net/xiaolinlife/article/details/134462172