1.HTML表格转换为Excel表格
CSDN:William_Tao(攻城狮)
依赖:npm install vue-json-excel -S
网站:点此进入
1.《main.js》
import JsonExcel from 'vue-json-excel'
Vue.component('downloadExcel', JsonExcel)
2.需求页面
<template>
<dis class="log">
<el-button type="primary" size="small">
<download-excel
class="export-excel-wrapper"
:data="tableDataDownload"
:fields="json_fields"
name="职位信息Excel"
>
</download-excel>
</el-button>
</dis>
</template>
<script>
export default {
data() {
return {
tableDataDownload: [
{
positionId: "1c1e2b88-1e5e-43a3-9b69-d7047373485e",
departmentName: "部门",
company: "湖南中医药大学第一附属医院",
positionName: "临床医学",
jobRequirements: "要求不高,你会Vue就行",
salaryCeiling: "男",
salaryLimit: "20",
location: "",
}
],
json_fields: {
编号: "positionId", //常规字段
部门名: "departmentName",
医院名: "company",
职位名: "positionName",
职位要求: "jobRequirements", //支持嵌套属性
薪资下线: "salaryCeiling",
薪资上限: "salaryLimit",
地理位置: "location",
},
};
},
methods: {},
};
</script>
博客园:菜鸟的编程VLOG
依赖:npm install -S file-saver xlsx、npm install -D script-loader
网站:点此进入
1.《 src/excel/Blob.js 》
/* eslint-disable */
/* Blob.js
* A Blob implementation.
* 2014-05-27
*
* By Eli Grey, http://eligrey.com
* By Devin Samarin, https://github.com/eboyjr
* License: X11/MIT
* See LICENSE.md
*/
/*global self, unescape */
/*jslint bitwise: true, regexp: true, confusion: true, es5: true, vars: true, white: true,
plusplus: true */
/*! @source http://purl.eligrey.com/github/Blob.js/blob/master/Blob.js */
(function (view) {
"use strict";
view.URL = view.URL || view.webkitURL;
if (view.Blob && view.URL) {
try {
new Blob;
return;
} catch (e) {}
}
// Internally we use a BlobBuilder implementation to base Blob off of
// in order to support older browsers that only have BlobBuilder
var BlobBuilder = view.BlobBuilder || view.WebKitBlobBuilder || view.MozBlobBuilder || (function(view) {
var
get_class = function(object) {
return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];
}
, FakeBlobBuilder = function BlobBuilder() {
this.data = [];
}
, FakeBlob = function Blob(data, type, encoding) {
this.data = data;
this.size = data.length;
this.type = type;
this.encoding = encoding;
}
, FBB_proto = FakeBlobBuilder.prototype
, FB_proto = FakeBlob.prototype
, FileReaderSync = view.FileReaderSync
, FileException = function(type) {
this.code = this[this.name = type];
}
, file_ex_codes = (
"NOT_FOUND_ERR SECURITY_ERR ABORT_ERR NOT_READABLE_ERR ENCODING_ERR "
+ "NO_MODIFICATION_ALLOWED_ERR INVALID_STATE_ERR SYNTAX_ERR"
).split(" ")
, file_ex_code = file_ex_codes.length
, real_URL = view.URL || view.webkitURL || view
, real_create_object_URL = real_URL.createObjectURL
, real_revoke_object_URL = real_URL.revokeObjectURL
, URL = real_URL
, btoa = view.btoa
, atob = view.atob
, ArrayBuffer = view.ArrayBuffer
, Uint8Array = view.Uint8Array
;
FakeBlob.fake = FB_proto.fake = true;
while (file_ex_code--) {
FileException.prototype[file_ex_codes[file_ex_code]] = file_ex_code + 1;
}
if (!real_URL.createObjectURL) {
URL = view.URL = {};
}
URL.createObjectURL = function(blob) {
var
type = blob.type
, data_URI_header
;
if (type === null) {
type = "application/octet-stream";
}
if (blob instanceof FakeBlob) {
data_URI_header = "data:" + type;
if (blob.encoding === "base64") {
return data_URI_header + ";base64," + blob.data;
} else if (blob.encoding === "URI") {
return data_URI_header + "," + decodeURIComponent(blob.data);
} if (btoa) {
return data_URI_header + ";base64," + btoa(blob.data);
} else {
return data_URI_header + "," + encodeURIComponent(blob.data);
}
} else if (real_create_object_URL) {
return real_create_object_URL.call(real_URL, blob);
}
};
URL.revokeObjectURL = function(object_URL) {
if (object_URL.substring(0, 5) !== "data:" && real_revoke_object_URL) {
real_revoke_object_URL.call(real_URL, object_URL);
}
};
FBB_proto.append = function(data/*, endings*/) {
var bb = this.data;
// decode data to a binary string
if (Uint8Array && (data instanceof ArrayBuffer || data instanceof Uint8Array)) {
var
str = ""
, buf = new Uint8Array(data)
, i = 0
, buf_len = buf.length
;
for (; i < buf_len; i++) {
str += String.fromCharCode(buf[i]);
}
bb.push(str);
} else if (get_class(data) === "Blob" || get_class(data) === "File") {
if (FileReaderSync) {
var fr = new FileReaderSync;
bb.push(fr.readAsBinaryString(data));
} else {
// async FileReader won't work as BlobBuilder is sync
throw new FileException("NOT_READABLE_ERR");
}
} else if (data instanceof FakeBlob) {
if (data.encoding === "base64" && atob) {
bb.push(atob(data.data));
} else if (data.encoding === "URI") {
bb.push(decodeURIComponent(data.data));
} else if (data.encoding === "raw") {
bb.push(data.data);
}
} else {
if (typeof data !== "string") {
data += ""; // convert unsupported types to strings
}
// decode UTF-16 to binary string
bb.push(unescape(encodeURIComponent(data)));
}
};
FBB_proto.getBlob = function(type) {
if (!arguments.length) {
type = null;
}
return new FakeBlob(this.data.join(""), type, "raw");
};
FBB_proto.toString = function() {
return "[object BlobBuilder]";
};
FB_proto.slice = function(start, end, type) {
var args = arguments.length;
if (args < 3) {
type = null;
}
return new FakeBlob(
this.data.slice(start, args > 1 ? end : this.data.length)
, type
, this.encoding
);
};
FB_proto.toString = function() {
return "[object Blob]";
};
FB_proto.close = function() {
this.size = this.data.length = 0;
};
return FakeBlobBuilder;
}(view));
view.Blob = function Blob(blobParts, options) {
var type = options ? (options.type || "") : "";
var builder = new BlobBuilder();
if (blobParts) {
for (var i = 0, len = blobParts.length; i < len; i++) {
builder.append(blobParts[i]);
}
}
return builder.getBlob(type);
};
}(typeof self !== "undefined" && self || typeof window !== "undefined" && window || this.content || this));
2.《 src/excel/Export2Excel.js 》
/* eslint-disable */
require('script-loader!file-saver');
require('./Blob');
require('script-loader!xlsx/dist/xlsx.core.min');
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]};
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 (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 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);
console.log('a')
var oo = generateArray(theTable);
var ranges = oo[1];
/* original data */
var data = oo[0];
var ws_name = "SheetJS";
console.log(data);
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(jsonData) {
console.log(jsonData)
}
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")
}
3.《common/js/util.js》
export function export2Excel(columns,list){
require.ensure([], () => {
const { export_json_to_excel } = require('../../excel/Export2Excel');
let tHeader = []
let filterVal = []
console.log(columns)
if(!columns){
return;
}
columns.forEach(item =>{
tHeader.push(item.title)
filterVal.push(item.key)
})
const data = list.map(v => filterVal.map(j => v[j]))
export_json_to_excel(tHeader, data, '数据列表');
})
}
4.在需求页面引入
<template>
<div class="hello">
<button @click="exportData">导出</button>
</div>
</template>
<script>
import { export2Excel } from "../../common/js/util";
export default {
name: "HelloWorld",
props: {
msg: String,
},
data() {
return {
columns: [
{ title: "日期", key: "date" },
{ title: "姓名", key: "name" },
{ title: "地址", key: "address" },
],
tableData: [
{
id: 1,
date: "2016-05-02",
name: "王小虎",
address: "上海市普陀区金沙江路 1518 弄",
},
{
id: 2,
date: "2016-05-04",
name: "王小虎",
address: "上海市普陀区金沙江路 1517 弄",
},
{
id: 3,
date: "2016-05-01",
name: "王小虎",
address: "上海市普陀区金沙江路 1519 弄",
children: [
{
id: 31,
date: "2016-05-01",
name: "王小虎",
address: "上海市普陀区金沙江路 1519 弄",
},
{
id: 32,
date: "2016-05-01",
name: "王小虎",
address: "上海市普陀区金沙江路 1519 弄",
},
],
},
{
id: 4,
date: "2016-05-03",
name: "王小虎",
address: "上海市普陀区金沙江路 1516 弄",
},
],
};
},
methods: {
exportData() {
export2Excel(this.columns, this.tableData);
},
},
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
JQuery之家插件
身份证验证函数
// Generated by CoffeeScript 1.12.7
/*
Validid is open source in:
https://github.com/Edditoria/validid
under MIT license:
https://github.com/Edditoria/validid/blob/master/LICENSE.md
*/
(function () {
var Validid, validid
Validid = (function () {
function Validid() {}
Validid.prototype.tools = {
normalize: function (id) {
var re
re = /\[-\/\s]/g
id = id.toUpperCase().replace(re, '')
re = /\([A-Z0-9]\)$/
if (re.test(id)) {
id = id.replace(/\[\(\)]/g, '')
}
return id
},
isDateValid: function (idDate, minDate, maxDate) {
var isFormatValid, parseDate
if (minDate == null) {
minDate = 'default'
}
if (maxDate == null) {
maxDate = 'today'
}
if (minDate === 'default' || minDate === '') {
minDate = '18991129'
}
isFormatValid = function (date) {
return typeof date === 'string' && /^[0-9]{8}$/.test(date)
}
if (!isFormatValid(idDate)) {
return false
}
if (!isFormatValid(minDate)) {
return false
}
parseDate = function (input) {
var date,
day,
isDayValid,
isFutureDate,
isLeapYear,
isMonthValid,
maxDay,
month,
startIndex,
year
startIndex = 0
year = +input.substring(startIndex, (startIndex += 4))
month = input.substring(startIndex, (startIndex += 2))
day = +input.substring(startIndex, (startIndex += 2))
date = new Date(year, +month - 1, day)
maxDay =
'01,03,05,07,08,10,12'.indexOf(month) >= 0
? 31
: '04,06,09,11'.indexOf(month) >= 0
? 30
: ((isLeapYear =
(year % 4 === 0 && year % 100 !== 0) || year % 400 === 0),
isLeapYear ? 29 : 28)
isDayValid = day > 0 && day <= maxDay
if (!isDayValid) {
return false
}
isMonthValid = +month > 0 && +month <= 12
if (!isMonthValid) {
return false
}
isFutureDate = new Date() < date
if (isFutureDate) {
return false
}
return date
}
idDate = parseDate(idDate)
if (idDate === false) {
return false
}
minDate = parseDate(minDate)
if (minDate === false) {
return false
}
maxDate =
maxDate === 'today'
? new Date()
: typeof maxDate === 'string'
? parseDate(maxDate)
: maxDate
if (maxDate === false) {
return false
}
return idDate >= minDate && idDate <= maxDate
},
getMaxDate: function (yearsOld) {
var now, year
now = new Date()
year = now.getFullYear() - yearsOld
return new Date(year, now.getMonth(), now.getDate())
},
}
Validid.prototype.cnid = function (id) {
var isChecksumValid, isDateValid, isFormatValid, isLengthValid
isLengthValid = function (id) {
return id.length === 18
}
isFormatValid = function (id) {
return /^[0-9]{17}[0-9X]$/.test(id)
}
isDateValid = (function (_this) {
return function () {
return _this.tools.isDateValid(id.substring(6, 14), '18860625')
}
})(this)
isChecksumValid = function (id) {
var char,
checkDigit,
getWeight,
i,
identifier,
index,
len,
remainder,
weightedSum
identifier = id.slice(0, -1)
checkDigit = id.slice(-1) === 'X' ? 10 : +id.slice(-1)
getWeight = function (n) {
return Math.pow(2, n - 1) % 11
}
weightedSum = 0
index = id.length
for (i = 0, len = identifier.length; i < len; i++) {
char = identifier[i]
weightedSum += +char * getWeight(index)
index--
}
remainder = ((12 - (weightedSum % 11)) % 11) - checkDigit
return remainder === 0
}
id = this.tools.normalize(id)
return (
isLengthValid(id) &&
isFormatValid(id) &&
isDateValid() &&
isChecksumValid(id)
)
}
Validid.prototype.twid = function (id) {
var isChecksumValid, isFormatValid, isLengthValid
isLengthValid = function (id) {
return id.length === 10
}
isFormatValid = function (id) {
return /^[A-Z][12][0-9]{8}$/.test(id)
}
isChecksumValid = function (id) {
var char,
i,
idLen,
idTail,
len,
letterIndex,
letterValue,
letters,
remainder,
weight,
weightedSum
idLen = id.length
letters = 'ABCDEFGHJKLMNPQRSTUVXYWZIO'
letterIndex = letters.indexOf(id[0]) + 10
letterValue =
Math.floor(letterIndex / 10) + (letterIndex % 10) * (idLen - 1)
idTail = id.slice(1)
weight = idLen - 2
weightedSum = 0
for (i = 0, len = idTail.length; i < len; i++) {
char = idTail[i]
weightedSum += +char * weight
weight--
}
remainder = (letterValue + weightedSum + +id.slice(-1)) % 10
return remainder === 0
}
id = this.tools.normalize(id)
return isLengthValid(id) && isFormatValid(id) && isChecksumValid(id)
}
Validid.prototype.hkid = function (id) {
var getLetterValue,
isChecksumValid,
isFormatValid,
isLengthValid,
isLetter
getLetterValue = function (letter) {
return letter.charCodeAt(0) - 64
}
isLetter = function (char) {
return /[a-zA-Z]/.test(char)
}
isLengthValid = function (id) {
return id.length === 8 || id.length === 9
}
isFormatValid = function (id) {
return /^[A-MP-Z]{1,2}[0-9]{6}[0-9A]$/.test(id)
}
isChecksumValid = function (id) {
var char,
charValue,
checkDigit,
i,
identifier,
len,
remainder,
weight,
weightedSum
weight = id.length
weightedSum = 0
identifier = id.slice(0, -1)
checkDigit = id.slice(-1) === 'A' ? 10 : +id.slice(-1)
for (i = 0, len = identifier.length; i < len; i++) {
char = identifier[i]
charValue = isLetter(char) ? getLetterValue(char) : +char
weightedSum += charValue * weight
weight--
}
remainder = (weightedSum + checkDigit) % 11
return remainder === 0
}
id = this.tools.normalize(id)
return isLengthValid(id) && isFormatValid(id) && isChecksumValid(id)
}
Validid.prototype.krid = function (id) {
var isChecksumValid, isDateValid, isFormatValid, isLengthValid
isLengthValid = function (id) {
return id.length === 13
}
isFormatValid = function (id) {
return /^[0-9]{13}$/.test(id)
}
isDateValid = (function (_this) {
return function (id) {
var date, maxDate, sDigit, yearPrefix
sDigit = id.substring(6, 7)
yearPrefix = (function () {
switch (sDigit) {
case '1':
case '2':
case '5':
case '6':
return '19'
case '3':
case '4':
case '7':
case '8':
return '20'
default:
return '18'
}
})()
date = yearPrefix + id.substring(0, 6)
maxDate = _this.tools.getMaxDate(17)
return _this.tools.isDateValid(date, 'default', maxDate)
}
})(this)
isChecksumValid = function (id) {
var char, i, index, len, remainder, weight, weightedSum
weight = [2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 4, 5, 0]
weightedSum = 0
index = 0
for (i = 0, len = id.length; i < len; i++) {
char = id[i]
weightedSum += +char * weight[index]
index++
}
remainder = ((11 - (weightedSum % 11)) % 10) - +id.slice(-1)
return remainder === 0
}
id = this.tools.normalize(id)
return (
isLengthValid(id) &&
isFormatValid(id) &&
isDateValid(id) &&
isChecksumValid(id)
)
}
return Validid
})()
validid = new Validid()
if (typeof module !== 'undefined' && module !== null && module.exports) {
module.exports = validid
}
if (typeof window !== 'undefined' && window !== null) {
window.validid = validid
}
}.call(this))
2.网页禁止复制、调试函数事件
CSDN:eara’s
网站:点此进入
《在<body>标签中添加以下代码》
οncοntextmenu='return false' 禁止右键
οndragstart='return false' 禁止拖动
onselectstart ='return false' 禁止选中
οnselect='document.selection.empty()' 禁止选中
οncοpy='document.selection.empty()' 禁止复制
onbeforecopy='return false' 禁止复制
οnmοuseup='document.selection.empty()'
// 禁用F12
function forbidF12() {
window.onkeydown = window.onkeyup = window.onkeypress = function (event) {
// 判断是否按下F12,F12键码为123
if (event.keyCode == 123) {
event.preventDefault() // 阻止默认事件行为
window.event.returnValue = false
}
}
}
// 禁用调试工具
function forbidConsole() {
var threshold = 160 // 打开控制台的宽或高阈值
// 每秒检查一次
var check = setInterval(function () {
if (
window.outerWidth - window.innerWidth > threshold ||
window.outerHeight - window.innerHeight > threshold
) {
// 如果打开控制台,则刷新页面
window.location.reload()
}
}, 1000)
}