How To Automatically Download Generated XLS File on Client Side (Spring MVC + JXLS)

Sometimes we want to generate report to be downloaded by user without save it on the server side. So here is one of what I did for my web application. The process to create the document are do with the download process on client side. For this example, I create xls file using Jxls library.  But you will also need apache poi libs and apache common too for this process.

Download File Sample

xlsHasil

First of all, we need to prepare xls source file that we will use. Mine is like this

xlssource

Then I create simple form to send the parameter and call the controller. Here my code:

<%@page import="com.aries.blog.controller.BaseController"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>File Download Page</title>

        <%
            String baseURL = (String) request.getAttribute(BaseController.PARAM_BASE_URL);
        %>
        <!-- BOOTSTRAP STYLES-->
        <link href="<%=baseURL%>/css/bootstrap.min.css" rel="stylesheet" />

    </head>
    <body>
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="panel panel-primary" style="margin-bottom: 0px;">
                    <div class="panel-heading">
                        Form Download Sample File
                    </div>
                    <div class="panel-body">
                        <div class="row">
                            <div class="col-md-6">
                                <form method="GET" action="<%=baseURL%>/getsamplereport" role="form">
                                    <div class="form-group">
                                        <label>Your Name : </label>
                                        <input type="text" class="form-username" name="name"/>
                                    </div>  
                                    <div class="form-group">
                                        <button type="submit" class="btn btn-primary">Get File..!</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>            
        </div>
    </body>
</html>

This is my controller class

@Controller
public class FileDownloadController extends BaseController{

    @Autowired
    private ServletContext context;

    @RequestMapping(value = "/filedwld", method = RequestMethod.GET)
    public String fileDownloadView(ModelMap model, HttpServletRequest req) {
        model.put(PARAM_BASE_URL, getBaseURL(req));
        return "FileDownload";
    }

    @RequestMapping(value = "/getsamplereport", method = RequestMethod.GET)
    public String getSampleReport(HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value = "name") String name) {
        try (ServletOutputStream os = response.getOutputStream()) {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename=\"test.xls\""); //will be the name of file
            String reportLocation = context.getRealPath("WEB-INF");

            Map datasource = new HashMap();
            datasource.put("name", name);

            XLSTransformer transformer = new XLSTransformer();
            try (FileInputStream fis = new FileInputStream(reportLocation + "/SampleFile.xls");) { //the source file
                Workbook workbook = transformer.transformXLS(fis, datasource);
                workbook.getCreationHelper().createFormulaEvaluator().evaluateAll(); //just to make sure the result has been calculated properly
                workbook.write(os);
                os.flush();
            } catch (ParsePropertyException | InvalidFormatException ex) {
                Logger.getLogger(FileDownloadController.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (IOException ex) {
            Logger.getLogger(FileDownloadController.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

}

Hope this simple sample can help 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s