preface

In my work, I wrote the function of importing and exporting Excel files, but I still encountered some small problems during the period, so please write it down simply, so as not to forget it again next time

export

When writing the export, I connected with the interface given by the back end, but the returned data was a pile of gibberish. For a moment, I was confused (because I had never done the export before and never encountered such a situation), as shown in the picture:

At first I thought it was the back end, but LUCKILY I was careful enough not to go to the back end, but to look up the problem online and find a solution

First, I’ll add responseType: ‘blob’ to my request method.

/ / export
export const exportFile = params= > {
  return request({
    url: '/xxxxx/xxxxxxxxxxx'.method: 'xxxx'.params: params,
    responseType: 'blob'})}Copy the code

Then, import the method in the page file and write the following code in the method:

exportFile(param)
    .then((res) = > {
    // Table name
        const fileName = "Budget Enquiry Form data.xls"; 
          
        // Non-IE download
        if ("download" in document.createElement("a")) { 
          
            // Parse the garble returned from the back end
            const blob = new Blob([res], { type: "application/ms-excel" });
            const a = document.createElement("a");
            
            // Define the download name
            a.download = fileName; 
            
            // Decide whether to hide
            a.style.display = "none"; 
            a.href = URL.createObjectURL(blob);
            document.body.appendChild(a);
            a.click();
            
            // Release the URL object
            URL.revokeObjectURL(a.href); 
            document.body.removeChild(a);
        }
    })
    .catch(() = > {});
Copy the code

In this way, the garbled code problem is solved

The import

Import is actually a file upload problem, this small requirement I have thought of using components, but I think there is a simple page to upload a single file requirements, there is no need to reference components, so I write the simplest version

Here I use the file attribute of the input tag directly to upload

Common attribute values for file

  • Multiple: Indicates whether multiple selection is required
  • Accept: Controls the format of uploaded files

Code sample

<input type="file" accept="video/x-msvideo" multiple="multiple" />
Copy the code

What file formats can accept control? This is just a sketch, not a complete one, but enough for simple cases. As follows:

*.3gpp audio/3gpp, video/3gpp 3GPP Audio/Video
*.ac3 audio/ac3 AC3 Audio
*.asf allpication/vnd.ms-asf Advanced Streaming Format
*.au audio/basic AU Audio
*.css text/css Cascading Style Sheets
*.csv text/csv Comma Separated Values
*.doc application/msword MS Word Document
*.dot application/msword MS Word Template
*.dtd application/xml-dtd Document Type Definition
*.dwg image/vnd.dwg AutoCAD Drawing Database
*.dxf image/vnd.dxf AutoCAD Drawing Interchange Format
*.gif image/gif Graphic Interchange Format
*.htm text/html HyperText Markup Language
*.html text/html HyperText Markup Language
*.jp2 image/jp2 JPEG-2000
*.jpe image/jpeg JPEG
*.jpeg image/jpeg JPEG
*.jpg image/jpeg JPEG
*.js text/javascript, application/javascript JavaScript
*.json application/json JavaScript Object Notation
*.mp2 audio/mpeg, video/mpeg MPEG Audio/Video Stream, Layer II
*.mp3 audio/mpeg MPEG Audio Stream, Layer III
*.mp4 audio/mp4, video/mp4 MPEG-4 Audio/Video
*.mpeg video/mpeg MPEG Video Stream, Layer II
*.mpg video/mpeg MPEG Video Stream, Layer II
*.mpp application/vnd.ms-project MS Project Project
*.ogg application/ogg, audio/ogg Ogg Vorbis
*.pdf application/pdf Portable Document Format
*.png image/png Portable Network Graphics
*.pot application/vnd.ms-powerpoint MS PowerPoint Template
*.pps application/vnd.ms-powerpoint MS PowerPoint Slideshow
*.ppt application/vnd.ms-powerpoint MS PowerPoint Presentation
*.rtf application/rtf, text/rtf Rich Text Format
*.svf image/vnd.svf Simple Vector Format
*.tif image/tiff Tagged Image Format File
*.tiff image/tiff Tagged Image Format File
*.txt text/plain Plain Text
*.wdb application/vnd.ms-works MS Works Database
*.wps application/vnd.ms-works Works Text Document
*.xhtml application/xhtml+xml Extensible HyperText Markup Language
*.xlc application/vnd.ms-excel MS Excel Chart
*.xlm application/vnd.ms-excel MS Excel Macro
*.xls application/vnd.ms-excel MS Excel Spreadsheet
*.xlt application/vnd.ms-excel MS Excel Template
*.xlw application/vnd.ms-excel MS Excel Workspace
*.xml text/xml, application/xml Extensible Markup Language
*.zip application/zip Compressed Archive

