spring4 mvc + poi 导出excel

只贴出controller部分,之前遇到问题是页面确实只请求了一次但是controller却执行了两次,后来自己摸索后原来问题出在没有指定ContentLength

@RequestMapping(value = "/exportExcel", method = RequestMethod.GET)
public void exportExcel(Integer companyCode, Integer channelCode, String from, String to, HttpServletResponse response) {
    DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd");
    Date fromDate = null;
    if (StringUtils.isNotBlank(from)) {
        fromDate = dtf.parseDateTime(from).toDate();
    }
    Date toDate = null;
    if (StringUtils.isNotBlank(to)) {
        toDate = dtf.parseDateTime(to).toDate();
    }
    try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();) {
        Workbook workbook = smsMoService.exportExcel(companyCode, channelCode, fromDate, toDate);
        workbook.write(byteArrayOutputStream);
        String fileName = URLEncoder.encode("上行短信.xlsx", "UTF-8");
        response.reset();
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.setContentType("application/vnd.ms-excel");
        response.setContentLength(byteArrayOutputStream.size());
        try (InputStream is = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
             OutputStream os = response.getOutputStream()
        ) {
            IOUtils.copy(is, os);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值