js和html中,将Excel文件渲染在页面上

发布于:2025-02-11 ⋅ 阅读:(27) ⋅ 点赞:(0)

1.如果从后端拿到的数据是文档流

// 从后端接口获取 Excel 文档流
async function fetchExcelFromBackend() {
    try {
        // 假设后端接口 URL
        const backendApiUrl = `http://local.hct10039.com:18080/recognition/downloadExcel?orderSn=${orderSn}`;
        const response = await fetch(backendApiUrl);

        if (!response.ok) {
            throw new Error('Failed to fetch Excel from backend: ' + response.status);
        }

        const blob = await response.blob();
        const file = new File([blob], 'filename.xlsx', { type: blob.type });
        loadExcelAndRender(file);
    } catch (error) {
        alert('出错了:' + error.message);
    }
}

// 加载并渲染 Excel
async function loadExcelAndRender(file) {
    try {
        const reader = new FileReader();
        reader.onload = function (e) {
            const data = new Uint8Array(e.target.result);
            const workbook = XLSX.read(data, { type: 'array' });
            const firstSheetName = workbook.SheetNames[0];
            const worksheet = workbook.Sheets[firstSheetName];
            const html = XLSX.utils.sheet_to_html(worksheet, { id: firstSheetName });
            document.getElementById('excelDom').innerHTML = html;
        };
        reader.readAsArrayBuffer(file);
    } catch (error) {
        alert('出错了:' + error.message);
    }
}

// 调用函数从后端接口获取并渲染 Excel
fetchExcelFromBackend();

2.如果从后端拿到的是文件的地址

function getFileObjectFromUrl(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob'; // 重要:设置响应类型为blob

    xhr.onload = function() {
        if (this.status === 200) {
            // 请求成功,this.response包含Blob对象
            var blob = this.response;
            // 创建File对象
            var file = new File([blob], 'filename.xlsx', {type: blob.type});
            // 调用回调函数,传入File对象
            callback(file);
        } else {
            console.error('Failed to download file:', this.status);
        }
    };

    xhr.onerror = function() {
        console.error('Request error');
    };

    xhr.send();
}
async function loadExcelAndRender(file) {
    try {
        const reader = new FileReader();
        reader.onload = function (e) {
            const data = new Uint8Array(e.target.result);
            const workbook = XLSX.read(data, { type: 'array' });
            const firstSheetName = workbook.SheetNames[0]; // 获取第一个sheet的名称
            const worksheet = workbook.Sheets[firstSheetName];
            const html = XLSX.utils.sheet_to_html(worksheet, {id: firstSheetName}); // 只渲染第一个sheet
            document.getElementById('excelDom').innerHTML = html; // 将HTML渲染到指定的div中
        };
        reader.readAsArrayBuffer(file);
    } catch (error) {
        console.error('Error loading or rendering Excel:', error);
    }
}

3.效果

4.附加功能

放大缩小和拖拽功能