1.下包
npm install xlsx
yarn add xlsx
2.结构
< template>
< input type = " file" @change = " onFileChange" />
</ template>
3.代码
< script>
import * as XLSX from 'xlsx'
export default {
methods : {
onFileChange ( event ) {
const file = event. target. files[ 0 ]
const reader = new FileReader ( )
reader. onload = ( e ) => {
const data = e. target. result
const fileType = file. name. split ( '.' ) . pop ( ) . toLowerCase ( ) ;
if ( fileType !== 'xls' && fileType !== 'xlsx' && fileType !== 'excel' ) {
alert ( '请选择有效的xls、xlsx或Excel文件' ) ;
return ;
}
const workbook = XLSX . read ( data, { type : 'binary' } )
workbook. SheetNames. forEach ( sheetName => {
const worksheet = workbook. Sheets[ sheetName]
const rows = XLSX . utils. sheet_to_json ( worksheet, { header : 1 } )
console. log ( ` Sheet Name: ${ sheetName} ` )
rows. forEach ( row => {
console. log ( row, '每一行' )
} )
} )
}
reader. readAsBinaryString ( file)
}
}
}
</ script>
4.结果