- A+
所属分类:Web前端
一、寻找合适的在线预览Excel的js库
经过百度各种搜索,加上ChatGpt推荐,决定用SheetJs实现在线预览Excel。下面是SheetJs的官网介绍:
SheetJS
电子表格简化
读取、编辑和导出电子表格
适用于网络浏览器和服务器
Office 365 受到 Microsoft 信任
SheetJS 软件为业务提供动力
谷歌、亚马逊、Facebook 服务
美国政府网站
超过 90% 的标准普尔 500 强公司的团队
二、基础版实现代码
<script> (async() => { /* replace with the URL of the file */ const URL_TO_DOWNLOAD = "https://sheetjs.com/pres.numbers"; const ab = await (await fetch(URL_TO_DOWNLOAD)).arrayBuffer(); /* Parse file and get first worksheet */ const wb = XLSX.read(ab); const wsname = wb.SheetNames[0]; const ws = wb.Sheets[wsname]; /* Generate HTML */ var output = document.getElementById("TableContainer"); output.innerHTML = XLSX.utils.sheet_to_html(ws); })(); </script>
三、增强版实现代码,支持单元格格式等
由于基础实现丢失了很多关键格式信息,比如字体大小、背景色、对齐方式、批注等。于是请教ChatGpt帮忙写代码。下面是ChatGpt写出来的代码,正确与否待验证
<!DOCTYPE html> <html> <head> <title>Excel Online Preview</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.9/xlsx.full.min.js"></script> <style> /* 根据需要设置单元格样式 */ .cell { padding: 5px; border: 1px solid #ccc; font-family: Arial, sans-serif; } </style> </head> <body> <button id="loadExcelButton">加载Excel</button> <div id="excelPreview"></div> <script> document.getElementById('loadExcelButton').addEventListener('click', function() { fetchExcelData(); }); function fetchExcelData() { fetch('URL_OF_YOUR_BACKEND_API') .then(response => response.arrayBuffer()) .then(data => { var workbook = XLSX.read(new Uint8Array(data), { type: 'array' }); var sheetName = workbook.SheetNames[0]; var sheet = workbook.Sheets[sheetName]; var cellData = XLSX.utils.sheet_to_json(sheet, { header: 1 }); var htmlTable = '<table>'; for (var row = 0; row < cellData.length; row++) { htmlTable += '<tr>'; for (var col = 0; col < cellData[row].length; col++) { var cellValue = cellData[row][col]; var cellRef = XLSX.utils.encode_cell({ r: row, c: col }); var cell = sheet[cellRef]; var cellStyle = cell ? cell.s : {}; var cellStyleAttr = 'style="' + getCellStyle(cellStyle) + '"'; var mergeAttr = getMergeAttributes(sheet, row, col); var comment = getCellComment(cell); var cellHtml = '<td class="cell" ' + cellStyleAttr + ' ' + mergeAttr + '" title="' + comment + '">' + cellValue + '</td>'; htmlTable += cellHtml; } htmlTable += '</tr>'; } htmlTable += '</table>'; document.getElementById('excelPreview').innerHTML = htmlTable; }) .catch(error => { console.error('Error fetching Excel data:', error); }); } function getCellStyle(cellStyle) { var styleAttr = ''; if (cellStyle.font) { var font = cellStyle.font; if (font.bold) styleAttr += 'font-weight:bold;'; if (font.italic) styleAttr += 'font-style:italic;'; if (font.underline) styleAttr += 'text-decoration:underline;'; if (font.strike) styleAttr += 'text-decoration:line-through;'; if (font.color) styleAttr += 'color:' + font.color.rgb + ';'; if (font.name) styleAttr += 'font-family:' + font.name + ';'; } if (cellStyle.alignment) { var alignment = cellStyle.alignment; if (alignment.horizontal) styleAttr += 'text-align:' + alignment.horizontal + ';'; if (alignment.vertical) styleAttr += 'vertical-align:' + alignment.vertical + ';'; } if (cellStyle.fill) { var fill = cellStyle.fill; if (fill.patternType === 'solid' && fill.fgColor) { styleAttr += 'background-color:' + fill.fgColor.rgb + ';'; } } return styleAttr; } function getMergeAttributes(sheet, row, col) { var mergeCells = sheet['!merges'] || []; for (var i = 0; i < mergeCells.length; i++) { var mergeRange = XLSX.utils.decode_range(mergeCells[i]); if (row >= mergeRange.s.r && row <= mergeRange.e.r && col >= mergeRange.s.c && col <= mergeRange.e.c) { return 'rowspan="' + (mergeRange.e.r - mergeRange.s.r + 1) + '" colspan="' + (mergeRange.e.c - mergeRange.s.c + 1) + '"'; } } return ''; } function getCellComment(cell) { if (cell && cell.c) { var comment = cell.c[0].t; return comment; } return ''; } </script> </body> </html>
图片展示
发现一个代码高亮转成图片的网站:
https://10015.io/tools/code-to-image-converter?utm_source=appinn.com