Java中实现写Word文档

2024-09-05 23:36
文章标签 java 实现 文档 word

本文主要是介绍Java中实现写Word文档,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

背景:通过java代码,往docx文档中写入标题和段落。

依赖的maven包:

<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>
<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>4.1.2</version>
</dependency>

创建标题,网上很多文章说使用如下代码可以实现:

            // 创建一个标题XWPFParagraph titleParagraph = document.createParagraph();titleParagraph.setStyle("heading 1");XWPFRun titleRun = titleParagraph.createRun();titleRun.setText("标题测试");titleRun.setBold(true);titleRun.setFontSize(20);

但是打开word后发现标题并没有生效。

这是因为需要自己编写标题的样式信息,参考如下代码中的addCustomHeadingStyle方法。

完整的代码参考如下:

import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.List;/*** word文档工具类*/
public class DocxUtil {/*** 增加自定义标题样式* @param docxDocument 目标文档* @param strStyleId 样式名称* @param headingLevel 样式级别*/private static void addCustomHeadingStyle(XWPFDocument docxDocument, String strStyleId, int headingLevel) {CTStyle ctStyle = CTStyle.Factory.newInstance();ctStyle.setStyleId(strStyleId);CTString styleName = CTString.Factory.newInstance();styleName.setVal(strStyleId);ctStyle.setName(styleName);CTDecimalNumber indentNumber = CTDecimalNumber.Factory.newInstance();indentNumber.setVal(BigInteger.valueOf(headingLevel));// lower number > style is more prominent in the formats barctStyle.setUiPriority(indentNumber);CTOnOff onoffnull = CTOnOff.Factory.newInstance();ctStyle.setUnhideWhenUsed(onoffnull);// style shows up in the formats barctStyle.setQFormat(onoffnull);// style defines a heading of the given levelCTPPrGeneral ppr = CTPPrGeneral.Factory.newInstance();ppr.setOutlineLvl(indentNumber);ctStyle.setPPr(ppr);XWPFStyle style = new XWPFStyle(ctStyle);// is a null op if already definedXWPFStyles styles = docxDocument.createStyles();style.setType(STStyleType.PARAGRAPH);styles.addStyle(style);}/*** 生成一个标题 + 一个段落格式的docx文档* @param title 标题* @param content 正文* @param filePath docx地址*/public static void generateDocxFile(String title, String content, String filePath){try {// 创建一个新的空白docx文档XWPFDocument document = new XWPFDocument();addCustomHeadingStyle(document, "heading 1", 1);// 创建一个标题XWPFParagraph titleParagraph = document.createParagraph();titleParagraph.setStyle("heading 1");XWPFRun titleRun = titleParagraph.createRun();titleRun.setText(title);titleRun.setBold(true);titleRun.setFontSize(20);// 获取段落的CTPPr对象CTPPr pPr = titleParagraph.getCTP().getPPr();// 如果pPr为null,说明还没有属性,需要创建if (pPr == null) {pPr = titleParagraph.getCTP().addNewPPr();}// 设置文本居中对齐CTJc jc = pPr.isSetJc() ? pPr.getJc() : pPr.addNewJc();jc.setVal(STJc.CENTER); // 居中对齐// 创建一个段落XWPFParagraph paragraph = document.createParagraph();XWPFRun run = paragraph.createRun();run.setText(content);// 写入数据到文档FileOutputStream out = new FileOutputStream(new File(filePath));document.write(out);out.close();}catch (Exception e){e.printStackTrace();}}/*** 生成N个标题 + N个段落格式的docx文档* @param titleList* @param contentList* @param filePath* @throws Exception*/public static void generateDocxFile(List<String> titleList, List<String> contentList, String filePath){if(titleList.size() != contentList.size()){System.out.println("title和content数量不匹配!");}// 创建一个新的空白docx文档XWPFDocument document = new XWPFDocument();addCustomHeadingStyle(document, "heading 1", 1);for(int i = 0; i < titleList.size(); i++){/* -------------创建一个标题 ---------------*/XWPFParagraph titleParagraph = document.createParagraph();titleParagraph.setStyle("heading 1");XWPFRun titleRun = titleParagraph.createRun();titleRun.setText(titleList.get(i));titleRun.setBold(true);titleRun.setFontSize(20);// 获取段落的CTPPr对象CTPPr pPr = titleParagraph.getCTP().getPPr();// 如果pPr为null,说明还没有属性,需要创建if (pPr == null) {pPr = titleParagraph.getCTP().addNewPPr();}// 设置文本居中对齐CTJc jc = pPr.isSetJc() ? pPr.getJc() : pPr.addNewJc();jc.setVal(STJc.CENTER); // 居中对齐/* -------------创建一个段落 ---------------*/XWPFParagraph paragraph = document.createParagraph();XWPFRun run = paragraph.createRun();run.setText(contentList.get(i));}// 写入数据到文档FileOutputStream out = null;try {out = new FileOutputStream(new File(filePath));document.write(out);out.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}public static void main(String[] args) {List<String> titleList = Arrays.asList("洗车标题2", "保养标题2");List<String> contentList = Arrays.asList("洗车的操作事项:\n1)好好洗;2)洗干净", "保养的操作事项:\n1)好好保养;2)保养干净");DocxUtil.generateDocxFile(titleList, contentList, "D:\\temp\\example3.docx");}
}

效果如下,标题的属性确实是"标题1"。

这篇关于Java中实现写Word文档的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1140379

相关文章

SpringBoot应用中出现的Full GC问题的场景与解决

《SpringBoot应用中出现的FullGC问题的场景与解决》这篇文章主要为大家详细介绍了SpringBoot应用中出现的FullGC问题的场景与解决方法,文中的示例代码讲解详细,感兴趣的小伙伴可... 目录Full GC的原理与触发条件原理触发条件对Spring Boot应用的影响示例代码优化建议结论F

springboot项目中常用的工具类和api详解

《springboot项目中常用的工具类和api详解》在SpringBoot项目中,开发者通常会依赖一些工具类和API来简化开发、提高效率,以下是一些常用的工具类及其典型应用场景,涵盖Spring原生... 目录1. Spring Framework 自带工具类(1) StringUtils(2) Coll

openCV中KNN算法的实现

《openCV中KNN算法的实现》KNN算法是一种简单且常用的分类算法,本文主要介绍了openCV中KNN算法的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的... 目录KNN算法流程使用OpenCV实现KNNOpenCV 是一个开源的跨平台计算机视觉库,它提供了各

SpringBoot条件注解核心作用与使用场景详解

《SpringBoot条件注解核心作用与使用场景详解》SpringBoot的条件注解为开发者提供了强大的动态配置能力,理解其原理和适用场景是构建灵活、可扩展应用的关键,本文将系统梳理所有常用的条件注... 目录引言一、条件注解的核心机制二、SpringBoot内置条件注解详解1、@ConditionalOn

OpenCV图像形态学的实现

《OpenCV图像形态学的实现》本文主要介绍了OpenCV图像形态学的实现,包括腐蚀、膨胀、开运算、闭运算、梯度运算、顶帽运算和黑帽运算,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起... 目录一、图像形态学简介二、腐蚀(Erosion)1. 原理2. OpenCV 实现三、膨胀China编程(

通过Spring层面进行事务回滚的实现

《通过Spring层面进行事务回滚的实现》本文主要介绍了通过Spring层面进行事务回滚的实现,包括声明式事务和编程式事务,具有一定的参考价值,感兴趣的可以了解一下... 目录声明式事务回滚:1. 基础注解配置2. 指定回滚异常类型3. ​不回滚特殊场景编程式事务回滚:1. ​使用 TransactionT

Android实现打开本地pdf文件的两种方式

《Android实现打开本地pdf文件的两种方式》在现代应用中,PDF格式因其跨平台、稳定性好、展示内容一致等特点,在Android平台上,如何高效地打开本地PDF文件,不仅关系到用户体验,也直接影响... 目录一、项目概述二、相关知识2.1 PDF文件基本概述2.2 android 文件访问与存储权限2.

使用Python实现全能手机虚拟键盘的示例代码

《使用Python实现全能手机虚拟键盘的示例代码》在数字化办公时代,你是否遇到过这样的场景:会议室投影电脑突然键盘失灵、躺在沙发上想远程控制书房电脑、或者需要给长辈远程协助操作?今天我要分享的Pyth... 目录一、项目概述:不止于键盘的远程控制方案1.1 创新价值1.2 技术栈全景二、需求实现步骤一、需求

Spring LDAP目录服务的使用示例

《SpringLDAP目录服务的使用示例》本文主要介绍了SpringLDAP目录服务的使用示例... 目录引言一、Spring LDAP基础二、LdapTemplate详解三、LDAP对象映射四、基本LDAP操作4.1 查询操作4.2 添加操作4.3 修改操作4.4 删除操作五、认证与授权六、高级特性与最佳

Spring Shell 命令行实现交互式Shell应用开发

《SpringShell命令行实现交互式Shell应用开发》本文主要介绍了SpringShell命令行实现交互式Shell应用开发,能够帮助开发者快速构建功能丰富的命令行应用程序,具有一定的参考价... 目录引言一、Spring Shell概述二、创建命令类三、命令参数处理四、命令分组与帮助系统五、自定义S