vue + element implements front-end excel upload parsing

Preface

Recently, there is a new requirement. The front-end needs to parse the excel file and display it on the page for the user to confirm that it is correct before uploading.

1. Install the plug-in

First install xlsxthe plug-in. What I installed here is0.14.1

npm install xlsx --save

2. html part of the code

Here el-uplaodthe upload component that comes with element is used, and the event function is used http-request.

<el-upload
 :http-request="handleUpload" 
 :limit="1"
  action
  class="upload-demo"
  multiple
  v-model:file-list="fileList"
 >
   <el-button type="primary">Click to upload</el-button>
 </el-upload>

3.js part code

import xlsx from 'xlsx'

const handleUpload = async ({
     
      file }) => {
    
    
  // 使用原生api去读取好的文件
  // 读取文件不是立马能够读取到的,所以是异步的,使用Promise
  let dataBinary = await new Promise(resolve => {
    
    
    // Web API构造函数FileReader,可实例化对象,去调用其身上方法,去读取解析文件信息
    let reader = new FileReader()
    reader.readAsBinaryString(file)
    reader.onload = ev => {
    
    
      resolve(ev.target.result) // 将解析好的结果扔出去,以供使用
    }
  })

  let workBook = xlsx.read(dataBinary, {
    
     type: 'binary', cellDates: true })
  // excel中有很多的sheet,这里取了第一个sheet:workBook.SheetNames[0]
  let firstWorkSheet = workBook.Sheets[workBook.SheetNames[0]]
  // 分为第一行的数据,和第一行下方的数据
  const header = getHeaderRow(firstWorkSheet)
  console.log("读取的excel表头数据(第一行)", header);
  const data = xlsx.utils.sheet_to_json(firstWorkSheet);
  console.log("读取所有excel数据", data);
}

const getHeaderRow = sheet => {
    
    
  // 定义数组,用于存放解析好的数据
  const headers = []
  // 读取sheet的单元格数据
  const range = xlsx.utils.decode_range(sheet['!ref'])
  let C
  const R = range.s.r
  for (C = range.s.c; C <= range.e.c; ++C) {
    
    
    /* walk every column in the range */
    const cell = sheet[xlsx.utils.encode_cell({
    
     c: C, r: R })]
    /* find the cell in the first row */
    let hdr = 'UNKNOWN ' + C // <-- replace with your desired default
    if (cell && cell.t) hdr = xlsx.utils.format_cell(cell)
    headers.push(hdr)
  }
  return headers
}

Guess you like

Origin blog.csdn.net/weixin_44013288/article/details/132894353