Vue imports excel table, and automatically downloads the data that failed to import

Vue imports excel table, and automatically downloads the data that failed to import

There is such a requirement: an import button, click the button to import an Excel table. If some data in the Excel table fails to be imported, the Excel table of the failed data will be automatically downloaded. If all data is imported successfully, it will prompt "Import successful".

First, attach the upload file component of ElementUI

Element - The world's most popular Vue UI framework

Element, a desktop component library based on Vue 2.0 for developers, designers and product managers

https://element.eleme.cn/#/zh-CN/component/upload

The official website introduces the properties and usage of the upload component in detail, so I won’t go into details here. Here we mainly use it to achieve the requirement of importing Excel tables at the beginning. (The ElementUI library needs to be introduced in the Vue project. Please refer to the official website for detailed steps)

1. Introduce ElementUI upload component upload

<el-upload
  class="upload-demo"
  action="https://jsonplaceholder.typicode.com/posts/"
  multiple
  :auto-upload="false"
  :file-list="fileList"
  :on-change="fileChange">
  <el-button type="primary">Import</el-button>
</el-upload>

Page Effects

Attribute Introduction

property illustrate type
action Required parameter, upload address string
multiple Whether to support multiple selection of files boolean
auto-upload Whether to upload the file immediately after selecting it boolean
We set auto-upload to false to avoid automatic uploading so that we can use a custom upload method.
file-list Uploaded file list, for example: [{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}] array
on-change The hook for file status changes. It will be called when adding files, uploading successfully, and uploading failed. function(file, fileList)

2. Click the Import button and select the file (click "Open" to trigger on-change)

At this point, you can use the fileChange method to print and view the file structure in the console

fileChange(file,fileList){
  console.log(file,'file')
  console.log(fileList,'fileList')
} 

3. Now we have the selected file and can customize the upload method to send it to the backend server

fileChange(file,fileList){
  console.log(file,'file')
  console.log(fileList,'fileList')
  let url = 'xxx' //Backend server API
  let headers = {
    'Content-Type':'multipart/form-data' //When custom uploading, this request header parameter is required}
  let formData = ''
  for(let i = 0;i < fileList.length;i++){ //Traverse the file array, there may be multiple files in fileList formData = new FormData()
    formData.append('name',fileList[i].name)
    formData.append('type','.xlsx')
    formData.append('file',fileList[i].raw)
  }
  this.$axios({
    headers: headers,
    method: 'post',
    data: formData,
    url: url,
    responseType:'blob' //This parameter is required, otherwise the downloaded Excel table will prompt that the file is damaged and cannot be opened}).then(res=>{
    if(res && res.data.size == 0){
      //If the background does not return a stream, it means that all data has been imported successfully, and a prompt "Import successful" will be displayed. Return will not be automatically downloaded.
    }
    //If the background returns a stream, it means that some data import failed, then the Excel table of the failed data will be automatically downloaded let name = 'Import failed data.xlsx' //Customize the download Excel table name let blob = new Blob([res.data])
    let url = window.URL.createObjectURL(blob)
    let aLink = document.createElement('a')
    aLink.style.display = 'none'
    aLink.href = url
    //The download attribute defines the address of the download link. The href attribute must be specified in the <a> tag.
    aLink.setAttribute('download',name) 
    document.body.appendChild(aLink)
    aLink.click()
    document.body.removeChild(aLink)
    window.URL.revokeObjectURL(url)
    //Other operations can be performed after the download is completed, such as refreshing the list, friendly prompts, etc.})
}

Method Analysis

formData is a new interface proposed by ajax2.0 (XMLHttpRequest Level2). FormData object can be used to combine name and value of form elements to serialize form data, thereby splicing form elements and improving work efficiency. append adds a new attribute value to FormData . If the attribute value corresponding to FormData exists, the original value is overwritten, otherwise a new attribute value is added.

A Blob object represents an immutable, raw file-like object. Its data can be read in text or binary format, and can also be converted into ReadableStream for data manipulation.

URL.createObjectURL() static method creates a DOMString containing a URL representing the object given as a parameter. The lifecycle of this URL is tied to document in the window that created it. This new URL object represents the specified File object or Blob object.

URL.revokeObjectURL() static method is used to release a previously existing URL object created by calling URL.createObjectURL() . When you have finished using a URL object, you should call this method to let the browser know that it does not need to keep a reference to the file in memory.

Summary: The above implements custom import of Excel tables and automatically downloads the stream returned by the interface. The code can be used directly, but please note that the returned data response may not be the same as mine. Please refer to the return data of the joint debugging interface for details.

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • The whole process record of Vue export Excel function
  • Detailed steps to implement the Excel import function in Vue
  • How to introduce Excel table plug-in into Vue
  • How to export web page data to Excel in Vue

<<:  The 6 Most Effective Ways to Write HTML and CSS

>>:  Detailed explanation of the idea of ​​implementing dynamic effect of lyrics progress text color filling change using CSS3

Recommend

Vue realizes price calendar effect

This article example shares the specific code of ...

Vue large screen data display example

In order to efficiently meet requirements and avo...

Detailed explanation of several error handling when Nginx fails to start

When using Nginx as a Web server, I encountered t...

Sample code for implementing radar chart with vue+antv

1. Download Dependency npm install @antv/data-set...

How to query whether the mysql table is locked

Specific method: (Recommended tutorial: MySQL dat...

VMware Workstation 15 Pro Installation Guide (for Beginners)

01. VMware Workstation Pro 15 Download Download: ...

Implementation code for using CSS text-emphasis to emphasize text

1. Introduction In the past, if you wanted to emp...

JavaScript flow control (loop)

Table of contents 1. for loop 2. Double for loop ...

JavaScript generates random graphics by clicking

This article shares the specific code of javascri...

Vue method to verify whether the username is available

This article example shares the specific code of ...

Key issues and solutions for web page access speed

<br /> The website access speed can directly...

SQL implementation of LeetCode (182. Duplicate mailboxes)

[LeetCode] 182.Duplicate Emails Write a SQL query...

Source code reveals why Vue2 this can directly obtain data and methods

Table of contents 1. Example: this can directly g...

Solution to MySQL master-slave delay problem

Today we will look at why master-slave delay occu...