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.附加功能
放大缩小和拖拽功能
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |