当前位置:网站首页>The tree form based on El table and JS xlsx realize the function of downloading excel (II)
The tree form based on El table and JS xlsx realize the function of downloading excel (II)
2022-07-23 11:22:00 【A big river depends on waves】
Catalog
This article mainly uses xlsx Download form , There are many references on the Internet
One 、 install xlsx
I only use the first three 
For the simplest use :
aoa_to_sheet Is to put an array arr Put one in sheet Page ,arr Similar to this structure
arr = [
[' full name ', ' Age ', ' Gender '],
[' Zhang San ', '18', ' male '],
[' Li Si ', '23', ' Woman '],
]
json_to_sheet Of json The data is as follows , It will automatically turn the key value into the header , Note that key values cannot be repeated
arr = [
{
' full name ': ' Zhang San ', ' Age ': '18', ' Gender ': ' male '},
{
' full name ': ' Li Si ', ' Age ': '23', ' Gender ': ' Woman '}
]
table_to_sheet The simplest , Your page shows such a table , Direct access to dom, Let's put this dom As a parameter .
Finally downloaded excel It's all the following 
Two 、 The downloaded table appears scientific counting
When the data is long , More than the 10 When a , excel Open to display the scientific count . The main reason is that cells treat it as a numerical value , Online The solution is to td Add style="mso-number-format:'\@';", But it seems useless , see xlsx file , Findings will be raw Set to true, Treat it as a string
raw: If true, every cell will hold raw strings
// raw by true The function of is to regard numbers as string
var sheet = XLSX.utils.table_to_sheet(objE.childNodes[0], {
raw: true })
3、 ... and 、 Code
Set up excel style
xlsx Currently, the changed style is limited , Only column width can be set , Merge cells, etc , More complex style changes can be seen xlsx-style
setExcelStyle() {
const obj = {
}
const colsNum = this.cmpColumns.length
// Dynamically add column width
for(let i = 0; i < colsNum; i++){
obj['!cols'].push({
wch: 15 })
}
/** merge cell - Merge one or two rows of the first column obj['!merges'] = [{ s: { // Start c: 0, r: 0, // 0 That's ok }, e: { // end c: 0, r: 1, // 1 That's ok }, }] */
return obj
},
Write as a tool function
/* * Tool function * @FilePath: assets\js\excel.js */
import XLSX from 'xlsx'
function s2ab(s) {
if (typeof ArrayBuffer !== 'undefined') {
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
} else {
var buf = new Array(s.length);
for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
}
function type2Excel({
data, style, type = "json", header = [], skipHeader = false}) {
//1、XLSX.utils.json_to_sheet(data) Receive an object array and return an automatically generated array based on the object keyword “ title ” The worksheet for , The default column order is used by Object.keys The first occurrence of the field is determined
//2、 Put data into objects workBook Of Sheets Waiting for output
let sheet = null
switch (type) {
case 'json':
sheet = Object.assign(XLSX.utils.json_to_sheet(data, {
header, skipHeader}), style)
break
case 'aoa':
sheet = Object.assign(XLSX.utils.aoa_to_sheet(data), style)
break
case 'dom':
sheet = Object.assign(XLSX.utils.table_to_sheet(data, {
raw: true }), style)
break
default:
break
}
return sheet
}
/** * @description: Pass in an array , The contents of the array object are sheetName, data, style, type = "json", header = {}, skipHeader = true * @param {*} sheets * @return {*} */
function genExcel(sheets){
var wopts = {
bookType: 'xlsx',
bookSST: false,
type: 'binary'
};
var workBook = {
SheetNames: [],
Sheets: {
},
Props: {
}
};
for(let sheet of sheets){
const name = sheet.sheetName
workBook.SheetNames.push(name)
workBook.Sheets[name] = type2Excel(sheet)
}
//3、XLSX.write() Start writing Excel form , s2ab() Process the data into the format that needs to be output
const blob = new Blob([s2ab(XLSX.write(workBook, wopts))], {
type: 'application/octet-stream'
})
return blob
}
export {
s2ab,
type2Excel,
genExcel
}
simulation a label , Click download function
/* * @Description: post The interface of the way , Or front-end download * @FilePath: assets\js\PostDLFile.js */
export default function postDLFile(data, name) {
let blob = data
let reader = new FileReader()
reader.readAsDataURL(blob)
reader.onload = (e) => {
let a = document.createElement('a')
a.download = `${
name}.xlsx`
a.href = e.target.result
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}
}
Download the use
downloadOrg(){
// This function is your own function for processing data , What kind of interface the data looks like
const data = this.genJsonForExcel()
const style = this.setExcelStyle()
const sheets = [{
sheetName:' Institutional data ', data, style, 'json'}]
postDLFile(genExcel(sheets), ' Download the excel name ')
},
边栏推荐
猜你喜欢

【C语言】什么是函数?函数的分类和侧重(帮你快速分类和记忆函数)

大厂面试机器学习算法(0):特征工程 | 数据预处理

When using cache in sprintboot, the data cannot be loaded

Error handling of "listener not started or database service not registered" in Oracle database creation

PyGame realizes the airplane war game

TypeScript 高级类型

牛客刷题记录--Mysql

【uiautomation】键指令大全(以及三种调用方式)+常用鼠标动作+SendKeys+Inspect学习

Machine learning algorithm for large factory interview (6) time series analysis
![[python flask notes 5] blueprint is easy to use](/img/0a/00b259f42e2fa83d4871263cc5f184.png)
[python flask notes 5] blueprint is easy to use
随机推荐
js的事件执行机制(Event loop)
【无标题】
[untitled]
Uscd pedestrian anomaly data set user guide | quick download
Redis数据库和项目框架
从零开始的pytorch小白使用指北
Install enterprise pycharm and Anaconda
大厂面试机器学习算法(5)推荐系统算法
Hyperlink de underlined code
Matrix vector derivation in machine learning
【无标题】
排序、限流
Spark常见面试问题整理
Five methods to prevent over fitting of neural network
Project process summary
uni-app小程序中v-show与display:flex一起使用时v-show不生效!
使用el-table懒加载树形表格时的注意点
js高阶函数
$attrs中的对象没有变化,但触发了watch监听?
JS call, apply, bind