Springboot+vue实现下载Excel

Download.vue
<script>
export default {
  data() {
    return {
      userId: '',
      form: {
        name: '',
        gender: '',
        email: '',
      },
      list: [
        {
          startTime: '',
          endTime: '',
          text: '',
        }
      ],
    };
  },
  activated: function () {
    this.userId = sessionStorage.getItem("userId");
  },
  methods: {
    async download() {
      let url = "/v1/test/downloadExcel";
      await this.$http.post(url, {
        info: this.form,
        list: this.list,
      }, { responseType: 'blob' })
        .then((response) => {
          const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' });
          const url = URL.createObjectURL(blob);

          // 创建一个下载链接并模拟点击
          const link = document.createElement('a');
          link.href = url;
          link.download = this.form.name + '.xlsx';
          link.click();

          // 释放创建的 URL 对象
          URL.revokeObjectURL(url);
        })
        .catch((err) => { });
    },
  },
};
</script>
PlanControllor.java
@RestController
@RequestMapping("/v1/test")
public class PlanController {

    @Autowired
    private DownloadService downloadService;

    @PostMapping("/downloadExcel")
    public void downloadExcel(@RequestBody InfoInputVO inputVO, HttpServletResponse response) {

        // excel下载
        downloadService.downloadExcel(inputVO, response);
    }
}
DownloadServiceImpl.java
@Service
public class DownloadServiceImpl implements DownloadService {
    @Transactional
    @Override
    public void downloadExcel(InfoInputVO inputVO, HttpServletResponse response) {

        // 取得下载内容
        Info info = inputVO.getInfo();
        List<Text> list = inputVO.getList();

        // 获取模板
        ClassPathResource classPathResource = new ClassPathResource("/templates/template.xlsx");
        // 输入流
        InputStream inputStream = null;
        // 输出流
        ServletOutputStream outputStream = null;
        // Excel对象
        ExcelWriter excelWriter = null;
        try {
            // 输入流
            inputStream = classPathResource.getInputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("excel", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            outputStream = response.getOutputStream();

            excelWriter = EasyExcel.write(outputStream).registerWriteHandler(writeHandler).withTemplate(inputStream).build();

            WriteSheet writeSheet = EasyExcel.writerSheet(0).build();

            excelWriter.fill(info, writeSheet);
            excelWriter.fill(list, writeSheet);

            excelWriter.finish();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
            //关闭流
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值