Using Java SpringBoot to integrate POI to export Word documents
Knowledge preparation
You need to understand the standards that Apache POI follows (Office Open XML (OOXML) standard and Microsoft's OLE 2 compound document format (OLE2)), which will correspond to the API's dependency packages .
What is POI
Apache POI is a free and open source cross-platform Java API written in Java. Apache POI provides an API for Java programs to read Microsoft Office format files. and write functions. POI is the abbreviation of "Poor Obfuscation Implementation", which means "concise version of fuzzy implementation".
Apache POI is a Java API that creates and maintains operations compliant with the Office Open XML (OOXML) standard and Microsoft's OLE 2 Composite Document Format (OLE2). Please refer to the official documentation for more information.
Implementation Case
Here is a Word example of SpringBoot integrating POI to export user information.
Pom dependency
Introducing the dependency package of poi
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>5.2.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>5.2.2</version> </dependency>
Exporting Word
Methods exported in UserController
package tech.pdai.springboot.file.word.poi.controller; import java.io.OutputStream; import javax.servlet.http.HttpServletResponse; import io.swagger.annotations.ApiOperation; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import tech.pdai.springboot.file.word.poi.service.IUserService; /** * @author pdai */ @RestController @RequestMapping("/user") public class UserController { @Autowired private IUserService userService; @ApiOperation("Download Word") @GetMapping("/word/download") public void download(HttpServletResponse response){ try { XWPFDocument document = userService.generateWordXWPFDocument(); response.reset(); response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-disposition", "attachment;filename=user_world_" + System.currentTimeMillis() + ".docx"); OutputStream os = response.getOutputStream(); document.write(os); os.close(); } catch (Exception e) { e.printStackTrace(); } } }
UserServiceImple Export Word method
package tech.pdai.springboot.file.word.poi.service.impl; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import lombok.extern.slf4j.Slf4j; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.util.Units; import org.apache.poi.xwpf.usermodel.BreakType; 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.XWPFTableCell; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblPr; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.stereotype.Service; import tech.pdai.springboot.file.word.poi.entity.User; import tech.pdai.springboot.file.word.poi.service.IUserService; /** * @author pdai */ @Slf4j @Service public class UserServiceImpl implements IUserService { @Override public XWPFDocument generateWordXWPFDocument(){ XWPFDocument doc = new XWPFDocument(); // Title createTitle(doc, "Java 全栈知识体系"); // Chapter 1 createChapterH1(doc, "1. 知识准备"); createChapterH2(doc, "1.1 什么是POI"); createParagraph(doc, "Apache POI 是创建和维护操作各种符合Office Open XML(OOXML)标准和微软的OLE 2复合文档格式(OLE2)的Java API。用它可以使用Java读取和创建,修改MS Excel文件.而且,还可以使用Java读取和创建MS Word和MSPowerPoint文件。更多请参考[官方文档](https://poi.apache.org/index.html)"); createChapterH2(doc, "1.2 POI中基础概念"); createParagraph(doc, "生成xls和xlsx有什么区别?POI对Excel中的对象的封装对应关系?"); // Chapter 2 createChapterH1(doc, "2. 实现案例"); createChapterH2(doc, "2.1 用户列表示例"); createParagraph(doc, "以导出用户列表为例"); // 表格 List<User> userList = getUserList(); XWPFParagraph paragraph = doc.createParagraph(); XWPFTable table = paragraph.getDocument().createTable(userList.size(), 5); table.setWidth(500); table.setCellMargins(20, 20, 20, 20); //表格属性 CTTblPr tablePr = table.getCTTbl().addNewTblPr(); //表格宽度 CTTblWidth width = tablePr.addNewTblW(); width.setW(BigInteger.valueOf(8000)); for(int i = 0; i< userList.size(); i++) { List<XWPFTableCell> tableCells = table.getRow(i).getTableCells(); tableCells.get(0).setText(userList.get(i).getId()+""); tableCells.get(1).setText(userList.get(i).getUserName()); tableCells.get(2).setText(userList.get(i).getEmail()); tableCells.get(3).setText(userList.get(i).getPhoneNumber()+""); tableCells.get(4).setText(userList.get(i).getDescription()); } createChapterH2(doc, "2.2 图片导出示例"); createParagraph(doc, "以导出图片为例"); // 图片 InputStream stream = null; try { XWPFParagraph paragraph3 = doc.createParagraph(); Resource resource = new ClassPathResource("pdai-guli.png"); stream = new FileInputStream(resource.getFile()); XWPFRun run = paragraph3.createRun(); run.addPicture(stream, Document.PICTURE_TYPE_PNG, "Generated", Units.toEMU(256), Units.toEMU(256)); } catch (IOException | InvalidFormatException e) { e.printStackTrace(); } return doc; } private void createTitle(XWPFDocument doc, String content){ XWPFParagraph title = doc.createParagraph(); title.setAlignment(ParagraphAlignment.CENTER); XWPFRun r1 = title.createRun(); r1.setBold(true); r1.setFontFamily("宋体"); r1.setText(content); r1.setFontSize(22); } private void createChapterH1(XWPFDocument doc, String content){ XWPFParagraph actTheme = doc.createParagraph(); actTheme.setAlignment(ParagraphAlignment.LEFT); XWPFRun runText1 = actTheme.createRun(); runText1.setBold(true); runText1.setText(content); runText1.setFontSize(18); } private void createChapterH2(XWPFDocument doc, String content){ XWPFParagraph actType = doc.createParagraph(); XWPFRun runText2 = actType.createRun(); runText2.setBold(true); runText2.setText(content); runText2.setFontSize(15); } private void createParagraph(XWPFDocument doc, String content){ XWPFParagraph actType = doc.createParagraph(); XWPFRun runText2 = actType.createRun(); runText2.setText(content); runText2.setFontSize(11); } private List<User> getUserList(){ List<User> userList = new ArrayList<>(); for (int i = 0; i < 5; i++) { userList.add(User.builder() .id(Long.parseLong(i + "")).userName("pdai" + i).email("pdai@pdai.tech" + i).phoneNumber(121231231231L) .description("hello world" + i) .build()); } return userList; } }
Export:
##Exported word:
The above is the detailed content of Using Java SpringBoot to integrate POI to export Word documents. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
