Spring Boot - Generate Microsoft Word with Apache POI

Hello everyone, today we will learn how to generate and export a Microsoft word document with Spring Boot and Apache POI. 

You can generate a Microsoft word document like the below at the end of this post,


Final Project Structure



Maven[pom.xml]

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.5</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<artifactId>springboot-microsoft-word</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-microsoft-word</name>

<properties>
<java.version>11</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

<description>springboot-jpa-thymeleaf-crud</description>
<groupId>com.knf.dev.demo</groupId>
</project>


Create Word Helper Class

You can use XWPFParagraph to create paragraphs and XWPFRun to create text. 
You can use XWPFRun for setting the styling properties of the font. It contains methods for changing font properties such as colour, font size, italic, bold, capitalized, embossed, and many more. 
You can use the XWPFTable component to create and initialize a table element.
package com.knf.dev.demo.helper;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.Document;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

public class WordHelper {

static String imgFile = "/home/user/Downloads/KnowledgeFactory-master"
+ "/springboot-microsoft-word"
+ "/src/main/resources/spring.png";

public static ByteArrayInputStream generateWord()
throws FileNotFoundException, IOException,
InvalidFormatException {

try (XWPFDocument doc = new XWPFDocument()) {

XWPFParagraph p1 = doc.createParagraph();
p1.setAlignment(ParagraphAlignment.CENTER);
// Set Text to Bold and font size to 22 for first paragraph
XWPFRun r1 = p1.createRun();
r1.setBold(true);
r1.setItalic(true);
r1.setFontSize(22);
r1.setText("Spring Boot + Apache POI Example");
r1.setFontFamily("Courier");
r1.setColor("008000");
r1.addBreak();

XWPFParagraph p2 = doc.createParagraph();
// Set color for second paragraph
XWPFRun r2 = p2.createRun();
r2.setText("Spring Boot + Apache POI Example");
r2.setColor("FF5733");
r2.setEmbossed(true);
r2.setStrikeThrough(true);
r2.addBreak();
r2.addBreak();

XWPFParagraph p3 = doc.createParagraph();
p3.setAlignment(ParagraphAlignment.CENTER);
XWPFRun r3 = p3.createRun();
r3.setBold(true);
r3.setItalic(true);
r3.setFontSize(22);
r3.setText("Table");
r3.setFontFamily("Arial");

XWPFTable table = doc.createTable();
// Creating first Row
XWPFTableRow row1 = table.getRow(0);
row1.getCell(0).setText("Java, Scala");
row1.addNewTableCell().setText("PHP, Flask");
row1.addNewTableCell().setText("Ruby, Rails");

// Creating second Row
XWPFTableRow row2 = table.createRow();
row2.getCell(0).setText("C, C ++");
row2.getCell(1).setText("Python, Kotlin");
row2.getCell(2).setText("Android, React");

// add png image
XWPFRun r4 = doc.createParagraph().createRun();
r4.addBreak();
XWPFParagraph p = doc.createParagraph();
XWPFRun r = p.createRun();
try (FileInputStream is = new FileInputStream(imgFile)) {
r.addPicture(is, Document.PICTURE_TYPE_PNG, imgFile,
Units.toEMU(500), Units.toEMU(200));

}

ByteArrayOutputStream b = new ByteArrayOutputStream();
doc.write(b);
return new ByteArrayInputStream(b.toByteArray());
}

}
}



Create Word Controller

package com.knf.dev.demo.controller;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.knf.dev.demo.helper.WordHelper;

@RestController
@RequestMapping("/api")
public class WordController {

@GetMapping(value = "/word",
produces = "application/vnd.openxmlformats-"
+ "officedocument.wordprocessingml.document")
public ResponseEntity<InputStreamResource> word()
throws IOException, InvalidFormatException {

ByteArrayInputStream bis = WordHelper.generateWord();
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition",
"inline; filename=mydoc.docx");
return ResponseEntity.ok().headers(headers).
body(new InputStreamResource(bis));
}
}


Spring Boot Main Driver

package com.knf.dev.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class KnowledgefactorydemoApplication {

public static void main(String[] args) {
SpringApplication.run(KnowledgefactorydemoApplication.class, args);
}

}


Download the complete source code - click here                               

Local Setup and Run the application

Step1: Download or clone the source code from GitHub to the local machine - Click here

Step 2: mvn clean install

Step 3: Run the Spring Boot application - mvn spring-boot:run

Hit this URL in your local system, http://localhost:8080/api/word

Open the downloaded word file


Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Spring boot video streaming example-HTML5

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Custom Exception Handling in Quarkus REST API

DataTable-Pagination example with Spring boot, jQuery and ajax

ReactJS, Spring Boot JWT Authentication Example

Spring Webflux File Download Example

Node JS mini projects with source code - free download