Detailed steps to implement the Excel import function in Vue

Detailed steps to implement the Excel import function in Vue

1. Front-end-led implementation steps

The first step is to click the import button on the page to read the Excel file

Completed using plugins.

The second step is to process the data format according to the requirements of the backend and convert it into the format they need

You need to write the logic yourself.

The third step is to send the data back via ajax through the backend interface

Adjust the interface and perform normal operations.

In short: the front end reads the Excel file, modifies the file format, and calls the interface

2. Read Excel files

Note: This step can realize the front-end import function. If you are interested in modifying the format, you can continue to step 3.

Summary: Copy the code to your own folder and download the necessary plugins.

2.1 The upload method in vue-admin-element provided by elementUI is used (Baidu warehouse cloning method, the official website also has it)

2.2 Download the package npm install xlsx -S (by default, step 2.1 has been completed)

2.3 Introduce the UploadExcel component and register it as global (find UploadExcel這個文件,復制一下,封裝組件不必多說)

If you don’t know how to register global components, refer to the following code: (You can do it in main.js if you like, but I will do it here for high maintainability)

import PageTools from './PageTools'
import UploadExcel from './UploadExcel'
 
export default {
  // Initialization of the plugin. The global functions provided by the plugin can be configured here install(Vue) {
    // Global registration of components Vue.component('PageTools', PageTools) // Register toolbar component Vue.component('UploadExcel', UploadExcel) // Register imported excel component }
} 

  2.4 Introduce components, use components, configure routes, and set click callback functions (no need to say more)

2.5 Test results

Manually enter the routing address you set in the browser and the page will jump to it


Summary: 1. The most important thing is to copy and then download the necessary plug-ins

2. It is necessary to introduce the UploadExcel component (to import Excel files), but it is not necessary to register it globally, depending on your mood

3. Import the component and register the callback function. The two parameters in it are required. You can refer to the source code for easier understanding.

4. The essence of the Excel import plug-in: convert Excel into regular data that can be recognized by JS after analysis, and we can perform any operation on the data

3. Process the data

Note: This step actually tests your ability to use JavaScript. Unfortunately, this is not difficult for me, and I believe it will not be difficult for me for a long time.

3.1 Format required by the backend:

3.2 What we are going to process:

  • Convert Chinese fields to English.姓名is read into Excel, but the backend needs username
  • Date processing. The time read from Excel is a number value, while the backend requires a standard date.

3.3 Encapsulate a processing function separately:

/**
     * results excel table content // [ {'name': 'Xiao Zhang', 'mobile phone number': '13712345678'}, {.....} ]
      // Target// [ {'username': 'Xiao Zhang', 'mobile': '13712345678'}, {.....} ]
     */
    transExcel(results) {
      const userRelations = {
        'Job Entry Date': 'timeOfEntry',
        'Mobile number': 'mobile',
        'Name': 'username',
        'Correction Date': 'correctionTime',
        'work number': 'workNumber',
        'Department': 'departmentName',
        'Form of employment': 'formOfEmployment'
      }
      return results.map(item => {
        const obj = {}
        // 1. Get all the attribute names of this object: ['name', 'phone number']
        // 2. Traverse this array, find the corresponding English name in userRelations through the Chinese name, and save the value const zhKeys = Object.keys(item)
        zhKeys.forEach(zhKey => {
          const enKey = userRelations[zhKey]
          // If it is in time format, convert it if (enKey === 'correctionTime' || enKey === 'timeOfEntry') {
            obj[enKey] = new Date(formatExcelDate(item[zhKey]))
          } else {
            obj[enKey] = item[zhKey]
          }
        })
 
        return obj
      })
    }
 
handleSuccess({ results, header }) {
    
  console.log('The content read from the current excel file is', results)
  // results: [{Joining date: 44502, Name: xxxx}]
  // Target:
  // results: [{timeOfEntry: 44502, username: xxxx}]
  // Process the format read from Excel const arr = this.transExcel(results)
  console.log('The format after conversion is', arr)
})

3.4 Date processing functions:

// Convert the date format in the Excel file back to standard time // https://blog.csdn.net/qq_15054679/article/details/107712966
export function formatExcelDate(numb, format = '/') {
  const time = new Date((numb - 25567) * 24 * 3600000 - 5 * 60 * 1000 - 43 * 1000 - 24 * 3600000 - 8 * 3600000)
  time.setYear(time.getFullYear())
  const year = time.getFullYear() + ''
  const month = time.getMonth() + 1 + ''
  const date = time.getDate() + ''
  if (format && format.length === 1) {
    return year + format + month + format + date
  }
  return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
}

4. Call the interface, send a request, and use it in the page

import { importEmployee } from '@/api/employees'
export default {
  name: 'Import',
  methods: {
    async handleSuccess({ results, header }) {
      try {
        console.log('The content read from the current excel file is', results)
        // results: [{Joining date: 44502, Name: xxxx}]
        // Target:
        // results: [{timeOfEntry: 44502, username: xxxx}]
        const arr = this.transExcel(results)
        console.log('The format after conversion is', arr)
        //Call the upload interface,
        const rs = await importEmployee(arr)
        console.log('Call the upload interface', rs)
        // After the upload is successful, return to the previous page this.$router.back()
        this.$message.success('Operation successful')
      } catch (err) {
        this.$message.error(err.message)
      }
    }
}

5 Summary:

The import function is similar to the export function. The difficulty lies in converting the data format. This article does not introduce it in detail, but it is explained in detail in another export article. If you are interested, you can go and have a look. Click here to jump to the export function implementation

This is the end of this article about Vue’s implementation of the Excel import function. For more relevant Vue import Excel content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • The whole process record of Vue export Excel function
  • How to introduce Excel table plug-in into Vue
  • How to export web page data to Excel in Vue
  • Vue imports excel table, and automatically downloads the data that failed to import

<<:  Practical method of deleting associated tables in MySQL

>>:  Summary of MYSQL full backup, master-slave replication, cascading replication, and semi-synchronization

Recommend

MySQL: Data Integrity

Data integrity is divided into: entity integrity,...

Seven Principles of a Skilled Designer (2): Color Usage

<br />Previous article: Seven Principles of ...

How to reset the root password in CentOS7

There are various environmental and configuration...

14 techniques for high-performance websites

Original : http://developer.yahoo.com/performance...

Implementing a table scrolling carousel effect through CSS animation

An application of CSS animation, with the same co...

MySQL 5.7.23 installation and configuration graphic tutorial

This article records the detailed installation pr...

A detailed introduction to Linux system configuration (service control)

Table of contents Preface 1. System Service Contr...

Create an SSL certificate that can be used in nginx and IIS

Table of contents Creating an SSL Certificate 1. ...

Common attacks on web front-ends and ways to prevent them

The security issues encountered in website front-...

MySQL 8.0.23 Major Updates (New Features)

Author: Guan Changlong is a DBA in the Delivery S...

Seven Principles of a Skilled Designer (1): Font Design

Well, you may be a design guru, or maybe that'...

JavaScript event delegation principle

Table of contents 1. What is event delegation? 2....

Detailed explanation of Bootstrap grid vertical and horizontal alignment

Table of contents 1. Bootstrap Grid Layout 2. Ver...

Detailed explanation of meta tags (the role of meta tags)

No matter how wonderful your personal website is,...