JavaScript實現(xiàn)將Excel文件渲染在頁面上
更新時間:2024年12月26日 11:13:50 作者:?團(tuán)子?
這篇文章主要為大家詳細(xì)介紹了如何使用Html和JavaScript實現(xiàn)將Excel文件渲染在頁面上,文中的示例代碼講解詳細(xì),有需要的小伙伴可以參考下
1.如果從后端拿到的數(shù)據(jù)是文檔流
// 從后端接口獲取 Excel 文檔流
async function fetchExcelFromBackend() {
try {
// 假設(shè)后端接口 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);
}
}
// 調(diào)用函數(shù)從后端接口獲取并渲染 Excel
fetchExcelFromBackend();2.如果從后端拿到的是文件的地址
function getFileObjectFromUrl(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob'; // 重要:設(shè)置響應(yīng)類型為blob
xhr.onload = function() {
if (this.status === 200) {
// 請求成功,this.response包含Blob對象
var blob = this.response;
// 創(chuàng)建File對象
var file = new File([blob], 'filename.xlsx', {type: blob.type});
// 調(diào)用回調(diào)函數(shù),傳入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.附加功能
放大縮小和拖拽功能
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>滾動拖拽示例</title>
</head>
<body>
<div class="excelContent borderLineBlack" style="width: 100%;height: 100%;" style="overflow: auto;">
<div id="excelDom" style="width: 30%;height: 30vh;background-color: aquamarine;">子盒子</div>
</div>
<!-- 引入JavaScript腳本 -->
<script >
// 獲取父元素excelContent
const excelContent = document.querySelector('.excelContent.borderLineBlack');
// 監(jiān)聽父元素的wheel事件,防止?jié)L動父盒子
excelContent.addEventListener('wheel', function(event) {
// 判斷事件的目標(biāo)元素是否為excelDom或其子元素
if (!excelDom.contains(event.target)) {
// 如果不是,則阻止默認(rèn)的滾動行為
event.preventDefault();
}
});
let scale = 1; // 設(shè)置初始縮放比例
var excelDom = document.getElementById("excelDom");
let isDragging = false;
let offsetX = 0, offsetY = 0; // 用于記錄拖動時的偏移量
// 監(jiān)聽鼠標(biāo)滾輪事件
excelDom.addEventListener('wheel', function(event) {
if (event.ctrlKey) {
event.preventDefault();
if (event.deltaY < 0) {
scale += 0.1;
} else {
scale -= 0.1;
}
scale = Math.max(0.1, scale);
// 更新變換,應(yīng)用縮放和平移
excelDom.style.transform = `scale(${scale}) translate(${offsetX}px, ${offsetY}px)`;
}
});
// 監(jiān)聽鼠標(biāo)按下事件
excelDom.addEventListener('mousedown', function(event) {
isDragging = true;
let startX = event.clientX;
let startY = event.clientY;
// 監(jiān)聽鼠標(biāo)移動事件,只在拖動時添加
const mouseMoveHandler = function(event) {
const dx = event.clientX - startX;
const dy = event.clientY - startY;
offsetX += dx;
offsetY += dy;
// 更新變換,應(yīng)用平移
excelDom.style.transform = `scale(${scale}) translate(${offsetX}px, ${offsetY}px)`;
// 重置起始坐標(biāo)
startX = event.clientX;
startY = event.clientY;
};
// 添加鼠標(biāo)移動事件監(jiān)聽器
document.addEventListener('mousemove', mouseMoveHandler);
// 監(jiān)聽鼠標(biāo)釋放事件,只在拖動時添加
const mouseUpHandler = function() {
isDragging = false;
excelDom.style.cursor = 'auto';
// 移除鼠標(biāo)移動和釋放事件監(jiān)聽器
document.removeEventListener('mousemove', mouseMoveHandler);
document.removeEventListener('mouseup', mouseUpHandler);
};
// 添加鼠標(biāo)釋放事件監(jiān)聽器
document.addEventListener('mouseup', mouseUpHandler);
event.preventDefault();
});
</script>
</body>
</html>到此這篇關(guān)于JavaScript實現(xiàn)將Excel文件渲染在頁面上的文章就介紹到這了,更多相關(guān)JavaScript Excel文件渲染內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
ES6?數(shù)組some()和every()的使用及說明
這篇文章主要介紹了ES6?數(shù)組some()和every()的使用及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01
DOM節(jié)點深度克隆函數(shù)cloneNode()用法實例
這篇文章主要介紹了DOM節(jié)點深度克隆函數(shù)cloneNode()用法,實例分析了cloneNode()函數(shù)深度復(fù)制的操作技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-01-01
如何用JavaScript實現(xiàn)功能齊全的單鏈表詳解
這篇文章主要給大家介紹了關(guān)于如何用JavaScript實現(xiàn)功能齊全的單鏈表的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-02-02
微信小程序?qū)崿F(xiàn)卡片左右滑動效果的示例代碼
這篇文章主要介紹了微信小程序?qū)崿F(xiàn)卡片左右滑動效果的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-05-05

