Generate a Excel file from Spring


We often need to generate a spreadsheet file from server and allow users to download the file. Here is how to do that with Spring using the Apache POI library.

Dependency:

We need to add the following dependencies in our spring application. Here is the Gradle dependencies.

compile group: 'org.apache.poi', name: 'poi', version: '3.15'
compile group: 'org.apache.poi', name: 'poi-ooxml', version: '3.15'
Once we add the dependencies we'll be able to access the POI library in our application.

Generate WorkBook

We need to generate a Workbook object in POI. Here is a sample method that returns a Workbook object

public Workbook downloadPersonList() throws IOException {

    // sample list. this can be the output of a DB query
    List<Person> personList = new ArrayList<>();
 
    personList.add(new Person("nayan", 29));

    personList.add(new Person("rafiq", 35));
    personList.add(new Person("sundor", 18));

    XSSFWorkbook wb = new XSSFWorkbook(); 
    XSSFSheet mySheet = wb.createSheet(); 

    // get the last row number to append new data 
    int rownum = mySheet.getLastRowNum(); 

    Row headerRow = mySheet.createRow(rownum++); 
    Cell headerRowCell1 = headerRow.createCell(0); 
    Cell headerRowCell2 = headerRow.createCell(1); 
    headerRowCell1.setCellValue("Name");  
    headerRowCell2.setCellValue("Age"); 

    for(Person person : personList){ 
        Row row = mySheet.createRow(rownum++); 
        row.createCell(0).setCellValue(person.getName());     
        row.createCell(1).setCellValue(person.getAge()); 
   
    return wb; 
}

Allow users to download the Workbook

Now we need to send the workbook as response from spring controller. We also need to send some additional headers so that user gets a save file prompt in their browser.

@RequestMapping(value="person/download",method=RequestMethod.GET) 
public void getPersonList(HttpServletResponse response) throws IOException {
    Workbook workbook = reportService.downloadPersonList(); // call to the above method 
    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); 
    response.setHeader("Content-Disposition", "inline; filename=person-list.xlsx"); 
    ServletOutputStream outputStream = response.getOutputStream(); 
    workbook.write(outputStream); 
    outputStream.close(); 
    workbook.close(); 
}
 
That's it!
 

Comments

Popular posts from this blog

Run tasks in background in Spring

Conditional field inclusion in Jackson and Spring Boot

How to configure Wildfly 10 to use MySQL