当前位置:网站首页>JS to load and display Excel files
JS to load and display Excel files
2022-06-12 11:41:00 【Jioho_】
js Load and display excel file
Form the good habit of putting the effect first ~

Project demo and code address :codesandbox/js-xlsx-demo
Entirely by JS The ability to load a excel form , Although the width and height of each cell cannot 100% Restore ( Maybe I haven't finished reading the specific documents ). However, the front end can be styled , Give each grid a different style
Today's leading role sheetjs
Official website demo No merged cells , But he can be like excel Select multiple cells as well , If you are interested, you can study it

Compatibility :IE8 ( That is, browsers all over the world support )
introduce
| CDN | URL |
|---|---|
| unpkg | https://unpkg.com/xlsx/ |
| jsDelivr | https://jsdelivr.com/package/npm/xlsx |
| CDNjs | http://cdnjs.com/libraries/xlsx |
| packd | https://bundle.run/[email protected]?name=XLSX |
perhaps npm install xlsx
In fact, it is import XLSX from 'xlsx' The back is full of medicine
The local demo I'll just use one cdn That's it . Or download it directly js file
Use
Read excel Mainly through XLSX.read(data, {type: type}) Method to implement , Return to one called WorkBook The object of ,type The main values are as follows :
| type value | describe |
|---|---|
| base64 | With base64 Mode reading |
| binary | BinaryString Format (byte n is data.charCodeAt(n)) |
| string | UTF8 Encoded string |
| buffer | nodejs Buffer |
| array | Uint8Array,8 Bit unsigned array |
| file | Path to file ( only nodejs Support ) |
- Local file read
// Read local excel file
function readWorkbookFromLocalFile(file, callback) {
var reader = new FileReader()
reader.onload = function(e) {
var data = e.target.result
var workbook = XLSX.read(data, {
type: 'binary' })
if (callback) callback(workbook)
}
reader.readAsBinaryString(file)
}
- Read remote files
- have access to axios Etc , As long as the interface returns a binary stream
- The network address of the file must be the same as url The same domain , Otherwise, an error will be reported
function readWorkbookFromRemoteFile(url, callback) {
var xhr = new XMLHttpRequest()
xhr.open('get', url, true)
xhr.responseType = 'arraybuffer'
xhr.onload = function(e) {
if (xhr.status == 200) {
var data = new Uint8Array(xhr.response)
var workbook = XLSX.read(data, {
type: 'array' })
if (callback) callback(workbook)
}
}
xhr.send()
}
workbook Object parsing
Introduce several important parameters :
SheetNamesandSheets

This is a excel Table name in ,Sheets The data corresponding to each table name recorded in the object
Sheets.Sheet1['!merges'] Record the cell information to be merged . Pictured above , Altogether 6 The block area needs to merge cells
among s Represents the starting cell information ,e Represents the end cell information .c Representative column (col),r On behalf of the line (row)
{
"s": {
"c": 0,
"r": 0
},
"e": {
"c": 8,
"r": 0
}
}
Take this for example , It's about starting from The first 0 That's ok (s.r) Of the 0 individual (s.c) Cell Start
Merge into The first 0 That's ok (e.r) Of the 8 individual (e.c) Cell
namely :A1-I1 Cell

Sheets Down A2,B2 And so on is the information of each cell
The fields and information are as follows :
| key | describe |
|---|---|
| v | Original value ( For more information , Please see the “ data type ” part ) |
| w | Formatting text ( If applicable ) |
| t | type :b Boolean value ,e error ,n Numbers ,d date ,s Text ,z stub |
| f | The cell formula code is A1 Style string ( If applicable ) |
| F | If the formula is an array formula , Contains the range of the array ( If applicable ) |
| r | Rich text encoding ( If applicable ) |
| h | Rich text format HTML present ( If applicable ) |
| c | Comments related to cells |
| z | The number format string associated with the cell ( If required ) |
| l | Cell hyperlink object (.Target Include links ,.Tooltip It's a tooltip ) |
| s | Cell style / The theme ( If applicable ) |
Speaking of style themes , There's also Themes and Styles object . See the documentation for details ~
Front end presentation form
Let's take a look at how many methods the plug-in provides

For the operation table , We all use sheet_ At the beginning API
| API | function |
|---|---|
XLSX.utils.sheet_to_csv | 【 Commonly used 】 Generate CSV Format |
XLSX.utils.sheet_to_html | 【 Commonly used 】 Generate HTML Format |
| XLSX.utils.sheet_to_txt | Generate plain text format |
| XLSX.utils.sheet_to_json | Output JSON Format |
What is commonly used is sheet_to_csv perhaps sheet_to_html, turn csv Will ignore the format 、 Cell merging and other information , So complex tables may not apply . turn html Will keep the cells merged , But what is generated is ( Generated by the latest version html It is already a merged cell )<html></html> Code , instead of <table></table>, It is not convenient to customize the form , Therefore, the appropriate tool class should be adopted according to the actual situation .
Use CVS, And merge cells
I looked at the top !merges analysis . According to the information given in the table , Handle the merged cells by yourself
- Front end display CVS data
// take csv Convert to table
function csv2table(csv, showTab) {
var html = '<table>'
var rows = csv.split('\n')
rows.pop() // The last line is useless
rows.forEach(function(row, idx) {
var columns = row.split(',')
if (showTab) {
columns.unshift(idx + 1) // Add row index
if (idx == 0) {
// Add column index
html += '<tr>'
for (var i = 0; i < columns.length; i++) {
html += '<th>' + (i == 0 ? '' : String.fromCharCode(65 + i - 1)) + '</th>'
}
html += '</tr>'
}
}
html += '<tr>'
columns.forEach(function(column) {
html += '<td>' + column + '</td>'
})
html += '</tr>'
})
html += '</table>'
return html
}
- merge cell
The idea of merging cells is simple
First determine the range of cells to be merged ( It says )
1.1 When determining the range, we need to pay attention to whether we have added cells in the above stepMatch the corresponding cell
2.1 When the match , If both rows and columns are starting points , This cell is the cell to be merged in the future
2.2 After a cell that is not a starting point , It's all about Merged , Simply put, it is the cell to be deleted
2.3 You cannot manipulate tables in a loop , Because that will cause cell confusion , Affect the following cycleAccording to the above marking , What should be deleted , The consolidation of the consolidation
The following code has a #result tr It's because I put my table in the local debugging code id="result" Inside , This point should be distinguished and modified .
function mergeTable(workbook, hasTab = false) {
let SheetNames = workbook.SheetNames[0]
let mergeInfo = workbook.Sheets[SheetNames]['!merges']
console.log(mergeInfo)
let result = document.getElementById('result')
// Is it displayed tab
let baiseAdd = hasTab ? 1 : 0
mergeInfo.forEach(item => {
let start_r = item.s.r + baiseAdd
let end_r = item.e.r + baiseAdd
let start_c = item.s.c + baiseAdd
let end_c = item.e.c + baiseAdd
for (let i = start_r; i <= end_r; i++) {
let row = document.querySelectorAll('#result tr')[i]
for (let child = start_c; child <= end_c; child++) {
if (child === start_c && i === start_r) {
// Loop to is the first cell , Start the merge with this cell
row.children[child].classList.add('will_span')
row.children[child].setAttribute('row', end_r - start_r + 1)
row.children[child].setAttribute('col', end_c - start_c + 1)
} else {
// Just mark , Do not delete here
row.children[child].classList.add('remove')
}
}
}
})
// Remove the corresponding td
document.querySelectorAll('.remove').forEach(item => {
item.parentNode.removeChild(item)
})
// For the big td Set up cross cell merge
document.querySelectorAll('.will_span').forEach(item => {
item.classList.remove('will_span')
item.rowSpan = item.getAttribute('row')
item.colSpan = item.getAttribute('col')
})
}
export excel
Since there is a show , There will be an export
excel There are many export schemes , such as js-export-excel It's one of them , But I won't introduce this library today , If you are interested, you can see for yourself npm On the document .
Since export , There is a way to download , have access to download.js , I will write a simple download method here
/** * General method of opening download dialog box , No specific compatibility has been tested * @param url Download address , It can also be a blob object , Mandatory * @param saveName Save filename , Optional */
function downLoadFile(url, saveName) {
if (typeof url == 'object' && url instanceof Blob) {
url = URL.createObjectURL(url) // establish blob Address
}
var aLink = document.createElement('a')
aLink.href = url
aLink.download = saveName || '' // HTML5 New properties , Specify the save file name , No suffixes , Be careful ,file:/// It doesn't work in mode
var event
if (window.MouseEvent) event = new MouseEvent('click')
else {
event = document.createEvent('MouseEvents')
event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
}
aLink.dispatchEvent(event)
}
export excel If so, we have to convert our data into the data recognized by the plug-in . Official API( Both in XLSX.utils Inside ):

Derived excel The form must have a worksheet
book. dependent api Just 3 individual
| api | describe |
|---|---|
| book_new | Create a new worksheet |
| book_append_sheet | Add... To the worksheet sheet Cell data |
| book_set_sheet_visibility | Set whether the worksheet is visible |
Create cell data (sheet) API as follows
| api | describe |
|---|---|
| aoa_to_sheet | Convert a two-dimensional array into sheet, Automatic processing number、string、boolean、date And so on |
| table_to_sheet | Will a table dom Direct conversion sheet, Will automatically identify colspan and rowspan And convert it into the corresponding cell to merge |
| json_to_sheet | Convert an array of objects into sheet |
Configure the worksheet with data Use
XLSX.writeGenerate corresponding data
Writing data is not enough , Now that you want to export the file , That must also be workbook Convert to binary stream again
function sheet2blob(workbook, wopts) {
// if (!wopts) {
// }
// Generate excel Configuration item reference for
var defaultWopts = {
bookType: 'xlsx', // The type of file to generate
bookSST: false, // Whether to generate Shared String Table, The official explanation is , If you turn on generate speed will decrease , But in the lower version IOS Better compatibility on the device
type: 'binary'
}
wopts = Object.assgin({
}, defaultWopts, wopts)
var wbout = XLSX.write(workbook, wopts)
var blob = new Blob([s2ab(wbout)], {
type: 'application/octet-stream' })
return blob
}
// String rotation ArrayBuffer
function s2ab(s) {
var buf = new ArrayBuffer(s.length)
var view = new Uint8Array(buf)
for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff
return buf
}
Normal table export
- The simplest table_to_sheet
var sheet = XLSX.utils.table_to_sheet($('table')[0])
const wb = XLSX.utils.book_new()
XLSX.utils.book_append_sheet(wb, sheet1, ' List of recipients ')
downLoadFile(sheet2blob(wb), ' export .xlsx')
- Two dimensional array export aoa_to_sheet
var aoa = [
[' full name ', ' Gender ', ' Age ', ' Registration time '],
[' Zhang San ', ' male ', 18, new Date()],
[' Li Si ', ' Woman ', 22, new Date()]
]
var sheet = XLSX.utils.aoa_to_sheet(aoa)
const wb = XLSX.utils.book_new()
XLSX.utils.book_append_sheet(wb, sheet, 'Sheet1')
downLoadFile(sheet2blob(wb), ' export .xlsx')
- Object type Export table_to_sheet
var arr = [
{
name: ' Zhang San ', sex: ' male ', age: 18, register: new Date() },
{
name: ' Li Si ', sex: ' Woman ', age: 22, register: new Date() }
]
// The key name is the header name , Value is the value of the corresponding column
var sheetData = arr.map(item => {
return {
full name : item.name,
Gender : item.sex,
Age : item.age,
Registration time : item.register
}
})
var sheet = XLSX.utils.json_to_sheet(sheetData)
const wb = XLSX.utils.book_new()
XLSX.utils.book_append_sheet(wb, sheet, 'Sheet1')
downLoadFile(sheet2blob(wb), ' export .xlsx')
Export of merged cells
The thing to note is that the merged cells should use null Reserved position
var aoa = [
[' Main information ', null, null, ' Other information '], // Pay special attention to the reserved space behind the merged place 2 individual null
[' full name ', ' Gender ', ' Age ', ' Registration time '],
[' Zhang San ', ' male ', 18, new Date()],
[' Li Si ', ' Woman ', 22, new Date()]
]
var sheet = XLSX.utils.aoa_to_sheet(aoa)
sheet['!merges'] = [
// Set up A1-C1 Merge cells
{
s: {
r: 0, c: 0 }, e: {
r: 0, c: 2 } }
]
const wb = XLSX.utils.book_new()
XLSX.utils.book_append_sheet(wb, sheet, 'Sheet1')
downLoadFile(sheet2blob(wb), ' Cell merge example .xlsx')
Last
In general, it will be used ,js-xlsx Provided API A lot of them , Finally, it also supports the export of complex headers , There are also many fun features , I studied it myself .
边栏推荐
- logrotate日志轮转方式create和copytruncate原理
- QT based travel query and simulation system
- manuscript手稿格式准备
- FormatConversionTool.exe
- Blue Bridge Cup 2015 CA provincial competition (filling the pit)
- postman传入list
- UML series articles (30) architecture modeling -- product diagram
- [the 11th national competition of Blue Bridge Cup single chip microcomputer]
- Signal relay rxsf1-rk271018dc110v
- Using stairs function in MATLAB
猜你喜欢

890. find and replace mode

視頻分類的類間和類內關系——正則化

VirtualBox virtual machine shut down due to abnormal system. The virtual machine startup item is missing

Selenium uses proxy IP

Pytorch笔记

Unity connect to Microsoft SQLSERVER database

Basic principle of Doppler effect

Blue Bridge Cup 2015 CA provincial competition (filling the pit)

Mysql45 lecture 01 | infrastructure: how is an SQL query executed?

你需要社交媒体二维码的21个理由
随机推荐
21 reasons why you need social media QR code
C# 36. DataGridView line number
Arm cross compilation chain download address
Byte order - how to judge the big end and the small end
Socket implements TCP communication flow
Google Earth Engine(GEE)——Kmeans聚类快速进行土地分类(双for循环快速调参)
【深度学习基础】神经网络的学习(4)
Byte order (network / host) conversion
单元测试用例框架--unittest
Unity connect to Microsoft SQLSERVER database
视频分类的类间和类内关系——正则化
Spark常用封装类
systemctl里万恶的203
当自己有台服务器之后
Drqueueonrails integrated LDAP authentication
Differences among various cross compiling tools of arm
ARM指令集之Load/Store访存指令(一)
ARM指令集之跳转指令
Signal relay rxsf1-rk271018dc110v
Design of tablewithpage