我目前正在创建一个允许用户将excel文件上传到数据库的Web应用程序,但在用户上传文件之前,我想让他们检查excel文件的标题,如果它与数据库。 下面的代码允许我显示excel文件中的所有内容:
//shortend the class because this is getting way to long already
userLogedin: boolean = false;
ngOnInit() {
this.checkAuthStatus();
}
presentAuthDialog(mode) {
this.dialogRef.close()
this.onClick.emit(mode)
this.checkAuthStatus()
}
logout() {
this.dialogRef.close()
this.authService.logOutUser().subscribe(() => this.router.navigate(['/']));
this.checkAuthStatus();
}
checkAuthStatus(){
this.authService.userSignedIn$.subscribe(data => {
this.userLogedin = data;
console.log(data)
})
}
我只想将excel文件的标题存储在一个数组中并显示它。 我是Javascript的新手,所以任何帮助都会非常感激。
答案 0 :(得分:0)
您可以执行以下操作:
const header = []
const columnCount = XLSX.utils.decode_range(ws['!ref']).e.c + 1
for (let i = 0; i < columnCount; ++i) {
header[i] = ws[`${XLSX.utils.encode_col(i)}1`].v
}
这是整个示例:
function extractHeader(ws) {
const header = []
const columnCount = XLSX.utils.decode_range(ws['!ref']).e.c + 1
for (let i = 0; i < columnCount; ++i) {
header[i] = ws[`${XLSX.utils.encode_col(i)}1`].v
}
return header
}
function handleFile() {
const input = document.getElementById("file")
const file = input.files[0]
if (file.type !== 'application/vnd.ms-excel') {
renderError()
}
const reader = new FileReader()
const rABS = !!reader.readAsBinaryString
reader.onload = e => {
/* Parse data */
const bstr = e.target.result
const wb = XLSX.read(bstr, { type: rABS ? 'binary' : 'array' })
/* Get first worksheet */
const wsname = wb.SheetNames[0]
const ws = wb.Sheets[wsname]
const header = extractHeader(ws)
renderTable(header)
}
if (rABS) reader.readAsBinaryString(file)
else reader.readAsArrayBuffer(file)
}
function renderTable(header) {
const table = document.createElement('table')
const tr = document.createElement('tr')
for (let i in header) {
const td = document.createElement('td')
const txt = document.createTextNode(header[i])
td.appendChild(txt)
tr.appendChild(td)
}
table.appendChild(tr)
document.getElementById('result').appendChild(table)
}
function renderError() {
const errorMsg = 'Unexpected file type'
const error = document.createElement('p')
error.setAttribute('class', 'error')
const txt = document.createTextNode(errorMsg)
error.appendChild(txt)
document.getElementById('result').appendChild(error)
throw new Error(errorMsg)
}
#result table tr td {
border: 2px solid grey;
}
#result .error {
color: red;
}
<script src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script>
<input type="file" onchange="handleFile()" id='file' accept=".csv"/>
<div id="result"><div>