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

<p>package com.programtalk.beginner.tutorial;</p>
<p>import javax.servlet.ServletException;<br />
import javax.servlet.http.HttpServlet;<br />
import javax.servlet.http.HttpServletRequest;<br />
import javax.servlet.http.HttpServletResponse;</p>
<p>import org.apache.poi.hssf.usermodel.HSSFCell;<br />
import org.apache.poi.hssf.usermodel.HSSFCellStyle;<br />
import org.apache.poi.hssf.usermodel.HSSFRow;<br />
import org.apache.poi.hssf.usermodel.HSSFSheet;<br />
import org.apache.poi.hssf.usermodel.HSSFWorkbook;</p>
<p>// Extend HttpServlet class<br />
public class DownLoadExcelServlet extends HttpServlet {<br />
	private static final long serialVersionUID = 2067115822080269398L;</p>
<p>	public void init() throws ServletException {<br />
		// Do nothing<br />
<p>	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {</p>
<p>		try {<br />
			response.setContentType(&quot;application/;);<br />
			response.setHeader(&quot;Content-Disposition&quot;, &quot;attachment; filename=SampleExcel.xls&quot;);<br />
			HSSFWorkbook workbook = createExcel();<br />
			workbook.write(response.getOutputStream());<br />
		} catch (Exception e) {<br />
			throw new ServletException(&quot;Exception in DownLoad Excel Servlet&quot;, e);<br />
		}<br />
<p>	private HSSFWorkbook createExcel() {<br />
		HSSFWorkbook workbook = new HSSFWorkbook();<br />
		HSSFSheet worksheet = workbook.createSheet(&quot;My First POI Worksheet&quot;);</p>
<p>		HSSFRow row1 = worksheet.createRow(0);</p>
<p>		HSSFCell cellA1 = row1.createCell(0);<br />
		cellA1.setCellValue(&quot;Hurray! You did it.&quot;);<br />
		HSSFCellStyle cellStyle = workbook.createCellStyle();<br />
		cellA1.setCellStyle(cellStyle);<br />
		return workbook;<br />
<p>	public void destroy() {<br />
		// do nothing.<br />
	}<br />



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!

One Comment

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.