Vue+Element ui+ Springboot實現Excel模板下載實現------Vue+Element 常用功能彙總之系列之一

情景:Vue+Element ui+ Springboot項目中前端用到Excel模板下載功能,在網上找了不少案例,多數不盡人意,不是失敗就是下載後數據亂碼,解決後在此記錄一下。

前後端代碼如下:

前端代碼:

1.按鈕

 <el-button size="mini" type="success" icon="el-icon-download" @click="subPrint">設備導入模板下載</el-button>

2.方法

 methods: { //vue 的方法
 subPrint() {
        downloadDevices()//這個是下載調用後臺的接口
        .then(res => {
          this.delLoading = false;
          this.downloadFile(res.data);
        })
        .catch(err => {
          console.log(err.response.data.message);
        });
    },
    downloadFile(data) {
      // 文件導出
      if (!data) {
        return;
      }
      let url = window.URL.createObjectURL(new Blob([data]));
      let link = document.createElement("a");
      link.style.display = "none";
      link.href = url;
      link.setAttribute("download", "設備導入模板.xls");
      document.body.appendChild(link);
      link.click();
    }
}

 3.接口引入路徑

//請求後臺的接口,這邊是統一放在一個js中的,所以調用時引入maintenanceManager.js文件
 import { downloadDevices } from "@/api/http/maintenanceManager";
 

maintenanceManager.js代碼:

//下載導入的設備模板
export function downloadDevices(data) { return axios({ url: "/wb/deviceparameters/import/template", method: "post", responseType: "blob", data }); }

注意:這裏一定要加上數據返回格式爲:responseType: "blob"返回的字節流的形式返回,不然不能實現。

後端代碼:

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams; 
import org.apache.poi.ss.usermodel.Workbook;
@Api(description = "")
@RestController
@RequestMapping("/wb/deviceparameters")
public class WbDeviceParametersController extends BaseController {

   /**
     * 下載導入數據模板 上面import的5個包是下面方法必須要用到的 其它的省略沒寫
     */
    @RequestMapping(value = "import/template")
    public void importFileTemplate(RedirectAttributes redirectAttributes, HttpServletRequest request, HttpServletResponse response) throws IOException {
        ServletOutputStream sos = null;
        try {
            String title = "設備信息";//表格標題
            String fileName = "設備信息導入模板.xlsx";
            WbDeviceParameters deviceParameters = new WbDeviceParameters();
            deviceParameters.setSbzcdm("312022030020190000001");
            deviceParameters.setQueryType("importexport");
            List<WbDeviceParameters> list = wbDeviceParametersService.findList(deviceParameters);//查詢設備列表
            ExportParams exportParams = new ExportParams(title, title);
            exportParams.setDictHandler(new ExcelDictHandlerImpl());
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, WbDeviceParameters.class, list);
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");//設置返回數據編碼
            response.setHeader("Content-Disposition", "attachment; filename=" + Encodes.urlEncode(fileName));
            sos = response.getOutputStream();
            workbook.write(sos);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
}

後臺注意要在pom.xml導入下面幾個包:

     <!-- excel -->
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>4.0.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-web</artifactId>
            <version>4.0.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>4.0.0</version>
        </dependency>

       <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.0.0</version>
       </dependency>

下載成功圖:

打開:

 

注意:要調好前端的請求路徑和參數,不然容易出問題。

ok 就到這裏啦

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章