知识准备
需要理解Apache POI遵循的标准(Office Open XML(OOXML)标准和微软的OLE 2复合文档格式(OLE2)), 这将对应着API的依赖包。
什么是POI
Apache POI 是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程序对Microsoft Office格式档案读和写的功能。POI为“Poor Obfuscation Implementation”的首字母缩写,意为“简洁版的模糊实现”。
Apache POI 是创建和维护操作各种符合Office Open XML(OOXML)标准和微软的OLE 2复合文档格式(OLE2)的Java API。更多请参考 官方文档。
实现案例
这里展示SpringBoot集成POI导出用户信息的Word例子。
Pom依赖
引入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>
导出Word
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中导出Word方法
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; } }
导出:
导出后的word:
以上是使用Java SpringBoot集成POI实现Word文档导出的详细内容。更多信息请关注PHP中文网其他相关文章!

本文讨论了使用Maven和Gradle进行Java项目管理,构建自动化和依赖性解决方案,以比较其方法和优化策略。

本文使用Maven和Gradle之类的工具讨论了具有适当的版本控制和依赖关系管理的自定义Java库(JAR文件)的创建和使用。

本文讨论了使用咖啡因和Guava缓存在Java中实施多层缓存以提高应用程序性能。它涵盖设置,集成和绩效优势,以及配置和驱逐政策管理最佳PRA

本文讨论了使用JPA进行对象相关映射,并具有高级功能,例如缓存和懒惰加载。它涵盖了设置,实体映射和优化性能的最佳实践,同时突出潜在的陷阱。[159个字符]

Java的类上载涉及使用带有引导,扩展程序和应用程序类负载器的分层系统加载,链接和初始化类。父代授权模型确保首先加载核心类别,从而影响自定义类LOA


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

记事本++7.3.1
好用且免费的代码编辑器

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

mPDF
mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。