Example code for uploading files (simple implementation)

submitUpload() {
    var formData = new FormData();
    const file = this.$refs.file;
      
    formData.append('file', file.files[0]);
      
    // addExcel is one of the methods I use here to call the back-end interface
    addExcel(formData).then(res= > {
        if (res.code === 200) {
            this.$message({
                message: 'Import successful! '.type: 'success'
            });
        } else {
            this.$message({
                message: 'Import failed! '.type: 'waring'}); }})},Copy the code

This is a simple file upload function

Spruce up the upload button a bit

We can spruce up our input box a bit, because its native button style is pretty ugly, like this:

I’m using element-UI in my project, so I’ll just use el-button instead of the input display, and use an input property readonly to display the name of the selected file

   / / HTML:
   
   <el-button type="primary" @click="handleSelExcel"<input ref="file" class="add-file" type="file" Accept ="application/vnd.ms-excel"> <input Ref ="fileText" class="file-text" type="text" value=" readonly="readonly"> // CSS: .add-file {// hide the native input display: none; }.file-text {// Adjust the display style of the file name; width: 250px; color: dimgray; outline-style: none; border: 0; text-overflow:ellipsis; }Copy the code

You can write your own style according to this way, how beautiful how to write. I’m going to write a simple style here, and it will look something like this:

Since we want to use the el-Button box instead of the input click-select file event, we can use $refs to get the EL-Button element and bind it to the click event

    handleSelExcel() {
      const addFile = this.$refs.file;
      const fileText = this.$refs.fileText;
      
      addFile.onchange = type;
      
      function type() {
        fileText.value = addFile.value;
      }
      
      addFile.click();
    },
Copy the code

Added progress bar display

Here I have a simple progress bar with two divs

// html

 <div class="progress-bar">
      <span>Upload progress:</span>
      <div class="progress-div">
          <div class="progress" :style="{ 'width': progress + '%' }" /></div>
      </div>
 </div>
      
// CSS is just like that

 .progress-div {
    width: 250px;
    height: 10px;
    border: 1px solid #808080;
    border-radius: 5px;
    margin-top: 5px;
  }

  .progress {
    height: 10px;
    border-radius: 5px;
    background-color: deepskyblue;
  }
Copy the code

The next step is to calculate the percentage of the file upload progress. Here I declare a progress variable in data directly to save, together with :style, to make a dynamic width change to the inner div, to achieve a progress bar display

As follows: When you make a request with Axios, you can pass the request configuration. Part of the request configuration is the function that is called when the upload takes place.

const config = {
    onUploadProgress: (progressEvent) = > {
        // Assign the progress variable declared in data
        this.progress = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total ); }};Copy the code

Minor problem record: ProgressEvent (){} function progressEvent(){} function progressEvent(){} function progressEvent(){} function progressEvent(){} function progressEvent(){} So progressEvent is going to be an arrow function

When making a request using AXIos, we can pass in the config configuration object.

// addExcel is one of the methods I use here to call the back-end interface
addExcel(formData, config).then((res) = > {});

// Then receive the configuration object, such as:
export const addExcel = (params, config) = > {
  return request({
    url: 'xxxxxxxxxxxxxx'.method: 'xxxx'.data: params, ... config }) }Copy the code

When the upload progress changes, this function is called to get a percentage of the upload progress, which can be used directly in :style

The result is something like this:

Well, here it is, the weekend is coming, I wish you a happy weekend, hey hey hey 🤭