前端本地文件獲取excel表格內(nèi)容并渲染在頁(yè)面的方法
插件:SheetJs ,如若想要了解更多,可參考官網(wǎng):SheetJS 中文網(wǎng)
效果圖:

方法1: XLSX.readFile(filename, opts) 讀取指定文件并生成 SheetJS 工作簿對(duì)象
如果表格內(nèi)容較少,體驗(yàn)較好
如果表格內(nèi)容很多,幾千行,則不推薦,數(shù)據(jù)量過大會(huì)導(dǎo)致頁(yè)面卡死,體驗(yàn)差
代碼:
<!DOCTYPE html>
<html lang="cn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>可在線展示Excel的js插件</title>
<style>
html,body {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
.container {
overflow: auto;
width: 100%;
height: 100%;
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
}
th {
background-color: #f2f2f2;
text-align: left;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
</head>
<body>
<div class="container" id="container">
</div>
<script>
var nContainer = document.getElementById('container');
var xlsx = new Plus.Xlsx(nContainer);
xlsx.readFile('本地文件路徑');
</script>
</body>
</html>
方法2:XLSX.read(data, opts) 解析文件數(shù)據(jù)并生成 SheetJS 工作簿對(duì)象
可獲取固定的數(shù)據(jù)格式,并處理懶加載方式,從而緩解數(shù)據(jù)量過大卡死現(xiàn)象
代碼:
<!DOCTYPE html>
<html lang="cn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>可在線展示Excel的 js插件</title>
<style>
html,body {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
.container {
overflow: auto;
width: 100%;
height: 100%;
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
}
th {
background-color: #f2f2f2;
text-align: left;
}
</style>
<script type="text/javascript" src="/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
</head>
<body>
<div id="excel-data" class="container"></div>
<script type="text/javascript">
const excelData = $('#excel-data');
let allData = [];
let loadedRows = 0;
const pageSize = 50;
let mergeInfo = {};
let currentMergeCounts = {};
async function loadStaticFile(filePath) {
try {
const response = await fetch(filePath);
const blob = await response.blob();
const file = new File([blob], '職業(yè)類別表.xls', { type: blob.type });
const reader = new FileReader();
reader.onload = (e) => {
const data = new Uint8Array(e.target.result);
const workbook = XLSX.read(data, { type: 'array' });
// 只讀取第一個(gè)工作表
const firstSheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[firstSheetName];
allData = XLSX.utils.sheet_to_json(worksheet);
// 初始化表格和合并信息
initializeTable();
calculateMergeInfo(allData);
loadMoreRows();
// 監(jiān)聽滾動(dòng)事件,在接近底部時(shí)加載更多數(shù)據(jù)
excelData.on('scroll', handleScroll);
};
reader.readAsArrayBuffer(file);
} catch (error) {
console.error('加載文件失敗:', error);
}
}
loadStaticFile('/view/zhiyefenlei01_new.xls');
function initializeTable() {
let jobHtml = "<table border='1' cellpadding='5' cellspacing='0'>";
// 構(gòu)建表頭
const headers = ['大分類', '中分類', '小分類', '代碼', '細(xì)類', '職業(yè)類別'];
jobHtml += `<thead><tr>${headers.map(h => `<th>${h}</th>`).join('')}</tr></thead>`;
jobHtml += "<tbody>";
excelData.html(jobHtml + "</tbody></table>");
}
function calculateMergeInfo(data) {
mergeInfo = {};
currentMergeCounts = {};
data.forEach((row, rowIndex) => {
const headers = ['大分類', '中分類', '小分類', '代碼', '細(xì)類', '職業(yè)類別'];
headers.forEach(header => {
if (!mergeInfo[header]) {
mergeInfo[header] = [];
currentMergeCounts[header] = 0;
}
// 如果當(dāng)前行缺少該字段,則認(rèn)為它是前一行的延續(xù)
if (row[header] === undefined || row[header] === '') {
currentMergeCounts[header]++;
} else {
// 如果有未處理的合并項(xiàng),更新之前的 rowspan
if (currentMergeCounts[header] > 0) {
const lastIndex = rowIndex - currentMergeCounts[header] - 1;
mergeInfo[header][lastIndex] = currentMergeCounts[header] + 1;
currentMergeCounts[header] = 0;
}
mergeInfo[header].push(0);
}
});
// 處理最后一組合并項(xiàng)
if (rowIndex === data.length - 1) {
Object.keys(currentMergeCounts).forEach(header => {
if (currentMergeCounts[header] > 0) {
const lastIndex = rowIndex - currentMergeCounts[header];
mergeInfo[header][lastIndex] = currentMergeCounts[header] + 1;
}
});
}
});
}
function generateMergedRow(row, rowIndex) {
let rowHtml = "<tr>";
const headers = ['大分類', '中分類', '小分類', '代碼', '細(xì)類', '職業(yè)類別'];
headers.forEach(header => {
if (row[header] !== undefined && row[header] !== '') {
const rowspan = mergeInfo[header][rowIndex] || 1;
rowHtml += `<td ${rowspan > 1 ? `rowspan="${rowspan}"` : ''}>${row[header]}</td>`;
} else {
// 跳過重復(fù)的單元格
rowHtml += '';
}
});
rowHtml += "</tr>";
return rowHtml;
}
function loadMoreRows() {
const dataSlice = allData.slice(loadedRows, loadedRows + pageSize);
if (dataSlice.length === 0) return;
let $tbody = $('#excel-data table tbody');
dataSlice.forEach((row, rowIndex) => {
$tbody.append(generateMergedRow(row, loadedRows + rowIndex));
});
loadedRows += dataSlice.length;
}
function handleScroll() {
const $container = $(this);
const scrollTop = $container.scrollTop();
const scrollHeight = $container[0].scrollHeight;
const clientHeight = $container.height();
// 當(dāng)滾動(dòng)到底部附近時(shí)加載更多數(shù)據(jù)
if (scrollTop + clientHeight >= scrollHeight - 50) {
loadMoreRows();
}
}
</script>
</body>
</html>總結(jié)
到此這篇關(guān)于前端本地文件獲取excel表格內(nèi)容并渲染在頁(yè)面的文章就介紹到這了,更多相關(guān)前端本地獲取excel表格并渲染內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
微信小程序非跳轉(zhuǎn)式組件授權(quán)登錄的方法示例
這篇文章主要介紹了微信小程序非跳轉(zhuǎn)式組件授權(quán)登錄的方法示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來(lái)看看吧2019-05-05
ES6 Array常用擴(kuò)展的應(yīng)用實(shí)例分析
這篇文章主要介紹了ES6 Array常用擴(kuò)展的應(yīng)用,結(jié)合實(shí)例形式分析各種常見擴(kuò)展方法針對(duì)Array數(shù)組的轉(zhuǎn)換、遍歷、查找、運(yùn)算等相關(guān)操作技巧,需要的朋友可以參考下2019-06-06
微信企業(yè)號(hào)開發(fā)之微信考勤百度地圖定位
本文給大家介紹微信企業(yè)號(hào)開發(fā)之微信考勤百度地圖定位,有需要的朋友參考下本篇文章2015-09-09
json 帶斜杠時(shí)如何解析的實(shí)現(xiàn)
這篇文章主要介紹了json 帶斜杠時(shí)如何解析的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08
跟我學(xué)習(xí)javascript的var預(yù)解析與函數(shù)聲明提升
跟我學(xué)習(xí)javascript的var預(yù)解析與函數(shù)聲明提升,小編對(duì)var預(yù)解析與函數(shù)聲明提升知識(shí)點(diǎn)也不甚了解,和大家一起學(xué)習(xí)本篇文章。2015-11-11

