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

Problems with index and FROM_UNIXTIME in mysql

Zero, Background I received a lot of alerts this ...

Summary of common sql statements in Mysql

1. mysql export file: SELECT `pe2e_user_to_compan...

Several common CSS layouts (summary)

Summary This article will introduce the following...

A brief analysis of crontab task scheduling in Linux

1. Create a scheduling task instruction crontab -...

CSS to achieve floating customer service effect

<div class="sideBar"> <div>...

Summary of basic usage of js array

Preface Arrays are a special kind of object. Ther...

Can MySQL's repeatable read level solve phantom reads?

introduction When I was learning more about datab...

How to use JavaScript to implement sorting algorithms

Table of contents Bubble Sort Selection Sort Inse...

How to load Flash in HTML (2 implementation methods)

First method : CSS code: Copy code The code is as ...

Example of implementing QR code scanning effects with CSS3

Online Preview https://jsrun.pro/AafKp/ First loo...

Tutorial on how to install htop on CentOS 8

If you are looking to monitor your system interac...

Some notes on mysql self-join deduplication

Let me briefly explain the functional scenario: T...

Description of the hr tag in various browsers

Generally, we rarely meet HR, but once we do, it c...

Linux server SSH cracking prevention method (recommended)

1. The Linux server configures /etc/hosts.deny to...