Create an ExcelService
class with a method like this, which is universal. This method can be used either for writing to a file (which is useful for testing and if you need to store the files on the server side), or using this method you may later write to the output stream of your servlet.
Also notice that each method is responsible for closing the resource (and just that resource) which it has opened - writeToXlsx(OutputStream)
for the Workbook
, writeToXlsx(String)
for the OutputStream
.
/**
* Create an Excel file (as OutputStream) with your data
*
* @param output The OutputStream to which the method should write.
* It must be opened before!
* Notice that although it is an <em>output</em> of the method,
* it is provided as an <em>input</em> parameter.
* The idea is: "Give me the data, and here is the place
* you should put them to."
* @throws IOException
*/
public void writeToXlsx(OutputStream output) throws IOException {
try (final Workbook wb = new XSSFWorkbook();) {
final Sheet sheet = wb.createSheet(...);
// your code here to fill the sheet
wb.write(output);
}
}
For your convenience (and testing), you may create a specific method which writes to a file. However this is not the method to be used by your client application!
/**
* Create an Excel file (as file) with your data.
*
* @param outputFile The name of the output file.
* @throws IOException
*/
public void writeToXlsx(String outputFile) throws IOException {
try (OutputStream output = new FileOutputStream(new File(outputFile))) {
writeToXlsx(output);
}
}
Your servlet may look like this. It uses the service you have created.
@WebServlet("/content/data")
public class DataServlet extends HttpServlet {
private static final long serialVersionUID = ....;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
writeHeader(response);
writeBody(response);
}
private void writeBody(HttpServletResponse response) throws IOException {
// Each servlet has the output stream which is directly
// streamed to the client browser as the response:
final OutputStream output = response.getOutputStream();
// Now your service creates the data and writes them to the
// output stream:
final ExcelService service = new ExcelService();
service.writeToXlsx(output);
// To be sure that nothing is lost:
output.flush();
}
private void writeHeader(HttpServletResponse response) {
// Here you tell the browser that the result is not HTML, but Excel.
// The browser uses this information to open an application
// associated in the client operating system with this type
// of data.
response.setContentType("application/ms-excel");
// The browser will pass this information to Excel
// which will consider this as the file name
response.setHeader("Content-Disposition", "attachment; filename=MyData.xlsx");
}
}