情景: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 就到这里啦

 

 

Logo

前往低代码交流专区

更多推荐