add scripts

This commit is contained in:
Cody Zhang
2020-10-08 17:31:39 +08:00
parent 9463e1dcbd
commit ff9710dc08
8 changed files with 21044 additions and 235 deletions

411
scripts/excelJS_helper.js Normal file
View File

@@ -0,0 +1,411 @@
/**
* 需要 ExcelJS 套件
* 提供一些 function可以把呼叫 ExcelJS 的方法,把 html 的 table 轉成 excel
*/
// let namespace = window.exhelper;
(function (ns) {
'use strict';
// create a self-reference
var _self = ns;
/**
* 以 0 為起始的行、列座標
* @param {Number} col 行座標
* @param {Number} row 列座標
*/
_self.CellCoordinate = function (col, row) {
this.col = col || 0;
this.row = row || 0;
}
/**
* 每格的資料
* @param {String} addr 位址 (A1, A2...)
* @param {Any} val 值
* @param {Object} style 格式
* @param {Number} type 型別 (預設 3 string)
*/
_self.CellData = function(addr, val, style, type){
this.address = addr || "";
this.value = val || "";
this.style = style || {};
this.type = type || 3;
}
/**
* 合併欄位的資料
* @param {Number} top
* @param {Number} left
* @param {Number} bottom
* @param {Number} right
*/
_self.MergedRange = function(top, left, bottom, right){
this.top = top || 0;
this.left = left || 0;
this.bottom = bottom || 0;
this.right = right || 0;
}
/**
* 傳入 CellCoordinate { col: 0, row: 0 } 回傳 A1
* @param {CellCoordinate} coordinate
* @return {String} 格位標記
*/
_self.parseCelltoTag = function (coordinate) {
if (parseInt(coordinate.col) < 0) {
console.log("傳入參數有誤Coordinate 的 col 要大於 0");
return;
}
return _self.getAlphabetByInt(parseInt(coordinate.col)) + (parseInt(coordinate.row) + 1);
}
/**
* 傳入數字,回傳對應的字母 ( 0=>A, 1=>B...)
* @param {Number} idx 要對應的數字
* @param {Number} alphabetBase 要用幾個字母去對應,預設 26最大 26
*/
_self.getAlphabetByInt = function (idx, alphabetBase) {
if (!alphabetBase)
alphabetBase = 26;
let alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// 在 base 內,一個字母就可以處理
if (idx < alphabetBase) {
return alphabets.charAt(idx);
}
let result = "";
let quotient = idx;
while (quotient >= alphabetBase) {
let mod = quotient % alphabetBase;
quotient = Math.floor(idx / alphabetBase);
result = alphabets.charAt(mod) + result;
}
// 最後一碼
result = alphabets.charAt(quotient - 1) + result;
return result;
}
/**
* 傳入字母,回傳對應的數值 ( A=>0, B=>2...)
* @param {String} a 要對應的字串
* @param {Number} alphabetBase 要用幾個字母去對應,預設 26最大 26
*/
_self.getIdxByAlphbet = function (a, alphabetBase) {
if (!alphabetBase)
alphabetBase = 26;
let alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// 全部轉大寫
a = a.toUpperCase();
let result = 0;
for (let i = 0; i < a.length; i++) {
// 如果是第二碼以上,就要加 1 再去乘
let modifier = (i == 0) ? 0 : 1;
result += (alphabets.indexOf(a.charAt(a.length - (i + 1))) + modifier) * Math.pow(alphabetBase, i);
}
return result;
}
/**
* 傳入格位代碼,回傳以 0 起始的座標物件
* @param {String} tag 格位代碼 (A1, A2...)
* @return {CellCoordinate} { col: 0, row: 0}
*/
_self.parseCelltoCoordinate = function (tag) {
let re = /(\w+)(\d+)/;
let match = tag.match(re);
return new _self.CellCoordinate(_self.getIdxByAlphbet(match[1]), parseInt(match[2]) - 1);
}
/**
* 儲存 Blob 資料至下載檔案
* @param {String} fileName 檔案名稱(含副檔名)
* @param {object} byte 檔案內容 byte 陣列
*/
_self.saveBlob = function (fileName, byte) {
var blob = new Blob([byte], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
});
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
// for IE
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else {
// for other browsers
var url = window.URL.createObjectURL(blob, {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
});
/*
var a = $("<a style='display: none;'/>");
a.attr("href", url);
a.attr("download", fileName);
$("body").append(a);
a[0].click();
window.URL.revokeObjectURL(url);
a.remove();
*/
var a = document.createElement("a");
a.style.display = "none";
a.setAttribute("href", url);
a.setAttribute("download", fileName);
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
a.remove();
}
}
/**
* 將 ExcelJS.Workbook 物件存成 excel 檔案,並開始下載
* @param {String} filename 檔案名稱含副檔名
* @param {object} Workbook 物件
*/
_self.saveXlsx = function (filename, wb) {
wb.xlsx.writeBuffer().then(
function (result) {
_self.saveBlob(filename, result);
},
function (err) {
console.log("error: ", err);
}
);
}
/**
* 傳入 table 物件,回傳 ExcelJS.Workbook 物件
* @param {object} elt table 物件
* @param {object} opt 屬性設定 => { sheet: "sheet 名稱 預設 Sheet1" }
* @return {object} ExcelJS.Workbook 物件
*/
_self.tableToBook = function (elt, opt) {
if (!opt)
opt = {};
// 沒有這個方法 => 可能是 jquery 物件,要轉成原始的 html 物件
if (!elt.getElementsByTagName)
elt = elt.get(0);
var wb = new ExcelJS.Workbook();
wb.creator = "gamapay";
wb.lastModifiedBy = "gamapay";
wb.created = new Date();
wb.modified = new Date();
let sheetName = opt.sheet || "Sheet1";
// Set workbook dates to 1904 date system
wb.properties.date1904 = true;
var ws = wb.addWorksheet(sheetName);
var rows = elt.getElementsByTagName("tr");
var mergedCells = new Array(rows.length);
for (let i = 0; i < rows.length; i++) {
// 取得格位資料
var cols = rows[i].querySelectorAll("th,td");
// 計算要右移幾格 (因為合併)
let shiftCell = 0;
for (let j = 0; j < cols.length; j++) {
let colElem = cols[j];
let colspan = colElem.getAttribute("colspan");
let rowspan = colElem.getAttribute("rowspan");
let colValue = colElem.innerHTML;
// 如果有值,就進行移除所有的 html tag 運算
if (colValue) {
colValue = colValue.replace(/<\/?[^>]+(>|$)/g, "");
}
// 初始化本列的合併格位陣列 (如果是合併列的話,可能已經有初始化了)
if (!mergedCells[i])
mergedCells[i] = [];
// 檢查目前的格位有沒有在合併欄位中,有的話就右移一格
while (mergedCells[i].indexOf(j + shiftCell) >= 0) {
shiftCell++;
}
// 目前的格位 (位移後)
let currCell = new _self.CellCoordinate(j + shiftCell, i);
// 轉成 tag
let currTag = _self.parseCelltoTag(currCell);
// 設定本格的值
ws.getCell(currTag).value = colValue;
// 是否有合併欄位
let hasMerge = false;
// 要合併欄位
let toCell = new _self.CellCoordinate(j + shiftCell, i);
if (colspan && colspan != 1) {
hasMerge = true;
toCell.col += parseInt(colspan) - 1;
}
if (rowspan && rowspan != 1) {
hasMerge = true;
toCell.row += parseInt(rowspan) - 1;
}
if (hasMerge) {
// 把合併的欄位加到陣列中
for (let idr = currCell.row; idr <= toCell.row; idr++) {
// 如果是列之間的合併格位,會遇到還沒有初始化,所以在這要初始化
if (!mergedCells[idr])
mergedCells[idr] = [];
for (let idx = currCell.col; idx <= toCell.col; idx++) {
// 將合併的欄位加到陣列中
mergedCells[idr].push(idx);
}
}
// 將要合併的欄位轉成 tag
let toTag = _self.parseCelltoTag(toCell);
// 進行合併
ws.mergeCells(currTag + ":" + toTag);
}
}
}
return wb;
}
/**
* 在指定位置插入指定行數的空行
* @param {Object} sheet Worksheet object
* @param {Number} pos 要插入的位置
* @param {Number} cnt 要插入幾行
*/
_self.insertRows = function (sheet, pos, cnt){
// 建立要合併的欄位
var merged = [];
// 每個合併的欄位向下一行
for(let cell in sheet._merges){
let model = sheet._merges[cell].model;
let range = new _self.MergedRange(model.top, model.left, model.bottom, model.right);
merged.push(range);
// 清除 merge 資訊
sheet.unMergeCells(cell);
}
// 紀錄所有格位資料
let cells = [];
sheet.eachRow(function(row, rowNumber) {
row.eachCell(function(cell, colNumber){
let model = cell._value.model;
let cellData = new _self.CellData(model.address, model.value, model. style, model.type);
cells.push(cellData);
});
});
// 清空所有資料
sheet._rows = [];
sheet._columns = [];
for(let i = 0; i < cells.length; i++){
let cell = cells[i];
let cellCoordinate = _self.parseCelltoCoordinate(cell.address);
// col 原則上不會變
let newCol = cellCoordinate.col + 1;
let newRow = cellCoordinate.row + 1;
console.log(cell.value, newRow, pos);
// row 依插入幾行而變
if(newRow >= pos){
newRow = newRow + cnt;
}
// 將原本的值寫入
sheet.getRow(newRow).getCell(newCol).value = cell.value;
}
// 重新 merge
for(let i = 0; i < merged.length; i++){
let range = merged[i];
// 如果插入的行在merge行的中間那就不進行merge
if(range.top > pos && range.bottom <= pos)
continue;
// 原本合併的行在插入行之下,下移指定行數
// ,在插入行之上,維持不變
if(range.top >= pos){
range.top += cnt;
range.bottom += cnt;
}
// 進行合併
sheet.mergeCells(range.top, range.left, range.bottom, range.right);
}
}
/**
* 為 worksheet 物件增加表頭
* @param {object} sheet ExcelJS.Worksheet 物件
* @param {String} title 表頭
*/
_self.addTitle = function (sheet, title) {
_self.insertRows(sheet, 1, 1);
// 插入表頭
sheet.mergeCells(1, 1, 1, sheet.columnCount);
let titleCell = sheet.getRow(1).getCell(1);
titleCell.value = title;
titleCell.alignment = { vertical: 'middle', horizontal: 'center' };
titleCell.font = { bold: true };
}
// reasign everything just incase
_self = ns;
})(window.exhelper = window.exhelper || {});

2
scripts/jquery-3.5.1.min.js vendored Normal file

File diff suppressed because one or more lines are too long

10872
scripts/jquery.js vendored Normal file

File diff suppressed because it is too large Load Diff

14
scripts/myjs.js Normal file
View File

@@ -0,0 +1,14 @@
requirejs([
"https://cdn.jsdelivr.net/npm/core-js@3.6.5/modules/es.promise.min.js",
"https://cdn.jsdelivr.net/npm/core-js@3.6.5/modules/es.string.includes.min.js",
"https://cdn.jsdelivr.net/npm/core-js@3.6.5/modules/es.object.assign.min.js",
"https://cdn.jsdelivr.net/npm/core-js@3.6.5/modules/es.object.keys.min.js",
"https://cdn.jsdelivr.net/npm/core-js@3.6.5/modules/es.symbol.min.js",
"https://cdn.jsdelivr.net/npm/core-js@3.6.5/modules/es.symbol.async-iterator.min.js",
"https://cdn.jsdelivr.net/npm/regenerator-runtime@0.13.7/runtime.min.js",
"https://cdnjs.cloudflare.com/ajax/libs/exceljs/4.1.1/exceljs.js"
], function(es1, es2, es3, es4, es5, es6, es7, exceljs){
$(function(){
console.log("test");
});
})

