[Java] Creating a Microsoft Word Report Easily using Servlet and A Plain HTML Template

Yesterday one of my friend, Edward Barchia, asked me a very simple question, “how can i creating an MSWord Report without using Jasper Report”. Because somehow, jasper report creates a very weird output when exported into Word file (.doc).

One fastest solution is using a html file, and renamed into .doc. Not an elegant solution, but perhaps (at that moment) is the best solution we had.

Okay, so basically what i need is only 2 files, 1 html template and a java servlet files. This is my HTML template, i put it on drie E and name it hello.html

<html>
	<head></head>
	<body>
		Test, hello ${name}
	</body>
</html>

And this is my servlet file,

package com.edw.testdownloaddoc.servlet;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;

@WebServlet(name = "downloadServlet", urlPatterns = {"/downloadServlet"})
public class DownloadServlet extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        BufferedReader downloadFile = new BufferedReader(new FileReader("e:\\hello.html"));
        FileInputStream inputStream = null;
        OutputStream outStream = null;
        try {
            String s;
            StringBuilder sb = new StringBuilder();
            while ((s=downloadFile.readLine()) != null) {
                if(s.contains("${name}"))
                    s = s.replace("${name}", "Edwin");
                sb.append(s);
            }
 
            response.setContentLength((int) sb.toString().length());
            response.setContentType("application/msword");           
 
            // response header
            String nameFile = "hello.doc";
            String headerKey = "Content-Disposition";
            String headerValue = String.format("attachment; filename=\"%s\"",nameFile);
            response.setHeader(headerKey, headerValue);
 
            // Write response
            outStream = response.getOutputStream();
            IOUtils.write(sb.toString(), outStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            IOUtils.closeQuietly(downloadFile);
            IOUtils.closeQuietly(inputStream);
            IOUtils.closeQuietly(outStream);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
}

Oh, and before i forgot, this is my pom.xml dependencies

<dependencies>
	<dependency>
		<groupId>commons-io</groupId>
		<artifactId>commons-io</artifactId>
		<version>2.2</version>
	</dependency>
	<dependency>
		<groupId>javax</groupId>
		<artifactId>javaee-web-api</artifactId>
		<version>7.0</version>
		<scope>provided</scope>
	</dependency>
</dependencies>

This is the final output looks like,
helloworld

Google+

2 Comments

Manjunathimagin

about 2 years ago

Hi Edwin , I am compiling above java program as "javac DownloadServlet.java" then I am getting errors like 1.) Cannot find the symbol (example : HTTPServlet request not found ) 2.) Package does not exist ( IOUtils does not exists ) please help me to solve the issue. Thank You

Reply

edwin

about 2 years ago

Hi Manju, you can add commons-io on Maven pom.xml, it solve IOUtils problem as for HTTPServlet, it suppose to be automatically added when selecting java web project

Leave a Comment

Please be polite. We appreciate that.
Your email address will not be published and required fields are marked


:-[ (B) (^) (P) (@) (O) (D) :-S ;-( (C) (&) :-$ (E) (~) (K) (I) (L) (8) :-O (T) (G) (F) :-( (H) :-) (*) :-D (N) (Y) :-P (U) (W) ;-)