2013-09-06 18 views
6

Quindi ho un controller Spring e vorrei creare un file Excel e restituirlo in modo che venga scaricato dal browser.File Excel scaricabile in uscita da Spring

Sto usando JEXcelApi.

Questo è il mio codice del controller

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

Come posso fare? Sospetto che ci sia un'intestazione di contenuto che posso impostare. So che un metodo è utilizzare la classe di visualizzazione di Excel Abstract di Spring, ma esiste un metodo più semplice?

risposta

8

È necessario impostare l'intestazione Content-Disposition.

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

e scrivere i byte direttamente alla risposta 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(); 

Quanto sopra è relativamente vecchia. È possibile costruire un ResponseEntity con FileSystemResource ora. A ResourceHttpMessageConverter copia quindi i byte, come ho suggerito sopra, per te. Spring MVC lo rende più semplice per te piuttosto che interagire con le interfacce dalle specifiche Servlet.

+0

come si scrivono i byte? – praks5432

+0

@ praks5432 Legge i byte dal file e li scrive nella risposta outputstream. –

+0

così è che sarà fatto sull'oggetto cartella di lavoro? – praks5432