9

所以我有一个 Spring 控制器,我想创建一个 Excel 文件并将其返回,以便浏览器下载它。

我正在使用 JEXcelApi。

这是我的控制器代码

@RequestMapping(value="/excel/cols/{colString}/rows/{rowString}/", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<String> exportExcel(HttpServletResponse response,
    @PathVariable List<String> colString,
    @PathVariable List<String> rowString) throws JSONException, IOException, WriteException {
    WritableWorkbook workbook = Workbook.createWorkbook(new File("exported.xls"));
    WritableSheet sheet = workbook.createSheet("Exported",0);
    String[] cols = colString.get(0).split(",");
    String[] rows = rowString.get(0).split(","); 
    for(int i = 0; i < cols.length;i++){
        Label label = new Label(i,0, cols[i]);
        sheet.addCell(label);
    }
    int excelCol = 0;
    int excelRow = 1;
    for(int i = 0; i < rows.length;i++){
        Label label = new Label(excelCol,excelRow, rows[i]);
        sheet.addCell(label);
        excelCol++;
        if((i+1) % cols.length == 0){
            excelCol = 0;
            excelRow++;
        }
    }
    workbook.write();
    workbook.close();
    return null;
}

我怎么做?我怀疑我可以设置一些内容标题。我知道一种方法是使用 Spring 的 Abstract Excel 视图类,但有更简单的方法吗?

4

1 回答 1

11

您需要设置Content-Disposition标题。

response.setHeader("Content-disposition","attachment; filename=" + yourFileName);

并将您的字节直接写入响应OutputStream

File xls = new File("exported.xls"); // or whatever your file is
FileInputStream in = new FileInputStream(xls);
OutputStream out = response.getOutputStream();

byte[] buffer= new byte[8192]; // use bigger if you want
int length = 0;

while ((length = in.read(buffer)) > 0){
     out.write(buffer, 0, length);
}
in.close();
out.close();

以上是比较老的。你可以ResponseEntityFileSystemResource现在构造一个。然后, AResourceHttpMessageConverter将为您复制字节,正如我上面建议的那样。Spring MVC 使您更简单,而不是让您与 Servlet 规范中的接口进行交互。

于 2013-09-06T02:17:27.063 回答