2013-09-06 87 views
6

Vì vậy, tôi có bộ điều khiển Spring và tôi muốn tạo tệp Excel và trả về tệp để trình duyệt tải xuống.Trả lại tệp có thể tải xuống Excel từ Spring

Tôi đang sử dụng JEXcelApi.

Đây là mã điều khiển của tôi

@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; 
} 

Làm thế nào để làm điều đó? Tôi nghi ngờ có một số tiêu đề nội dung tôi có thể thiết lập. Tôi biết một phương pháp là sử dụng lớp xem Tóm tắt Excel của Spring, nhưng có phương pháp đơn giản hơn không?

Trả lời

8

Bạn cần đặt tiêu đề Content-Disposition.

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

và ghi byte trực tiếp vào phản hồi 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(); 

Trên đây là tương đối cũ. Bạn có thể tạo một ResponseEntity với FileSystemResource ngay bây giờ. Sau đó, ResourceHttpMessageConverter sẽ sao chép các byte, như tôi đã đề xuất ở trên, cho bạn. Spring MVC làm cho nó đơn giản hơn cho bạn thay vì để bạn tương tác với các giao diện từ đặc tả Servlet.

+0

làm cách nào để viết các byte? – praks5432

+0

@ praks5432 Đọc byte từ tệp và ghi chúng vào đầu ra phản hồi. –

+0

như vậy là sẽ được thực hiện trên đối tượng bảng tính? – praks5432