用JS实现excel预览
这次为大家分享的是,如何用js写出excel文件的预览。
他方便了pc用户和手机端用户可以无需下载,并且直接在线预览excel文件。
因为excel转html的显示用的是第三方开源库的代码,所以实现上有所限制。具体请参见 所用到开源的库 这些库的说明。
| 支持 | 不支持 |
|---|---|
| 多sheet显示 | 图片显示 |
| 合并后的单元格显示 | 链接,文字样式等 |
| 手机画面优化 |
效果图
PC:
手机:
示例代码
所用到开源的库
js:
jQuery:https://js.cybozu.cn/jquery/3.4.1/jquery.min.js
sheetjs ( js-xlsx ):GitHub - SheetJS/sheetjs: SheetJS Community Edition -- Spreadsheet Data Toolkit
bootstrap: GitHub - twbs/bootstrap: The most popular HTML, CSS, and JavaScript framework for developing responsive, mobile first projects on the web.
css:
GitHub - FortAwesome/Font-Awesome: The iconic SVG, font, and CSS toolkit
GitHub - keaukraine/bootstrap4-fs-modal: A simple way to improve UX of Bootstrap 4 modals on mobile phones. (mobile端)
代码
判断是否为excel文件
| 1 2 3 4 | function checkXls(file) { let reg = /\.xl(s[xmb]|t[xm]|am|s)$/g; return reg.test(file); } |
加载模态框,显示加载画面,添加预览图标
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | function loadModal(fileInfo) { let previewElement; jQuery( ".file-image-container-gaia" ).each( function (i, e) { let fileName = jQuery(e).children( "a:eq(0)" ).text(); if (fileName == fileInfo.name && jQuery(e).children( "button" ).length == 0) { previewElement = jQuery(e); return false ; } }); if (!previewElement) return ; let modalId = 'myModal' + fileInfo.fileKey; let tabId = 'myTab' + fileInfo.fileKey; let tabContentId = 'tab-content' + fileInfo.fileKey; let $button = $( '' ); let myModal = '' + ' |
下载文件并加载到模态框中
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | function readWorkbookFromRemoteFile(url, callback) { let xhr = new XMLHttpRequest(); xhr.open( 'get' , url, true ); xhr.setRequestHeader( 'X-Requested-With' , 'XMLHttpRequest' ); xhr.responseType = 'arraybuffer' ; xhr.onload = function (e) { if (xhr.status == 200) { let data = new Uint8Array(xhr.response) let workbook = XLSX.read(data, { type: 'array' }); if (callback) callback(workbook); } }; xhr.send(); } function readWorkbook(workbook, fileInfo) { let sheetNames = workbook.SheetNames; let navHtml = '' ; let tabHtml = '' ; let myTabId = 'myTab' + fileInfo.fileKey; let tabContentId = 'tab-content' + fileInfo.fileKey; for (let index = 0; index < sheetNames.length; index++) { let sheetName = sheetNames[index]; let worksheet = workbook.Sheets[sheetName]; let sheetHtml = XLSX.utils.sheet_to_html(worksheet); let tabid = "tab" + fileInfo.fileKey + "-" + index; let xlsid = "xlsid" + fileInfo.fileKey + "-" + index; let active = index == 0 ? "active" : '' ; navHtml += ' ; tabHtml += ' |
具体的mobile优化等等详细代码请参考完整文章:
kintone excel预览插件
更多文章和演示:Kintone demo环境
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
