The front end uses the xlsx plug-in to read excel file data (nanny level tutorial)

I am an intern rookie, please read carefully......

      In the development process, it is inevitable that we will encounter the need to use the front end to process the excel file. We need to parse the content of the excel file and then display it in the form of an object or connect it with the back end.

Function realization idea:

     File selection => FileReader object gets binary data => XLSX processes binary data => gets data

1. Import button styles and events (element ui)

        First of all, what we need is an import button, but our import button is not easy to handle the change event that triggers the selection file (file), so we can use positioning to solve this problem. The principle is: the selection file button (file) is overlaid on the normal button Then change the transparency of the select file button (file) to 0

<el-button size="mini" type="success" style="margin-top: 10px" :disabled="disabled" 
class="el-dialog-position">
    <span v-if="importStatus === false">
        导入<i class="el-icon-upload el-icon--right" />
        <input ref="files" type="file" v-if="!disabled" class="excelFile" @change="excelFileMethod" />
    </span>
    <span v-if="importStatus === true">
        导入中<i class="el-icon-loading el-icon--right" />
    </span>
</el-button>

        Next is the chnage event, which fires on input, select, and textarea elements when the user changes the value of change these elements. Unlike  inputvalue events, events are not  triggered   every time an element  changes change . After we selected the file and confirmed, we got some big piles of data below

We don't care about this large amount of data, we just focus on the files object in the target object because we need to use it later, but note that the information here is only the information of the file, not the data, let alone the binary file! ! ! ! ! !

2. Process the obtained file information (use of fileReader)

        Let's introduce fileReaderFileReader first.  The object allows Web applications to asynchronously read the contents of files (or raw data buffers) stored on the user's computer, and use  File  or  Blob  objects to specify the files or data to be read. (Original text on the official website) Here I will give you an address to see the use of attributes and methods for yourself. I won’t introduce too much... Let’s look at the code first:

// change事件
excelFileMethod(e) {
    var _this = this
	//  excel文件信息
	const files = e.target.files
	console.log(files);
	// 构建fileReader对象
	const fileReader = new FileReader()
	// 读取操作完成时
	fileReader.onload = function(e) {
		try {
			// 二进制数据
			console.log(e.target.result)
			
		} catch (e) {
			console.log('文件类型不正确')
			return
		}
	}
	// 读取指定文件内容
	fileReader.readAsBinaryString(files[0])
}
  • The first step we need to build a new FileReader object
  • The second step uses FileReader.readAsBinaryString() to read the content in the specified Blob . Once complete, resultthe properties will contain the raw binary data of the read file.
  • The third step is FileReader.onLoad, which is triggered when the read operation is completed.

3. Process the obtained binary data (use of XLSX plug-in)

        To use the XLSX plug-in , we need to download it before using it and use it with CND. It can also be installed by npm to see personal needs. I am here for the vue project, so it is installed by npm and then we need to introduce XLSX. The method is as follows:

import XLSX from 'xlsx'

We have obtained the binary data through the above code, let's start parsing the binary data! Use the XLSX.read(data, { type: type}) method to implement, and the main values ​​of type are as follows:

  • base64: read in base64
  • binary:BinaryString格式( byte n is data.charCodeAt(n) )
  • string: UTF8 encoded string
  • buffer:nodejs Buffer
  • array: Uint8Array, 8-bit unsigned array
  • file: the path of the file (only supported under nodejs)

This method returns a workBook object whose contents are as follows:

You can see the workBook object, sheetNames saves all the sheet names, and Sheets saves the specific content of each sheet (we call it Sheet Object). Each sheet A1saves the content of each cell through a key value like this, which we call a cell object (Cell Object)

Method for parsing the workBook object

  • XLSX.utils.sheet_to_csv : generate CSV format
  • XLSX.utils.sheet_to_txt : generate plain text format
  • XLSX.utils.sheet_to_html : generate HTML format
  • XLSX.utils.sheet_to_json : output in JSON format

XLSX.utils.sheet_to_json is used here, so I will focus on introducing it. XLSX.utils.sheet_to_json(data, type) has two parameters. The first is the data corresponding to the Sheets object in our wordBook object. The second parameter is configured as follows :

  • raw:  use raw values ​​(true) or formatted strings (false) (default: true )
  • dateNF: use the specified date format in string output (default: FMT 14 )
  • defval:  use the specified value instead of null or undefined ()
  • blankrows:  Include blank rows** in the output (default: **  )
  • range: 

            (number) Use worksheet range, but set start row to value

            (String) Use the specified range (A1-style bounded range string

            (default) use worksheet range ( worksheet['!ref'])

  • header:

            1: Generate an array of arrays ("two-dimensional array")

            "A".Row object keys are literal column labels

            array of strings: Use the specified strings as keys in the row object

            (default): read the first row as the key and disambiguate it

The following is the entire code process for importing excel files and reading data. We can use the obtained data as parameters to connect with the back-end interface!

// 处理excel文件
excelFileMethod(e) {
    // 导入状态和文件信息
    var _this = this
    _this.importStatus = true
    const excelFile = e.target.files
    // 构建fileReader对象
    const fileReader = new FileReader()
    // 该事件为读取完成时触发
    fileReader.onload = function (ev) {
      try {
        const data = ev.target.result
        const workbook = XLSX.read(data, {type: 'binary'})
        const list = ''
        const listNew = list.concat(XLSX.utils.sheet_to_json(workbook.Sheets['sheets1'], {header: 1}))
        _this.excelData.list = listNew.slice(6).split(',')
        // 得到的数据发送axios请求
        importExcel(_this.excelData).then(res => {
          console.log(res)
          _this.importStatus = false
          if (res.code === 200) {
            _this.$alert(res.data.msg, '导入成功', {
              confirmButtonText: '确定',
              callback: () => {
                // 确认后做什么
              }
            })
          } else {
            _this.$alert(res.data.msg, '导入失败', {
              confirmButtonText: '确定',
              callback: () => {
                // 确认后做什么
              }
            })
          }
        })
      } catch (e) {
        _this.$message({message: '文件类型不正确', type: 'warning'})
      }
    }
    // 读取数据
    fileReader.readAsBinaryString(excelFile[0])
}

We will continue to update technical issues in the future. Friends who are interested can pay attention or private message me! ! !

Guess you like

Origin blog.csdn.net/admin_W_KP/article/details/129166603