7087
scripts/polyfill.js Normal file

File diff suppressed because it is too large Load Diff

2145
scripts/require.js Normal file

File diff suppressed because it is too large Load Diff

397
scripts/rewrite-pattern.js Normal file
View File

@@ -0,0 +1,397 @@
'use strict';
function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
var generate = require('regjsgen').generate;
var parse = require('regjsparser').parse;
var regenerate = require('regenerate');
var unicodeMatchProperty = require('unicode-match-property-ecmascript');
var unicodeMatchPropertyValue = require('unicode-match-property-value-ecmascript');
var iuMappings = require('./data/iu-mappings.js');
var ESCAPE_SETS = require('./data/character-class-escape-sets.js'); // Prepare a Regenerate set containing all code points, used for negative
// character classes (if any).
var UNICODE_SET = regenerate().addRange(0x0, 0x10FFFF); // Without the `u` flag, the range stops at 0xFFFF.
// https://mths.be/es6#sec-pattern-semantics
var BMP_SET = regenerate().addRange(0x0, 0xFFFF); // Prepare a Regenerate set containing all code points that are supposed to be
// matched by `/./u`. https://mths.be/es6#sec-atom
var DOT_SET_UNICODE = UNICODE_SET.clone() // all Unicode code points
.remove( // minus `LineTerminator`s (https://mths.be/es6#sec-line-terminators):
0x000A, // Line Feed <LF>
0x000D, // Carriage Return <CR>
0x2028, // Line Separator <LS>
0x2029 // Paragraph Separator <PS>
);
var getCharacterClassEscapeSet = function getCharacterClassEscapeSet(character, unicode, ignoreCase) {
if (unicode) {
if (ignoreCase) {
return ESCAPE_SETS.UNICODE_IGNORE_CASE.get(character);
}
return ESCAPE_SETS.UNICODE.get(character);
}
return ESCAPE_SETS.REGULAR.get(character);
};
var getUnicodeDotSet = function getUnicodeDotSet(dotAll) {
return dotAll ? UNICODE_SET : DOT_SET_UNICODE;
};
var getUnicodePropertyValueSet = function getUnicodePropertyValueSet(property, value) {
var path = value ? "".concat(property, "/").concat(value) : "Binary_Property/".concat(property);
try {
return require("regenerate-unicode-properties/".concat(path, ".js"));
} catch (exception) {
throw new Error("Failed to recognize value `".concat(value, "` for property ") + "`".concat(property, "`."));
}
};
var handleLoneUnicodePropertyNameOrValue = function handleLoneUnicodePropertyNameOrValue(value) {
// It could be a `General_Category` value or a binary property.
// Note: `unicodeMatchPropertyValue` throws on invalid values.
try {
var _property = 'General_Category';
var category = unicodeMatchPropertyValue(_property, value);
return getUnicodePropertyValueSet(_property, category);
} catch (exception) {} // Its not a `General_Category` value, so check if its a binary
// property. Note: `unicodeMatchProperty` throws on invalid properties.
var property = unicodeMatchProperty(value);
return getUnicodePropertyValueSet(property);
};
var getUnicodePropertyEscapeSet = function getUnicodePropertyEscapeSet(value, isNegative) {
var parts = value.split('=');
var firstPart = parts[0];
var set;
if (parts.length == 1) {
set = handleLoneUnicodePropertyNameOrValue(firstPart);
} else {
// The pattern consists of two parts, i.e. `Property=Value`.
var property = unicodeMatchProperty(firstPart);
var _value = unicodeMatchPropertyValue(property, parts[1]);
set = getUnicodePropertyValueSet(property, _value);
}
if (isNegative) {
return UNICODE_SET.clone().remove(set);
}
return set.clone();
}; // Given a range of code points, add any case-folded code points in that range
// to a set.
regenerate.prototype.iuAddRange = function (min, max) {
var $this = this;
do {
var folded = caseFold(min);
if (folded) {
$this.add(folded);
}
} while (++min <= max);
return $this;
};
var update = function update(item, pattern) {
var tree = parse(pattern, config.useUnicodeFlag ? 'u' : '');
switch (tree.type) {
case 'characterClass':
case 'group':
case 'value':
// No wrapping needed.
break;
default:
// Wrap the pattern in a non-capturing group.
tree = wrap(tree, pattern);
}
Object.assign(item, tree);
};
var wrap = function wrap(tree, pattern) {
// Wrap the pattern in a non-capturing group.
return {
'type': 'group',
'behavior': 'ignore',
'body': [tree],
'raw': "(?:".concat(pattern, ")")
};
};
var caseFold = function caseFold(codePoint) {
return iuMappings.get(codePoint) || false;
};
var processCharacterClass = function processCharacterClass(characterClassItem, regenerateOptions) {
var set = regenerate();
var _iterator = _createForOfIteratorHelper(characterClassItem.body),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var item = _step.value;
switch (item.type) {
case 'value':
set.add(item.codePoint);
if (config.ignoreCase && config.unicode && !config.useUnicodeFlag) {
var folded = caseFold(item.codePoint);
if (folded) {
set.add(folded);
}
}
break;
case 'characterClassRange':
var min = item.min.codePoint;
var max = item.max.codePoint;
set.addRange(min, max);
if (config.ignoreCase && config.unicode && !config.useUnicodeFlag) {
set.iuAddRange(min, max);
}
break;
case 'characterClassEscape':
set.add(getCharacterClassEscapeSet(item.value, config.unicode, config.ignoreCase));
break;
case 'unicodePropertyEscape':
set.add(getUnicodePropertyEscapeSet(item.value, item.negative));
break;
// The `default` clause is only here as a safeguard; it should never be
// reached. Code coverage tools should ignore it.
/* istanbul ignore next */
default:
throw new Error("Unknown term type: ".concat(item.type));
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
if (characterClassItem.negative) {
update(characterClassItem, "(?!".concat(set.toString(regenerateOptions), ")[\\s\\S]"));
} else {
update(characterClassItem, set.toString(regenerateOptions));
}
return characterClassItem;
};
var updateNamedReference = function updateNamedReference(item, index) {
delete item.name;
item.matchIndex = index;
};
var assertNoUnmatchedReferences = function assertNoUnmatchedReferences(groups) {
var unmatchedReferencesNames = Object.keys(groups.unmatchedReferences);
if (unmatchedReferencesNames.length > 0) {
throw new Error("Unknown group names: ".concat(unmatchedReferencesNames));
}
};
var processTerm = function processTerm(item, regenerateOptions, groups) {
switch (item.type) {
case 'dot':
if (config.useDotAllFlag) {
break;
} else if (config.unicode) {
update(item, getUnicodeDotSet(config.dotAll).toString(regenerateOptions));
} else if (config.dotAll) {
// TODO: consider changing this at the regenerate level.
update(item, '[\\s\\S]');
}
break;
case 'characterClass':
item = processCharacterClass(item, regenerateOptions);
break;
case 'unicodePropertyEscape':
if (config.unicodePropertyEscape) {
update(item, getUnicodePropertyEscapeSet(item.value, item.negative).toString(regenerateOptions));
}
break;
case 'characterClassEscape':
update(item, getCharacterClassEscapeSet(item.value, config.unicode, config.ignoreCase).toString(regenerateOptions));
break;
case 'group':
if (item.behavior == 'normal') {
groups.lastIndex++;
}
if (item.name && config.namedGroup) {
var name = item.name.value;
if (groups.names[name]) {
throw new Error("Multiple groups with the same name (".concat(name, ") are not allowed."));
}
var index = groups.lastIndex;
delete item.name;
groups.names[name] = index;
if (groups.onNamedGroup) {
groups.onNamedGroup.call(null, name, index);
}
if (groups.unmatchedReferences[name]) {
groups.unmatchedReferences[name].forEach(function (reference) {
updateNamedReference(reference, index);
});
delete groups.unmatchedReferences[name];
}
}
/* falls through */
case 'alternative':
case 'disjunction':
case 'quantifier':
item.body = item.body.map(function (term) {
return processTerm(term, regenerateOptions, groups);
});
break;
case 'value':
var codePoint = item.codePoint;
var set = regenerate(codePoint);
if (config.ignoreCase && config.unicode && !config.useUnicodeFlag) {
var folded = caseFold(codePoint);
if (folded) {
set.add(folded);
}
}
update(item, set.toString(regenerateOptions));
break;
case 'reference':
if (item.name) {
var _name = item.name.value;
var _index = groups.names[_name];
if (_index) {
updateNamedReference(item, _index);
break;
}
if (!groups.unmatchedReferences[_name]) {
groups.unmatchedReferences[_name] = [];
} // Keep track of references used before the corresponding group.
groups.unmatchedReferences[_name].push(item);
}
break;
case 'anchor':
case 'empty':
case 'group':
// Nothing to do here.
break;
// The `default` clause is only here as a safeguard; it should never be
// reached. Code coverage tools should ignore it.
/* istanbul ignore next */
default:
throw new Error("Unknown term type: ".concat(item.type));
}
return item;
};
var config = {
'ignoreCase': false,
'unicode': false,
'dotAll': false,
'useDotAllFlag': false,
'useUnicodeFlag': false,
'unicodePropertyEscape': false,
'namedGroup': false
};
var rewritePattern = function rewritePattern(pattern, flags, options) {
config.unicode = flags && flags.includes('u');
var regjsparserFeatures = {
'unicodePropertyEscape': config.unicode,
'namedGroups': true,
'lookbehind': options && options.lookbehind
};
config.ignoreCase = flags && flags.includes('i');
var supportDotAllFlag = options && options.dotAllFlag;
config.dotAll = supportDotAllFlag && flags && flags.includes('s');
config.namedGroup = options && options.namedGroup;
config.useDotAllFlag = options && options.useDotAllFlag;
config.useUnicodeFlag = options && options.useUnicodeFlag;
config.unicodePropertyEscape = options && options.unicodePropertyEscape;
if (supportDotAllFlag && config.useDotAllFlag) {
throw new Error('`useDotAllFlag` and `dotAllFlag` cannot both be true!');
}
var regenerateOptions = {
'hasUnicodeFlag': config.useUnicodeFlag,
'bmpOnly': !config.unicode
};
var groups = {
'onNamedGroup': options && options.onNamedGroup,
'lastIndex': 0,
'names': Object.create(null),
// { [name]: index }
'unmatchedReferences': Object.create(null) // { [name]: Array<reference> }
};
var tree = parse(pattern, flags, regjsparserFeatures); // Note: `processTerm` mutates `tree` and `groups`.
processTerm(tree, regenerateOptions, groups);
assertNoUnmatchedReferences(groups);
return generate(tree);
};
module.exports = rewritePattern;

351
test.html
View File

@@ -3,248 +3,129 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>測試檔案</title>
<style>
table {
border: solid black 1px;
}
tr {
border: solid black 1px;
}
th {
border: solid black 1px;
}
td {
border: solid black 1px;
}
</style>
<!-- <script src="scripts/polyfill.js"></script> -->
<script src="https://cdn.jsdelivr.net/npm/@babel/polyfill@7.11.5/dist/polyfill.js"
integrity="sha256-zMiIDM5XypPGREBv9Hmb5fNhRS727Fuldppe2Gv565Y=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/exceljs@3.8.0/dist/exceljs.min.js"
integrity="sha256-FnNb+CH5ZwjbWvJBzN+0phddfKPBgExLcXGBMRhuYc8=" crossorigin="anonymous"></script>
<script src="scripts/excelJS_helper.js"></script>
<script>
document.onreadystatechange = function () {
if (document.readyState == "complete") {
document.getElementById("btnExcel").onclick = function () {
var elt = document.getElementById("table-javascript");
var wb = exhelper.tableToBook(elt);
exhelper.addTitle(wb.worksheets[0], "title test");
//wb.worksheets[0].spliceRows(1, 7);
console.log(wb);
// save file
exhelper.saveXlsx("test.xlsx", wb);
/*
wb.xlsx.writeBuffer().then(
function (result) {
exhelper.saveBlob("test.xlsx", result);
},
function (err) {
console.log("error: ", err);
}
);
*/
}
}
}
<!-- CSS only -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<!-- JS, Popper.js, and jQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous">
</script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"
integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous">
</script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous">
</script>
<!-- ExcelJS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.26.0/polyfill.js"></script>
<!-- 因為 3.8.0 之後的版本有新加的功能,造成 IE 無法載入,所以如果要相容 IE 就先使用 3.8.0 版的,之後如果有需要新的功能,再想辦法透過 polyfill 處理 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/exceljs/3.8.0/exceljs.js"
integrity="sha512-vwSn7EltjzuN+K9iDCs+g39sPCoOxGjrJw7XoTELF8gg8r54+Pm+arEBxhJUkbd8jigd7g9hXJ0ja+mWJJbW6w=="
crossorigin="anonymous"></script>
</head>
<body>
<div class="page-content">
<table class="table table-javascript">
<thead>
<tr role="row">
<th data-title="支付工具" data-data="PaymentAgent" class="sorting_disabled" rowspan="1" colspan="1"
style="width: 256px;">支付工具</th>
<th data-title="通路名稱" data-data="StoreName" class="sorting_disabled" rowspan="1" colspan="1"
style="width: 336px;">通路名稱</th>
<th data-title="儲值筆數" data-data="DepositCount" class="sorting_disabled" rowspan="1"
style="width: 256px;">儲值筆數</th>
<th data-title="本次儲值金額" data-data="TransAmount" class="sorting_disabled" colspan="1"
style="width: 368px;">本次儲值金額</th>
</tr>
</thead>
<tbody>
<tr role="row" class="odd">
<th rowspan="2" tabindex="0">委外代收</th>
<td>貝克漢健康事業</td>
<td>1</td>
<td>20,000</td>
</tr>
<tr class="group">
<td>總計</td>
<td>1</td>
<td>20,000</td>
</tr>
<tr role="row" class="even">
<th rowspan="2" tabindex="0">其他</th>
<td>橘子支活動獎勵</td>
<td>2</td>
<td>200</td>
</tr>
<tr class="group">
<td>總計</td>
<td>2</td>
<td>200</td>
</tr>
<tr role="row" class="odd">
<th rowspan="2" tabindex="0">null</th>
<td></td>
<td>3</td>
<td>4,100</td>
</tr>
<tr class="group">
<td>總計</td>
<td>3</td>
<td>4,100</td>
</tr>
</tbody>
</table>
<div class="card-content">
<div id="search-result">
<div id="table-javascript_wrapper" class="dataTables_wrapper form-inline dt-bootstrap no-footer">
<div class="dt-buttons">
<button id="btnExcel" class="btn btn-info btn-sm" tabindex="0" aria-controls="table-javascript">
<span>excel</span>
</button>
</div>
<div id="table-javascript_processing" class="dataTables_processing panel panel-default"
style="display: none;">處理中...</div>
<table id="table-javascript"
class="table table-striped table-no-bordered table-hover table-responsive display no-wrap dataTable no-footer dtr-inline"
cellspacing="0" style="width: 100%;" role="grid" aria-describedby="table-javascript_info">
<thead>
<tr role="row">
<th data-title="支付工具" data-data="PaymentAgent" class="sorting_disabled" rowspan="1"
colspan="1" style="width: 225px;">支付工具</th>
<th data-title="通路名稱" data-data="StoreName" class="sorting_disabled" rowspan="1" colspan="1"
style="width: 304px;">通路名稱</th>
<th data-title="儲值筆數" data-data="DepositCount" class="sorting_disabled" rowspan="1"
colspan="1" style="width: 226px;">儲值筆數</th>
<th data-title="儲值金額" data-data="TransAmount" class="sorting_disabled" rowspan="1"
colspan="1" style="width: 227px;">儲值金額</th>
</tr>
</thead>
<tbody>
<tr role="row" class="odd">
<th rowspan="3" tabindex="0">其他</th>
<td colspan="2">3</td>
<td>4,100</td>
</tr>
<tr role="row" class="even">
<td tabindex="0" colspan="3">橘子支活動獎勵</td>
</tr>
<tr class="group">
<th>總計</th>
<th colspan="2">5</th>
</tr>
<tr role="row" class="odd">
<th rowspan="2" tabindex="0">委外代收</th>
<td>貝克漢健康事業</td>
<td>1</td>
<td>20,000</td>
</tr>
<tr class="group">
<th>總計</th>
<th>1</th>
<th>20,000</th>
</tr>
<tr class="totalSum">
<th>總計</th>
<th></th>
<th>6</th>
<th>24,300</th>
</tr>
</tbody>
</table>
<div class="dataTables_info" id="table-javascript_info" role="status" aria-live="polite">顯示第 1 至 3 項結果,共
3 項</div>
</div>
</div>
</div>
<div>
<button id="btnDownload" type="button" value="download">Download</button>
</div>
<script type="text/javascript">
$("#btnDownload").click(function () {
exportExcel($(".table-javascript"), "test.xlsx");
});
function exportExcel(tableElem, fileName) {
// 建立 ExcelJS 物件
const workbook = new ExcelJS.Workbook();
let now = new Date();
workbook.creator = "Gamapay";
workbook.lastModifiedBy = "Gamapay";
workbook.created = now;
workbook.modified = now;
workbook.lastPrinted = now;
// set workbook dates to 1904 date system
workbook.properties.date1904 = true;
// add worksheet
const sheet = workbook.addWorksheet("Sheet1");
// 建立 header
let headerTrs = tableElem.children("thead").children("tr");
for (var i = 0; i < headerTrs.length; i++) {
let headerThs = $(headerTrs[i]).children("th");
let totalColspan = 0;
for (var j = 0; j < headerThs.length; j++) {
// 現在的行數
let currRow = sheet.getRow(i);
// 現在的格子
let currCell = {
c: j + totalColspan,
r: i
};
// 目前的 th 物件
let elemTh = $(headerThs[j]);
// colspan
let colspan = !elemTh.attr("colspan") ? "2" : elemTh.attr("colspan");
// rowspan
let rowspan = !elemTh.attr("rowspan") ? "1" : elemTh.attr("rowspan");
// 合併欄位
if (colspan != 1) {
let mergeStart = currCell;
let mergeEnd = {
c: currCell.c + parseInt(colspan) - 1,
r: currCell.r
};
sheet.mergeCells(parseCellString(mergeStart) + ":" + parseCellString(mergeEnd));
totalColspan++;
}
let cell = sheet.getCell(parseCellString(currCell));
console.log(elemTh.text());
console.log(elemTh);
currRow.getCell(currCell.c + 1).value = elemTh.text();
// cell.value = elemTh.val();
// console.log(parseCellString(currCell));
// console.log(headerThs[j]);
// console.log(colspan);
// console.log(rowspan);
// console.log($(headerThs[j]).text());
}
}
console.log(sheet);
// sheet.addTable({
// name: "Test",
// ref: "A1",
// headerRow: true,
// totalsRow: false,
// columns: [{
// name: "支付工具"
// },
// {
// name: "通路名稱"
// },
// {
// name: "儲值筆數"
// },
// {
// name: "本次儲值金額"
// }
// ],
// rows: [
// ["委外代收", "貝克漢健康事業", 1, 20000],
// ["", "總計", 1, 20000],
// ["其它", "橘子支付活動獎勵", 2, 200],
// ["", "總計", 2, 200],
// ["null", "", 3, 4100],
// ["", "總計", 3, 4100]
// ]
// });
}
function parseCellString(cellElem) {
// 目前先定義A-Z之後有需要再加
var colArray = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
"S", "T", "U", "V", "W", "X", "Y", "Z"
];
var r = cellElem.r + 1;
return colArray[cellElem.c + 1] + r;
}
function saveByteArray(reportName, byte) {
var blob = new Blob([byte], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
var filename = reportName;
link.download = filename;
link.click();
};
function saveFile(fileName, byte) {
var blob = new Blob([byte], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
})
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
// for IE
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else {
// other browsers
var a = $("<a style='display: none;'/>");
var url = window.URL.createObjectURL(blob, {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
});
a.attr("href", url);
a.attr("download", fileName);
$("body").append(a);
a[0].click();
window.URL.revokeObjectURL(url);
a.remove();
}
}
</script>
</body>
</html>
</html>