You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
2.7 KiB
JavaScript

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

layui.config({
base: './../../static/layui/layui_exts/'
}).use(['table', 'excel'], function () {
var table = layui.table //表格
,
$ = layui.$,
excel = layui.excel;
$('#LAY-excel-import-excel').change(function (e) {
// 注意:这里直接引用 e.target.files 会导致 FileList 对象在读取之前变化,导致无法弹出文件
var files = Object.values(e.target.files)
uploadExcel(files)
// 变更完清空,否则选择同一个文件不触发此事件
e.target.value = ''
})
// 文件拖拽
document.body.ondragover = function (e) {
e.preventDefault()
}
document.body.ondrop = function (e) {
e.preventDefault()
var files = e.dataTransfer.files
uploadExcel(files)
}
if (!Array.from) {
Array.from = function (el) {
return Array.apply(this, el);
}
}
/**
* 上传excel的处理函数传入文件对象数组
* @param {FileList} files [description]
* @return {[type]} [description]
*/
function uploadExcel(files) {
try {
excel.importExcel(files, {
// 可以在读取数据的同时梳理数据
/*fields: {
'id': 'A'
, 'username': 'B'
, 'experience': 'C'
, 'sex': 'D'
, 'score': 'E'
, 'city': 'F'
, 'classify': 'G'
, 'wealth': 'H'
, 'sign': 'I'
}*/
}, function (data, book) {
// data: {1: {sheet1: [{id: 1, name: 2}, {...}]}}// 工作表的数据对象
// book: {1: {Sheets: {}, Props: {}, ....}} // 工作表的整个原生对象https://github.com/SheetJS/js-xlsx#workbook-object
// 也可以全部读取出来再进行数据梳理
/* data = excel.filterImportData(data, {
'id': 'A'
, 'username': 'B'
, 'experience': 'C'
, 'sex': 'D'
, 'score': 'E'
, 'city': 'F'
, 'classify': 'G'
, 'wealth': 'H'
, 'sign': 'I'
})*/
// 如果不需要展示直接上传,可以再次 $.ajax() 将JSON数据通过 JSON.stringify() 处理后传递到后端即可
/**
* 2019-06-21 JeffreyWang 应群友需求,加一个单元格合并还原转换
* 思路:
* 1. 渲染时为每个cell加上唯一的IDdemo里边采用 table-export-文件索引-sheet名称-行索引-列索引
* 2. 根据 book[文件索引].Sheets[sheet名称]['!merge'] 参数,取左上角元素设置 colspan 以及 rowspan并删除其他元素
*/
console.log(data, book);
})
} catch (e) {
layer.alert(e.message)
}
}
});