Download an Excel using Servlet

How to download an Excel using Servlet?

Create a workbook using any frameworks and write out the created workbook to response.getoutputstream(). For creating the excelsheet I am using apache poi. Set the content type of response to "application/" and set response header as   "Content-Disposition", "attachment; filename=YourExcelName.xls".

Download an Excel using Servlet Example

package com.programtalk.beginner.tutorial;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

// Extend HttpServlet class
public class DownLoadExcelServlet extends HttpServlet {
	private static final long serialVersionUID = 2067115822080269398L;

	public void init() throws ServletException {
		// Do nothing

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {
			response.setHeader("Content-Disposition", "attachment; filename=SampleExcel.xls");
			HSSFWorkbook workbook = createExcel();
		} catch (Exception e) {
			throw new ServletException("Exception in DownLoad Excel Servlet", e);

	private HSSFWorkbook createExcel() {
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet worksheet = workbook.createSheet("My First POI Worksheet");

		HSSFRow row1 = worksheet.createRow(0);

		HSSFCell cellA1 = row1.createCell(0);
		cellA1.setCellValue("Hurray! You did it.");
		HSSFCellStyle cellStyle = workbook.createCellStyle();
		return workbook;

	public void destroy() {
		// do nothing.



Should I close HttpServletResponse.getOutputStream()?

You should not close the stream. The servlet container will automatically close the stream after the servlet is finished running as part of the servlet request life-cycle.


So here we learned to download an excel using a servlet. In case of any comments or questions, please leave a note in the comments section below.

Like this post? Don’t forget to share it!

Leave a Reply

Your email address will not be published. Required fields are marked *