console
const input = document.getElementById('input')
const run = document.getElementById('run')
const download = document.getElementById('download')
const result = document.getElementById('result')
const renderData = function () {
const words = input.value.trim().split(/[\r\n\t\s,;,;。、.'"“”()]+/)
const info = []
const map = {}
words.map(w => {
if (!map[w]) {
map[w] = 1
info.push(w)
}
else {
map[w]++
}
})
return info.map(w => ({ word: w, times: map[w] })).filter(t => !!t.word)
}
const renderTable = function () {
const data = renderData()
const table = document.createElement('table')
const theadrow = table.insertRow()
const th1 = theadrow.insertCell(); th1.innerText = 'word';
const th2 = theadrow.insertCell(); th2.innerText = 'times';
data.map((item) => {
const line = table.insertRow()
const td1 = line.insertCell(); td1.innerText = item.word;
const td2 = line.insertCell(); td2.innerText = item.times;
})
result.innerHTML = ''
result.appendChild(table)
return table
}
const tableToExcel = function (t, filename) {
const uri = 'data:application/vnd.ms-excel;base64,'
const template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><?xml version="1.0" encoding="UTF-8" standalone="yes"?><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table border=1>{table}</table></body></html>'
const ctx = {
table: t.innerHTML,
worksheet: filename,
}
const a = document.createElement("a")
a.download = filename + '.xls'
a.href = uri + btoa( unescape(encodeURIComponent(template.replace(/{(\w+)}/g, (_, k) => ctx[k]))) )
a.click()
}
const downloadTable = function () {
tableToExcel(renderTable(), 'words')
}
run.addEventListener('click', renderTable)
download.addEventListener('click', downloadTable)
<textarea class="input" name="words" id="input" rows="8">
const input = document.getElementById('input')
const run = document.getElementById('run')
const download = document.getElementById('download')
const result = document.getElementById('result')
</textarea>
<button id="run">统计</button> | <button id="download">导出</button>
<div id="result" class="result">
</div>
.input {
display: block;
width: 98%;
margin: 20px auto;
}
.result {
margin: 20px;
text-align: center;
color: #333;
--border-color: #333;
}
.result table {
border-spacing: 0;
border-left: 1px solid var(--border-color);
border-top: 1px solid var(--border-color);
}
.result table th,
.result table td {
border-right: 1px solid var(--border-color);
border-bottom: 1px solid var(--border-color);
padding: 6px 12px;
}