如何使用Spring Rest Service生成和下载带有Angular Post的xls?

时间:2015-11-12 20:32:26

标签: angularjs spring-mvc download

使用angular-file-saver依赖项解决了问题。

当我点击导出按钮时,我会像这样做一个角度,我想下载一个xls文件:

$http.post('api/sportsbooks/downloadXLS').then(function (response) {
                return response.data;
            });

在我的Spring Rest服务中,我有:

@RequestMapping(value = "/sportsbooks/downloadXLS",method = RequestMethod.POST, produces = { "application/json;charset=UTF-8" })
public void downloadXLS(HttpServletResponse response) {
    Pageable pageable = new PageRequest(0, 20, Direction.ASC, "id");
    Page<Sportsbook> page = sportsbookRepositoryCustom.findAll(pageable, null, null, null);
    List<Sportsbook> sportsbookList = page.getContent();

    HSSFWorkbook workbook = new HSSFWorkbook();
    HSSFSheet sheet = workbook.createSheet("Sample sheet");

    Map<String, Object[]> data = new HashMap<String, Object[]>();
    data.put("1", new Object[] { "Emp No.", "Name", "Salary" });
    data.put("2", new Object[] { 1d, "John", 1500000d });
    data.put("3", new Object[] { 2d, "Sam", 800000d });
    data.put("4", new Object[] { 3d, "Dean", 700000d });

    Set<String> keyset = data.keySet();
    int rownum = 0;
    for (String key : keyset) {
        Row row = sheet.createRow(rownum++);
        Object[] objArr = data.get(key);
        int cellnum = 0;
        for (Object obj : objArr) {
            Cell cell = row.createCell(cellnum++);
            if (obj instanceof Date)
                cell.setCellValue((Date) obj);
            else if (obj instanceof Boolean)
                cell.setCellValue((Boolean) obj);
            else if (obj instanceof String)
                cell.setCellValue((String) obj);
            else if (obj instanceof Double)
                cell.setCellValue((Double) obj);
        }
    }

    if (workbook != null) {
        // Writing file to outputstream
        try {

            byte[] bytes  = workbook.getBytes();
            String fileName = "report.xls";
               response.setContentType("application/xls");
                response.setHeader("Content-Length", String.valueOf(bytes.length));
                response.setHeader("Content-Disposition", "attachment; filename="+fileName);

                response.getOutputStream().write(bytes);
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
    }

也许我必须在角度回调中做点什么,但我不知道是什么。有人能帮助我吗?

0 个答案:

没有答案