mn create-app example.micronaut.micronautguide --build=gradle --lang=groovy
Table of Contents
Download an Excel file in a Micronaut Application
Learn how to download an Excel file with the Micronaut framework and Spreadsheet Builder library.
Authors: Sergio del Amo
Micronaut Version: 3.9.2
1. Getting Started
In this guide, we will demonstrate Micronaut file transfer capabilities by creating an application which downloads an Excel file containing a list of books.
2. What you will need
To complete this guide, you will need the following:
-
Some time on your hands
-
A decent text editor or IDE
-
JDK 1.8 or greater installed with
JAVA_HOME
configured appropriately
3. Solution
We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.
-
Download and unzip the source
4. Writing the Application
Create an application using the Micronaut Command Line Interface or with Micronaut Launch.
If you don’t specify the --build argument, Gradle is used as the build tool. If you don’t specify the --lang argument, Java is used as the language.
|
The previous command creates a Micronaut application with the default package example.micronaut
in a directory named micronautguide
.
5. Writing the App
5.1. Books
Create Book
POJO:
package example.micronaut
import io.micronaut.core.annotation.NonNull
import groovy.transform.EqualsAndHashCode
import io.micronaut.core.annotation.Introspected
import javax.validation.constraints.NotBlank
@EqualsAndHashCode
@Introspected
class Book {
@NonNull
@NotBlank
private final String isbn
@NonNull
@NotBlank
private final String name
Book(@NonNull @NotBlank String isbn, @NonNull @NotBlank String name) {
this.isbn = isbn
this.name = name
}
@NonNull
String getIsbn() {
return isbn
}
@NonNull
String getName() {
return name
}
}
Create an interface to encapsulate Book retrieval.
package example.micronaut
import io.micronaut.core.annotation.NonNull
import io.micronaut.context.annotation.DefaultImplementation
@DefaultImplementation(BookRepositoryImpl)
interface BookRepository {
@NonNull
List<Book> findAll()
}
Create a bean which implements the previous interface:
package example.micronaut
import io.micronaut.core.annotation.NonNull
import jakarta.inject.Singleton
@Singleton (1)
class BookRepositoryImpl implements BookRepository {
@NonNull
@Override
List<Book> findAll() {
[
new Book("1491950358", "Building Microservices"),
new Book("1680502395", "Release It!"),
new Book("0321601912", "Continuous Delivery:")
]
}
}
1 | Use jakarta.inject.Singleton to designate a class as a singleton. |
5.2. Spreadsheet Builder
Add a dependency to Spreadsheet builder
Spreadsheet builder provides convenient way how to read and create MS Excel OfficeOpenXML Documents (XSLX) focus not only on content side but also on easy styling.
implementation("builders.dsl:spreadsheet-builder-poi:2.2.1")
5.3. Excel Creation
Create a interface to encapsulate Excel generation:
package example.micronaut
import io.micronaut.core.annotation.NonNull
import io.micronaut.context.annotation.DefaultImplementation
import io.micronaut.http.server.types.files.SystemFile
import javax.validation.Valid
import javax.validation.constraints.NotNull
@DefaultImplementation(BookExcelServiceImpl)
interface BookExcelService {
String SHEET_NAME = "Books"
String HEADER_ISBN = "Isbn"
String HEADER_NAME = "Name"
String HEADER_EXCEL_FILE_SUFIX = ".xlsx"
String HEADER_EXCEL_FILE_PREFIX = "books"
String HEADER_EXCEL_FILENAME = HEADER_EXCEL_FILE_PREFIX + HEADER_EXCEL_FILE_SUFIX;
@NonNull
SystemFile excelFileFromBooks(@NonNull @NotNull List<@Valid Book> bookList) (1)
}
1 | SystemFile is specified as the return type of a route execution to indicate the given file should be downloaded by the client instead of displayed. |
Externalize your styles configuration into a class implementing builders.dsl.spreadsheet.builder.api.Stylesheet
interface to maximize code reuse.
package example.micronaut
import builders.dsl.spreadsheet.api.FontStyle
import builders.dsl.spreadsheet.builder.api.CanDefineStyle
import builders.dsl.spreadsheet.builder.api.Stylesheet
class BookExcelStylesheet implements Stylesheet {
public static final String STYLE_HEADER = "header"
@Override
void declareStyles(CanDefineStyle stylable) {
stylable.style(STYLE_HEADER, st -> {
st.font(f -> f.style(FontStyle.BOLD))
})
}
}
Create a bean which generates the Excel file.
package example.micronaut
import builders.dsl.spreadsheet.builder.poi.PoiSpreadsheetBuilder
import io.micronaut.core.annotation.NonNull
import io.micronaut.http.HttpStatus
import io.micronaut.http.exceptions.HttpStatusException
import io.micronaut.http.server.types.files.SystemFile
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import jakarta.inject.Singleton
import javax.validation.Valid
import javax.validation.constraints.NotNull
import java.util.stream.Stream
@Singleton (1)
class BookExcelServiceImpl implements BookExcelService {
private static final Logger LOG = LoggerFactory.getLogger(BookExcelServiceImpl)
@NonNull
SystemFile excelFileFromBooks(@NonNull @NotNull List<@Valid Book> bookList) {
try {
File file = File.createTempFile(HEADER_EXCEL_FILE_PREFIX, HEADER_EXCEL_FILE_SUFIX);
PoiSpreadsheetBuilder.create(file).build(w -> {
w.apply(BookExcelStylesheet)
w.sheet(SHEET_NAME, s -> {
s.row(r -> Stream.of(HEADER_ISBN, HEADER_NAME)
.forEach(header -> r.cell(cd -> {
cd.value(header)
cd.style(BookExcelStylesheet.STYLE_HEADER)
})
))
bookList.stream()
.forEach( book -> s.row(r -> {
r.cell(book.isbn)
r.cell(book.name)
}));
})
})
return new SystemFile(file).attach(HEADER_EXCEL_FILENAME)
} catch (IOException e) {
LOG.error("File not found exception raised when generating excel file");
}
throw new HttpStatusException(HttpStatus.SERVICE_UNAVAILABLE, "error generating excel file")
}
}
1 | Use jakarta.inject.Singleton to designate a class as a singleton. |
5.4. Controller
5.5. Views
Although the Micronaut framework is primarily designed around message encoding / decoding, there are occasions where it is convenient to render a view on the server side.
To use the Thymeleaf Java template engine to render views in a Micronaut application, add the following dependency on your classpath.
implementation("io.micronaut.views:micronaut-views-thymeleaf")
Create a controller:
package example.micronaut
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
import io.micronaut.http.annotation.Produces
import io.micronaut.http.server.types.files.SystemFile
import io.micronaut.views.View
@Controller (1)
class HomeController {
private final BookRepository bookRepository
private final BookExcelService bookExcelService
HomeController(BookRepository bookRepository, (2)
BookExcelService bookExcelService) {
this.bookRepository = bookRepository
this.bookExcelService = bookExcelService
}
@View("index") (3)
@Get
Map<String, String> index() {
[:]
}
@Produces(value = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
@Get("/excel") (4)
SystemFile excel() { (5)
bookExcelService.excelFileFromBooks(bookRepository.findAll())
}
}
1 | The class is defined as a controller with the @Controller annotation mapped to the path / . |
2 | Constructor injection |
3 | Use @View annotation to specify which template to use to render the response. |
4 | You can specify the HTTP verb that a controller action responds to. To respond to a GET request, use io.micronaut.http.annotation.Get |
5 | SystemFile is specified as the return type of a route execution to indicate the given file should be downloaded by the client instead of displayed. |
The previous controller index method renders a simple view with a link to download the Excel file:
<!DOCTYPE html>
<html>
<head>
<title>Micronaut</title>
</head>
<body>
<p><a href="/excel">Excel</a></p>
</body>
</html>
5.6. Tests
Often, file transfers remain untested in many applications. In this section, you will see how easy is to test that the file downloads but also that the downloaded file contents match our expectations.
Create a test to verify the Excel file is downloaded and the content matches our expectations.
package example.micronaut
import builders.dsl.spreadsheet.query.api.SpreadsheetCriteria
import builders.dsl.spreadsheet.query.api.SpreadsheetCriteriaResult
import builders.dsl.spreadsheet.query.poi.PoiSpreadsheetCriteria
import io.micronaut.http.HttpRequest
import io.micronaut.http.HttpStatus
import spock.lang.Specification
import io.micronaut.test.extensions.spock.annotation.MicronautTest
import io.micronaut.http.client.HttpClient
import io.micronaut.http.client.annotation.Client
import jakarta.inject.Inject
import io.micronaut.http.HttpResponse
@MicronautTest (1)
class DownloadExcelSpec extends Specification {
@Inject
@Client("/")
HttpClient client (2)
def "books can be downloaded as an excel file"() {
when:
HttpResponse<byte[]> response = client.toBlocking().exchange(HttpRequest.GET('/excel') (3)
.accept("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"), byte[])
then:
noExceptionThrown()
response.status == HttpStatus.OK
when:
InputStream inputStream = new ByteArrayInputStream(response.body()) (4)
SpreadsheetCriteria query = PoiSpreadsheetCriteria.FACTORY.forStream(inputStream)
SpreadsheetCriteriaResult result = query.query( { workbookCriterion ->
workbookCriterion.sheet(BookExcelService.SHEET_NAME, { sheetCriterion ->
sheetCriterion.row({ rowCriterion ->
rowCriterion.cell({ cellCriterion ->
cellCriterion.value('Building Microservices')
})
})
})
})
then: 'a row is found'
result.cells.size() == 1
}
}
1 | Annotate the class with @MicronautTest so the Micronaut framework will initialize the application context and the embedded server. More info. |
2 | Inject the HttpClient bean and point it to the embedded server. |
3 | Creating HTTP Requests is easy thanks to the Micronaut framework fluid API. |
4 | Use .body() to retrieve the excel bytes. |
6. Testing the Application
To run the tests:
./gradlew test
Then open build/reports/tests/test/index.html
in a browser to see the results.
7. Running the Application
To run the application, use the ./gradlew run
command, which starts the application on port 8080.
8. Next Steps
Read more about Micronaut File Transfers support.
9. Help with the Micronaut Framework
The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.