Vue front-end download excel file template

first step :

  //vue3.0版本的在项目public目录下新建static文件夹,放入“文件模板.xlsx”文件。
  //vue2.0版本的在项目根目录下的static文件夹,放入“文件模板.xlsx”文件。

   
   
    
    

Step 2:
Add events to the button

<el-button type="warning" @click="downloadTemplate">Excel模板下载</el-button>

   
   
    
    

Step 3:
Write the following method in methods:

 downloadTemplate() {
      
      
      let a = document.createElement("a");
      a.href = "./static/template.xlsx";
      a.download = "文件模板.xlsx";
      a.style.display = "none";
      document.body.appendChild(a);
      a.click();
      a.remove();
  },

   
   
    
    

Possible problems: downloading local files via a tag in vue reports an error - file not found

问题的解决:
原因之一:下载的模板文件的名字不可以为中文名,若为中文名会报错找不到文件;

The second reason: the downloaded template file must be placed in the static, and the vue2.0 version is placed in the static folder under the project root directory,
but since the vue3.0 version static is canceled, the file can be placed in the public, or in the public Create a new static folder and put it in it;

The third reason: and the most important first point, the path problem of the url, if you use ".../.../public/muban.xlsx" , an empty file will be downloaded
     because the path at this time should not be used relative to the current vue page When placing it under public, you should use the path relative to index.html,
     that is, "./" , and then you can access it;
of course, this is bound to the button. If you simply use the a tag to download The same goes for <
a href = " ./static/template.xlsx" download = " template.xlsx" > </a>

first step :

  //vue3.0版本的在项目public目录下新建static文件夹,放入“文件模板.xlsx”文件。
  //vue2.0版本的在项目根目录下的static文件夹,放入“文件模板.xlsx”文件。

   
   
  
  

Step 2:
Add events to the button

<el-button type="warning" @click="downloadTemplate">Excel模板下载</el-button>

   
   
  
  

Step 3:
Write the following method in methods:

 downloadTemplate() {
    
    
      let a = document.createElement("a");
      a.href = "./static/template.xlsx";
      a.download = "文件模板.xlsx";
      a.style.display = "none";
      document.body.appendChild(a);
      a.click();
      a.remove();
  },

   
   
  
  

Possible problems: downloading local files via a tag in vue reports an error - file not found

问题的解决:
原因之一:下载的模板文件的名字不可以为中文名,若为中文名会报错找不到文件;

Guess you like

Origin blog.csdn.net/m0_71349739/article/details/128861827