栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【SpringBoot+Vue】简单实现导入到Excel

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【SpringBoot+Vue】简单实现导入到Excel

后端

一般在项目中使用需要拦截配置器放行该导出方法,然后在控制层调用【@CrossOrigin】注解

拦截配置器
package com.bw.note.config.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


@Configuration
public class WebConfigurer implements WebMvcConfigurer {

    @Autowired
    private LoginInterceptor loginInterceptor;

    // 这个方法是用来配置静态资源的,比如html,js,css,等等
    

    // 这个方法用来注册拦截器,我们自己写好的拦截器需要通过这里添加注册才能生效
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor).excludePathPatterns(
                "/api/v1/note/merchant/exportExcel").addPathPatterns("
public static void exportExcel(HttpServletResponse response,
                               List>> excelDatas,
                               List sheetNames,
                               String fileName,
                               int columnWidth) throws IOException {

    //声明一个工作簿
    XSSFWorkbook workbook = new XSSFWorkbook();

    XSSFCellStyle cellStyle = workbook.createCellStyle();

    //生成一个表格,设置表格名称
    for (int i = 0; i < sheetNames.size(); i++) {
        String sheetName = sheetNames.get(i);
        XSSFSheet sheet = workbook.createSheet(sheetName);
        //设置表格列宽度
        sheet.setDefaultColumnWidth(columnWidth);
        //写入List>中的数据
        int rowIndex = 0;
        List> excelData = excelDatas.get(i);

        for (List data: excelData) {

            //创建一个row行,然后自增1
            XSSFRow row = sheet.createRow(rowIndex++);

            //遍历添加本行数据
            for (int j = 0; j < data.size(); j++) {
                //创建一个单元格
                XSSFCell cell = row.createCell(j);

                    try {
                        Double value = Double.valueOf(data.get(j));
                        cellStyle.setDataFormat(workbook.createDataFormat().getFormat("0"));
                        cell.setCellValue(value);
                    } catch (Exception e) {
                        //创建一个内容对象
                        XSSFRichTextString text = new XSSFRichTextString(data.get(j));
                        //将内容对象的文字内容写入到单元格中
                        cell.setCellValue(text);
                    }
            }
        }
    }


    //准备将Excel的输出流通过response输出到页面下载
    //八进制输出流
    response.setContentType("application/octet-stream");

    //设置导出Excel的名称
    response.setHeader("Content-disposition", "attachment;filename=" + fileName);

    //刷新缓冲
    response.flushBuffer();

    //workbook将Excel写入到response的输出流中,供页面下载该Excel文件
    workbook.write(response.getOutputStream());

    //关闭workbook
    workbook.close();
}
前端
// 导出
exportBtn () {
  axios({
    method: 'GET',
    url: '/api/v1/note/merchant/exportExcel',
    params: {
      classifyName: this.search.name.trim(),
      pageSize: this.pageSize,
      pageNo: this.pageNo
    },
    responseType: 'blob'
  }).then(res => {
    let obj = res.headers
    let fileName
    for (const key in obj) {
      if (Object.hasOwnProperty.call(obj, key)) {
        if (key == 'content-disposition') {
          // fileName = obj[key].split("=")
          fileName = obj[key].slice(20)
        }
      }
    }
    let date = new Date().getTime()
    let url = window.URL.createObjectURL(new Blob([res.data]))
    let link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', fileName)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    this.$message({
      message: '导出提现记录成功',
      type: 'success'
    })
  }).catch(err => {
    console.log(err)
  })
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/721753.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号