rt-sim-training-client/src/utils/Export2Excel.js
sunzhenyu 7d98ea5f18 pull
2019-10-17 18:49:19 +08:00

339 lines
12 KiB
JavaScript

/* eslint-disable */
require('script-loader!file-saver');
require('@/utils/Blob');
import XLSX from 'xlsx';
import { translate } from '@/scripts/translate';
import { translateSame } from '@/scripts/translateSame';
function generateArray(table) {
var out = [];
var rows = table.querySelectorAll('tr');
var ranges = [];
for (var R = 0; R < rows.length; ++R) {
var outRow = [];
var row = rows[R];
var columns = row.querySelectorAll('td');
for (var C = 0; C < columns.length; ++C) {
var cell = columns[C];
var colspan = cell.getAttribute('colspan');
var rowspan = cell.getAttribute('rowspan');
var cellValue = cell.innerText;
if (cellValue !== "" && cellValue == +cellValue) cellValue = +cellValue;
//Skip ranges
ranges.forEach(function (range) {
if (R >= range.s.r && R <= range.e.r && outRow.length >= range.s.c && outRow.length <= range.e.c) {
for (var i = 0; i <= range.e.c - range.s.c; ++i) outRow.push(null);
}
});
//Handle Row Span
if (rowspan || colspan) {
rowspan = rowspan || 1;
colspan = colspan || 1;
ranges.push({ s: { r: R, c: outRow.length }, e: { r: R + rowspan - 1, c: outRow.length + colspan - 1 } });
}
;
//Handle Value
outRow.push(cellValue !== "" ? cellValue : null);
//Handle Colspan
if (colspan) for (var k = 0; k < colspan - 1; ++k) outRow.push(null);
}
out.push(outRow);
}
return [out, ranges];
};
function datenum(v, date1904) {
if (date1904) v += 1462;
var epoch = Date.parse(v);
return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
}
function sheet_from_array_of_arrays(data, opts) {
var ws = {};
var range = { s: { c: 10000000, r: 10000000 }, e: { c: 0, r: 0 } };
for (var R = 0; R != data.length; ++R) {
for (var C = 0; C != data[R].length; ++C) {
if (range.s.r > R) range.s.r = R;
if (range.s.c > C) range.s.c = C;
if (range.e.r < R) range.e.r = R;
if (range.e.c < C) range.e.c = C;
var cell = { v: data[R][C], t: 's' };
if (cell.v == null) continue;
var cell_ref = XLSX.utils.encode_cell({ c: C, r: R });
if (typeof cell.v === 'number') cell.t = 'n';
else if (typeof cell.v === 'boolean') cell.t = 'b';
else if (typeof cell.v === 'object') {
cell.t = 'o';
cell.v = JSON.stringify(cell.v);
cell.h = 'o';
}
else if (cell.v instanceof Date) {
cell.t = 'n';
cell.z = XLSX.SSF._table[14];
cell.v = datenum(cell.v);
}
// else cell.t = 's';
ws[cell_ref] = cell;
}
}
if (range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range);
return ws;
}
function encode_row(row) { return "" + (row + 1); };
function encode_col(col) { var s = ""; for (++col; col; col = Math.floor((col - 1) / 26)) s = String.fromCharCode(((col - 1) % 26) + 65) + s; return s; }
function safe_format_cell(cell, v) {
var q = (cell.t == 'd' && v instanceof Date);
if (cell.z != null) try { return (cell.w = SSF.format(cell.z, q ? datenum(v) : v)); } catch (e) { }
try { return (cell.w = SSF.format((cell.XF || {}).numFmtId || (q ? 14 : 0), q ? datenum(v) : v)); } catch (e) { return '' + v; }
}
function format_cell(cell, v, o) {
if (cell == null || cell.t == null || cell.t == 'z') return '';
if (cell.t == 'b' || cell.t == 'n') return cell.v;
if (cell.t == 'o') return JSON.parse(cell.v);
if (cell.w !== undefined) return cell.w;
// if (cell.v !== undefined) return cell.v;
if (v == undefined) return safe_format_cell(cell, cell.v);
return safe_format_cell(cell, v);
}
export function sheet_to_json(sheet, opts) {
if (sheet == null || sheet["!ref"] == null) return [];
var val = { t: 'n', v: 0 }, header = 0, offset = 1, hdr = [], isempty = true, v = 0, vv = "";
var r = { s: { r: 0, c: 0 }, e: { r: 0, c: 0 } };
var o = opts || {};
var raw = o.raw;
var defval = o.defval;
var range = o.range != null ? o.range : sheet["!ref"];
if (o.header === 1) header = 1;
else if (o.header === "A") header = 2;
else if (Array.isArray(o.header)) header = 3;
switch (typeof range) {
case 'string': r = safe_decode_range(range); break;
case 'number': r = safe_decode_range(sheet["!ref"]); r.s.r = range; break;
default: r = range;
}
if (header > 0) offset = 0;
var rr = encode_row(r.s.r);
var cols = [];
var out = [];
var outi = 0, counter = 0;
var dense = Array.isArray(sheet);
var R = r.s.r, C = 0, CC = 0;
if (dense && !sheet[R]) sheet[R] = [];
for (C = r.s.c; C <= r.e.c; ++C) {
cols[C] = encode_col(C);
val = dense ? sheet[R][C] : sheet[cols[C] + rr];
switch (header) {
case 1: hdr[C] = C - r.s.c; break;
case 2: hdr[C] = cols[C]; break;
case 3: hdr[C] = o.header[C - r.s.c]; break;
default:
if (val == null) val = { w: "__EMPTY", t: "s" };
vv = v = format_cell(val, null, o);
counter = 0;
for (CC = 0; CC < hdr.length; ++CC) if (hdr[CC] == vv) vv = v + "_" + (++counter);
hdr[C] = vv;
}
}
var row = (header === 1) ? [] : {};
for (R = r.s.r + offset; R <= r.e.r; ++R) {
rr = encode_row(R);
isempty = true;
if (header === 1) row = [];
else {
row = {};
if (Object.defineProperty) try { Object.defineProperty(row, '__rowNum__', { value: R, enumerable: false }); } catch (e) { row.__rowNum__ = R; }
else row.__rowNum__ = R;
}
if (!dense || sheet[R]) for (C = r.s.c; C <= r.e.c; ++C) {
val = dense ? sheet[R][C] : sheet[cols[C] + rr];
if (val === undefined || val.t === undefined) {
if (defval === undefined) continue;
if (hdr[C] != null) { row[hdr[C]] = defval; }
continue;
}
v = val.v;
switch (val.t) {
case 'z': if (v == null) break; continue;
case 'e': v = void 0; break;
case 's': case 'd': case 'b': case 'n': break;
default: throw new Error('unrecognized type ' + val.t);
}
if (hdr[C] != null) {
if (v == null) {
if (defval !== undefined) row[hdr[C]] = defval;
else if (raw && v === null) row[hdr[C]] = null;
else continue;
} else {
row[hdr[C]] = raw ? v : format_cell(val, v, o);
}
if (v != null) isempty = false;
}
}
if ((isempty === false) || (header === 1 ? o.blankrows !== false : !!o.blankrows)) out[outi++] = row;
}
out.length = outi;
return out;
}
function safe_decode_range(range) {
var o = { s: { c: 0, r: 0 }, e: { c: 0, r: 0 } };
var idx = 0, i = 0, cc = 0;
var len = range.length;
for (idx = 0; i < len; ++i) {
if ((cc = range.charCodeAt(i) - 64) < 1 || cc > 26) break;
idx = 26 * idx + cc;
}
o.s.c = --idx;
for (idx = 0; i < len; ++i) {
if ((cc = range.charCodeAt(i) - 48) < 0 || cc > 9) break;
idx = 10 * idx + cc;
}
o.s.r = --idx;
if (i === len || range.charCodeAt(++i) === 58) { o.e.c = o.s.c; o.e.r = o.s.r; return o; }
for (idx = 0; i != len; ++i) {
if ((cc = range.charCodeAt(i) - 64) < 1 || cc > 26) break;
idx = 26 * idx + cc;
}
o.e.c = --idx;
for (idx = 0; i != len; ++i) {
if ((cc = range.charCodeAt(i) - 48) < 0 || cc > 9) break;
idx = 10 * idx + cc;
}
o.e.r = --idx;
return o;
}
function Workbook() {
if (!(this instanceof Workbook)) return new Workbook();
this.SheetNames = [];
this.Sheets = {};
}
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;
}
export function export_table_to_excel(id) {
var theTable = document.getElementById(id);
var oo = generateArray(theTable);
var ranges = oo[1];
/* original data */
var data = oo[0];
var ws_name = "SheetJS";
var wb = new Workbook(), ws = sheet_from_array_of_arrays(data);
/* add ranges to worksheet */
// ws['!cols'] = ['apple', 'banan'];
ws['!merges'] = ranges;
/* add worksheet to workbook */
wb.SheetNames.push(ws_name);
wb.Sheets[ws_name] = ws;
var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: false, type: 'binary' });
saveAs(new Blob([s2ab(wbout)], { type: "application/octet-stream" }), "test.xlsx")
}
function formatJson(filterVal, jsonData) {
return jsonData.map(v => filterVal.map(j => v[j]))
}
export function export_json_to_excel(th, jsonData, defaultTitle) {
/* original data */
var data = jsonData;
data.unshift(th);
var ws_name = "SheetJS";
var wb = new Workbook(), ws = sheet_from_array_of_arrays(data);
/* add worksheet to workbook */
wb.SheetNames.push(ws_name);
wb.Sheets[ws_name] = ws;
var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: false, type: 'binary' });
var title = defaultTitle || '列表'
saveAs(new Blob([s2ab(wbout)], { type: "application/octet-stream" }), title + ".xlsx")
}
// 转换数据格式
function handelData(translate, key) {
let tHeader = [];
let tHeaderF = [];
if (translate[key]) {
translate[key].columns.forEach(item => {
tHeader.push(item.tHeader);
tHeaderF.push(item.key);
});
}
let filterVal = {
tHeader: tHeader,
tHeaderF: tHeaderF,
};
return filterVal;
}
export function export_json_excel(jsonData, defaultTitle) {
let data = jsonData;
let wb = new Workbook();
for (let index in data) {
let filterVal = handelData(translate, index);
if (filterVal.tHeader.length) {
let dataDetail = formatJson(filterVal.tHeaderF, data[index]);
dataDetail.unshift(filterVal.tHeader); // 设置表头的
let ws = sheet_from_array_of_arrays(dataDetail);
/* add worksheet to workbook */
let title = translate[index].sheetName || index;
wb.SheetNames.push(title);
wb.Sheets[`${title}`] = ws;
}
}
let wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: false, type: 'binary' });
var title = defaultTitle || '列表'
saveAs(new Blob([s2ab(wbout)], { type: "application/octet-stream" }), title + ".xlsx")
}
export function export_json_excel_same(jsonData, defaultTitle) {
let data = jsonData;
let wb = new Workbook();
for (let index in data) {
let filterVal = handelData(translateSame, index);
if (filterVal.tHeader.length) {
let dataDetail = formatJson(filterVal.tHeaderF, data[index]);
dataDetail.unshift(filterVal.tHeader); // 设置表头的
let ws = sheet_from_array_of_arrays(dataDetail);
/* add worksheet to workbook */
let title = translate[index].sheetName || index;
wb.SheetNames.push(title);
wb.Sheets[`${title}`] = ws;
}
}
let wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: false, type: 'binary' });
var title = defaultTitle || '列表'
saveAs(new Blob([s2ab(wbout)], { type: "application/octet-stream" }), title + ".xlsx")
}