Spring MVC XLS Download

Spring MVC XLS Download

To generate report generation in various format today you will see how to generate report in XLS format in spring MVC application. Inside controller we will create XML object and write to the response object which will be return back to the user so that he could open/save generated report.

If you want to generate report in other format please visit previous tutorial using below link:

Steps for XLS report:

  • Create maven web project name: SpringMVCDownloadXLS below is complete structure:

Spring MVC XLS Download

  • SpringMVCController.java:
package com.javahonk.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class SpringMVCController {

	@RequestMapping(value = "/downloadXLS")
	public void downloadXLS(HttpServletResponse response) {

		try {
			response.setContentType("application/vnd.ms-excel");
			String reportName = "JavaHonk_XLS_Report_.xls";
			response.setHeader("Content-disposition", "attachment; filename=" + reportName);
			ArrayList<String> rows = new ArrayList<String>();
			rows.add("First Name");
			rows.add("\t");
			rows.add("Last name");
			rows.add("\t");
			rows.add("Test");
			rows.add("\n");

			for (int i = 0; i < 5; i++) {
				rows.add("Java");
				rows.add("\t");
				rows.add("Honk");
				rows.add("\t");
				rows.add("Success");
				rows.add("\n");
			}
			Iterator<String> iter = rows.iterator();
			while (iter.hasNext()) {
				String outputString = (String) iter.next();
				response.getOutputStream().print(outputString);
			}
			
			response.getOutputStream().flush();

		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
  • index.jsp:
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring MVC XLS Download Example</title>
</head>
<body>
	<form:form action="downloadXLS" method="post">
		<h3>Spring MVC XLS Download Example</h3>
		<input type="submit" value="Downlaod XLS Report">
	</form:form>
</body>
</html>
  • Now i will run this project on tomcat server you could choose any server below is output:

Spring MVC XLS Download Spring MVC XLS Download Spring MVC XLS Download

  • Please visit spring official site for more details 

download  Download Project:  SpringMVCDownloadXLS

Leave a Reply

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