使用 POI 在 Word 中重新开始编号、自定义标题格式

效果图

引入依赖

html 复制代码
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.2</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>ooxml-schemas</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>4.1.2</version>
        </dependency>

示例代码

java 复制代码
import cn.hutool.core.date.DateTime;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.xml.bind.annotation.adapters.HexBinaryAdapter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.time.LocalDateTime;

@Component
public class CreateTestWordUtil {
	private static CreateTestWordUtil createJGWordUtil;
	int numLevel = 0; //编号
	String filePath;
	String filename;
	@PostConstruct
	public void init() {
		createJGWordUtil = this;
	}

	/**
	 * @param styles       样式
	 * @param strStyleId   标题id
	 * @param headingLevel 标题级别
	 * @param pointSize    字体大小(/2)
	 * @param hexColor     字体颜色
	 * @param typefaceName 字体名称(默认微软雅黑)
	 */
	public void createHeadingStyle(XWPFStyles styles, String strStyleId,
								   int headingLevel, int pointSize, String hexColor, String typefaceName) {
		//创建样式
		CTStyle ctStyle = CTStyle.Factory.newInstance();
		//设置id
		ctStyle.setStyleId(strStyleId);

		CTString styleName = CTString.Factory.newInstance();
		styleName.setVal(strStyleId);
		ctStyle.setName(styleName);

		CTDecimalNumber indentNumber = CTDecimalNumber.Factory.newInstance();
		indentNumber.setVal(BigInteger.valueOf(headingLevel));

		// 数字越低在格式栏中越突出
		ctStyle.setUiPriority(indentNumber);

		CTOnOff onoffnull = CTOnOff.Factory.newInstance();
		ctStyle.setUnhideWhenUsed(onoffnull);

		// 样式将显示在"格式"栏中
		ctStyle.setQFormat(onoffnull);

		// 样式定义给定级别的标题
		if (headingLevel != 0) {
			CTPPr ppr = CTPPr.Factory.newInstance();
			ppr.setOutlineLvl(indentNumber);
			ctStyle.setPPr(ppr);
		}
		XWPFStyle style = new XWPFStyle(ctStyle);

		CTHpsMeasure size = CTHpsMeasure.Factory.newInstance();
		size.setVal(new BigInteger(String.valueOf(pointSize)));
		CTHpsMeasure size2 = CTHpsMeasure.Factory.newInstance();
		size2.setVal(new BigInteger(String.valueOf(pointSize)));

		CTFonts fonts = CTFonts.Factory.newInstance();
		if (typefaceName == null || typefaceName.equals("")) typefaceName = "微软雅黑";
		fonts.setAscii(typefaceName);    //字体

		CTRPr rpr = CTRPr.Factory.newInstance();
		rpr.setRFonts(fonts);
		rpr.setSz(size);
		rpr.setSzCs(size2);    //字体大小

		CTColor color = CTColor.Factory.newInstance();
		color.setVal(hexToBytes(hexColor));
		rpr.setColor(color);    //字体颜色
		style.getCTStyle().setRPr(rpr);
		// is a null op if already defined

		style.setType(STStyleType.PARAGRAPH);
		styles.addStyle(style);

	}

	public void writeWordAQJG() {
		// 文档生成方法
		XWPFDocument doc = new XWPFDocument();

		XWPFStyles xwpfStyles = doc.createStyles();
		CTFonts fonts = CTFonts.Factory.newInstance();
		fonts.setAscii("微软雅黑");
		fonts.setEastAsia("微软雅黑");
		fonts.setHAnsi("微软雅黑");
		xwpfStyles.setDefaultFonts(fonts);
		createHeadingStyle(xwpfStyles, "标题 1", 1, 32, "000000", "微软雅黑");
		createHeadingStyle(xwpfStyles, "标题 2", 2, 28, "000000", "微软雅黑");
		createHeadingStyle(xwpfStyles, "正文", 0, 24, "000000", "微软雅黑");

		XWPFParagraph xwpfParagraphtop = doc.createParagraph(); // 创建段落
		xwpfParagraphtop.setFontAlignment(2);
		xwpfParagraphtop.setStyle("标题 1");
		XWPFRun xwpfRuntop = xwpfParagraphtop.createRun(); // 创建段落文本
		xwpfRuntop.setText(String.format("标题")); // 设置文本
//		xwpfRuntop.setFontFamily("微软雅黑");
		xwpfRuntop.setBold(true);
		xwpfRuntop.setFontSize(24);
//		xwpfRuntop.addBreak();// 换行
		xwpfRuntop.addTab();

		XWPFParagraph xwpfParagraphtop1 = doc.createParagraph(); // 创建段落
		xwpfParagraphtop1.setFontAlignment(3);
		xwpfParagraphtop1.setStyle("正文");
		XWPFRun xwpfRuntop1 = xwpfParagraphtop1.createRun(); // 创建段落文本
		xwpfRuntop1.setText("- abcd"); // 设置文本
//		xwpfRuntop1.setFontSize(12);
//		xwpfRuntop1.addBreak();// 换行
		xwpfRuntop1.addTab();


		FileOutputStream out = null; // 创建输出流
		try {
			//需要的配置项
			writeItemBGGS(doc);
			writeItemNGDWQK(doc);
			writeItemNGZCQK(doc);
			writeItemDDZLQK(doc);

			if (System.getProperty("os.name").toLowerCase().contains("linux")) {
				filePath = "/usr/local/createfile/weekly/";
			} else {
				filePath = "D:\\hian\\createfile\\weekly\\";
			}

			filename = LocalDateTime.now().getYear() + "年" + LocalDateTime.now().getMonth().getValue() + "月-" + DateTime.now().getTime();

			File file = new File(filePath + filename + ".docx");
			if (!file.exists()) {
				file.getParentFile().mkdirs();
				file.createNewFile();
			}
			out = new FileOutputStream(file);
			doc.write(out);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					doc.close();
					out.close();

				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}


	public void writeItemBGGS(XWPFDocument doc) {
		//编号等级
		CTAbstractNum cTAbstractNum = CTAbstractNum.Factory.newInstance();
		cTAbstractNum.setAbstractNumId(BigInteger.valueOf(10));

		CTLvl cTLvl = cTAbstractNum.addNewLvl();
		cTLvl.addNewNumFmt().setVal(STNumberFormat.DECIMAL);
		cTLvl.addNewLvlText().setVal("%1.");
		cTLvl.addNewStart().setVal(BigInteger.valueOf(1));

		XWPFAbstractNum abstractNum = new XWPFAbstractNum(cTAbstractNum);
		XWPFNumbering numbering = doc.createNumbering();
		BigInteger abstractNumID = numbering.addAbstractNum(abstractNum);
		BigInteger numID = numbering.addNum(abstractNumID);

		XWPFParagraph xwpfParagraphtext = doc.createParagraph(); // 创建段落
		xwpfParagraphtext.setAlignment(ParagraphAlignment.LEFT);
		xwpfParagraphtext.setNumID(numID);
		xwpfParagraphtext.setStyle("标题 1");
		XWPFRun xwpfRuntext = xwpfParagraphtext.createRun(); // 创建段落文本
		xwpfRuntext.setText("标题");
		xwpfRuntext.setBold(true);

		XWPFParagraph xwpfParagraphtext1 = doc.createParagraph(); // 创建段落
		XWPFRun xwpfRuntext1 = xwpfParagraphtext1.createRun(); // 创建段落文本
		xwpfRuntext1.setStyle("正文");
		xwpfRuntext1.setText("abcd");
		xwpfRuntext1.addBreak();// 换行

		numLevel++;
	}


	public void writeItemNGDWQK(XWPFDocument doc) {
		//编号等级
		CTAbstractNum cTAbstractNum = CTAbstractNum.Factory.newInstance();
		cTAbstractNum.setAbstractNumId(BigInteger.valueOf(10));


		CTLvl cTLvl = cTAbstractNum.addNewLvl();
		cTLvl.addNewNumFmt().setVal(STNumberFormat.DECIMAL);
		cTLvl.addNewLvlText().setVal("%1.");
		cTLvl.addNewStart().setVal(BigInteger.valueOf(1));

		XWPFAbstractNum abstractNum = new XWPFAbstractNum(cTAbstractNum);
		XWPFNumbering numbering = doc.createNumbering();
		BigInteger abstractNumID = numbering.addAbstractNum(abstractNum);
		BigInteger numID = numbering.addNum(abstractNumID);

		XWPFParagraph xwpfParagraphtext = doc.createParagraph(); // 创建段落
		xwpfParagraphtext.setAlignment(ParagraphAlignment.LEFT);
		xwpfParagraphtext.setNumID(numID);
		xwpfParagraphtext.setStyle("标题 1");
		XWPFRun xwpfRuntext = xwpfParagraphtext.createRun(); // 创建段落文本
		xwpfRuntext.setText("标题");
		xwpfRuntext.setBold(true);

		XWPFParagraph xwpfParagraphtext1 = doc.createParagraph(); // 创建段落
		XWPFRun xwpfRuntext1 = xwpfParagraphtext1.createRun(); // 创建段落文本
		xwpfRuntext1.setStyle("正文");
		xwpfRuntext1.setText("abcd");

		xwpfRuntext1.addBreak();// 换行


		numLevel++;
	}


	public void writeItemNGZCQK(XWPFDocument doc) {
		//编号等级
		CTAbstractNum cTAbstractNum = CTAbstractNum.Factory.newInstance();
		cTAbstractNum.setAbstractNumId(BigInteger.valueOf(10));

		CTLvl cTLvl = cTAbstractNum.addNewLvl();
		cTLvl.addNewNumFmt().setVal(STNumberFormat.DECIMAL);
		cTLvl.addNewLvlText().setVal("%1.");
		cTLvl.addNewStart().setVal(BigInteger.valueOf(1));

		XWPFAbstractNum abstractNum = new XWPFAbstractNum(cTAbstractNum);
		XWPFNumbering numbering = doc.createNumbering();
		BigInteger abstractNumID = numbering.addAbstractNum(abstractNum);
		BigInteger numID = numbering.addNum(abstractNumID);

		XWPFParagraph xwpfParagraphtext = doc.createParagraph(); // 创建段落
		xwpfParagraphtext.setAlignment(ParagraphAlignment.LEFT);
		xwpfParagraphtext.setNumID(numID);
		xwpfParagraphtext.setStyle("标题 1");
		XWPFRun xwpfRuntext = xwpfParagraphtext.createRun(); // 创建段落文本
		xwpfRuntext.setText("标题");
		xwpfRuntext.setBold(true);

		numLevel++;

		writeItemZCRRQK(doc);
		writeItemGFXZC(doc);
		writeItemXTHGQK(doc);
	}

	public void writeItemDDZLQK(XWPFDocument doc) {
		//编号等级
		CTAbstractNum cTAbstractNum = CTAbstractNum.Factory.newInstance();
		cTAbstractNum.setAbstractNumId(BigInteger.valueOf(10));

		CTLvl cTLvl = cTAbstractNum.addNewLvl();
		cTLvl.addNewNumFmt().setVal(STNumberFormat.DECIMAL);
		cTLvl.addNewLvlText().setVal("%1.");
		cTLvl.addNewStart().setVal(BigInteger.valueOf(1));

		XWPFAbstractNum abstractNum = new XWPFAbstractNum(cTAbstractNum);
		XWPFNumbering numbering = doc.createNumbering();
		BigInteger abstractNumID = numbering.addAbstractNum(abstractNum);
		BigInteger numID = numbering.addNum(abstractNumID);

		XWPFParagraph xwpfParagraphtext = doc.createParagraph(); // 创建段落
		xwpfParagraphtext.setAlignment(ParagraphAlignment.LEFT);
		xwpfParagraphtext.setNumID(numID);
		xwpfParagraphtext.setStyle("标题 1");
		XWPFRun xwpfRuntext = xwpfParagraphtext.createRun(); // 创建段落文本
		xwpfRuntext.setText("标题");
		xwpfRuntext.setBold(true);

		numLevel++;
		writeItemZLLXTJ(doc);
		writeItemZLXYTJ(doc);
	}

	public void writeItemZCRRQK(XWPFDocument doc) {
		//编号等级
		CTAbstractNum cTAbstractNum = CTAbstractNum.Factory.newInstance();
		cTAbstractNum.setAbstractNumId(BigInteger.valueOf(13));

		CTLvl cTLvl = cTAbstractNum.addNewLvl();
		cTLvl.addNewNumFmt().setVal(STNumberFormat.DECIMAL);

		cTLvl.addNewLvlText().setVal(numLevel + ".%1");
		cTLvl.addNewStart().setVal(BigInteger.valueOf(1));

		XWPFAbstractNum abstractNum = new XWPFAbstractNum(cTAbstractNum);
		XWPFNumbering numbering = doc.createNumbering();
		BigInteger abstractNumID = numbering.addAbstractNum(abstractNum);
		BigInteger numID = numbering.addNum(abstractNumID);

		XWPFParagraph xwpfParagraphtext = doc.createParagraph(); // 创建标题段落
		xwpfParagraphtext.setNumID(numID);
		xwpfParagraphtext.setStyle("标题 2");
		XWPFRun xwpfRuntext = xwpfParagraphtext.createRun(); // 创建段落文本
		xwpfRuntext.setText("标题");
		xwpfRuntext.setBold(true);

		XWPFParagraph xwpfParagraphtext1 = doc.createParagraph(); // 创建段落
		XWPFRun xwpfRuntext1 = xwpfParagraphtext1.createRun(); // 创建段落文本
		xwpfRuntext1.setStyle("正文");
		xwpfRuntext1.setText(String.format("abcd:"));
//		xwpfRuntext1.addTab();
//		xwpfRuntext1.addBreak();// 换行

	}

	public void writeItemGFXZC(XWPFDocument doc) {
		//编号等级
		CTAbstractNum cTAbstractNum = CTAbstractNum.Factory.newInstance();
		cTAbstractNum.setAbstractNumId(BigInteger.valueOf(13));

		CTLvl cTLvl = cTAbstractNum.addNewLvl();
		cTLvl.addNewNumFmt().setVal(STNumberFormat.DECIMAL);

		cTLvl.addNewLvlText().setVal(numLevel + ".%1");
		cTLvl.addNewStart().setVal(BigInteger.valueOf(1));

		XWPFAbstractNum abstractNum = new XWPFAbstractNum(cTAbstractNum);
		XWPFNumbering numbering = doc.createNumbering();
		BigInteger abstractNumID = numbering.addAbstractNum(abstractNum);
		BigInteger numID = numbering.addNum(abstractNumID);

		XWPFParagraph xwpfParagraphtext = doc.createParagraph(); // 创建标题段落
		xwpfParagraphtext.setNumID(numID);
		xwpfParagraphtext.setStyle("标题 2");
		XWPFRun xwpfRuntext = xwpfParagraphtext.createRun(); // 创建段落文本
		xwpfRuntext.setText("标题");
		xwpfRuntext.setBold(true);

	}

	public void writeItemXTHGQK(XWPFDocument doc) {
		//编号等级
		CTAbstractNum cTAbstractNum = CTAbstractNum.Factory.newInstance();
		cTAbstractNum.setAbstractNumId(BigInteger.valueOf(13));

		CTLvl cTLvl = cTAbstractNum.addNewLvl();
		cTLvl.addNewNumFmt().setVal(STNumberFormat.DECIMAL);

		cTLvl.addNewLvlText().setVal(numLevel + ".%1");
		cTLvl.addNewStart().setVal(BigInteger.valueOf(1));

		XWPFAbstractNum abstractNum = new XWPFAbstractNum(cTAbstractNum);
		XWPFNumbering numbering = doc.createNumbering();
		BigInteger abstractNumID = numbering.addAbstractNum(abstractNum);
		BigInteger numID = numbering.addNum(abstractNumID);

		XWPFParagraph xwpfParagraphtext = doc.createParagraph(); // 创建标题段落
		xwpfParagraphtext.setNumID(numID);
		xwpfParagraphtext.setStyle("标题 2");
		XWPFRun xwpfRuntext = xwpfParagraphtext.createRun(); // 创建段落文本
		xwpfRuntext.setText("标题");
		xwpfRuntext.setBold(true);

	}

	public void writeItemZLLXTJ(XWPFDocument doc) {
		//编号等级
		CTAbstractNum cTAbstractNum = CTAbstractNum.Factory.newInstance();
		cTAbstractNum.setAbstractNumId(BigInteger.valueOf(14));

		CTLvl cTLvl = cTAbstractNum.addNewLvl();
		cTLvl.addNewNumFmt().setVal(STNumberFormat.DECIMAL);

		cTLvl.addNewLvlText().setVal(numLevel + ".%1");
		cTLvl.addNewStart().setVal(BigInteger.valueOf(1));

		XWPFAbstractNum abstractNum = new XWPFAbstractNum(cTAbstractNum);
		XWPFNumbering numbering = doc.createNumbering();
		BigInteger abstractNumID = numbering.addAbstractNum(abstractNum);
		BigInteger numID = numbering.addNum(abstractNumID);

		XWPFParagraph xwpfParagraphtext = doc.createParagraph(); // 创建标题段落
		xwpfParagraphtext.setNumID(numID);
		xwpfParagraphtext.setStyle("标题 2");
		XWPFRun xwpfRuntext = xwpfParagraphtext.createRun(); // 创建段落文本
		xwpfRuntext.setText("标题");
		xwpfRuntext.setBold(true);

	}

	public void writeItemZLXYTJ(XWPFDocument doc) {
		//编号等级
		CTAbstractNum cTAbstractNum = CTAbstractNum.Factory.newInstance();
		cTAbstractNum.setAbstractNumId(BigInteger.valueOf(14));

		CTLvl cTLvl = cTAbstractNum.addNewLvl();
		cTLvl.addNewNumFmt().setVal(STNumberFormat.DECIMAL);

		cTLvl.addNewLvlText().setVal(numLevel + ".%1");
		cTLvl.addNewStart().setVal(BigInteger.valueOf(1));

		XWPFAbstractNum abstractNum = new XWPFAbstractNum(cTAbstractNum);
		XWPFNumbering numbering = doc.createNumbering();
		BigInteger abstractNumID = numbering.addAbstractNum(abstractNum);
		BigInteger numID = numbering.addNum(abstractNumID);

		XWPFParagraph xwpfParagraphtext = doc.createParagraph(); // 创建标题段落
		xwpfParagraphtext.setNumID(numID);
		xwpfParagraphtext.setStyle("标题 2");
		XWPFRun xwpfRuntext = xwpfParagraphtext.createRun(); // 创建段落文本
		xwpfRuntext.setText("标题");
		xwpfRuntext.setBold(true);

		XWPFParagraph xwpfParagraphtext1 = doc.createParagraph(); // 创建段落
		XWPFRun xwpfRuntext1 = xwpfParagraphtext1.createRun(); // 创建段落文本
		xwpfRuntext1.setStyle("正文");
		xwpfRuntext1.setText(String.format("abc"));

	}

	public static byte[] hexToBytes(String hexString) {
		HexBinaryAdapter adapter = new HexBinaryAdapter();
		byte[] bytes = adapter.unmarshal(hexString);
		return bytes;
	}

}
相关推荐
Jacob程序员6 小时前
java导出word文件(手绘)
java·开发语言·word
q2498596936 小时前
前端预览word、excel、ppt
前端·word·excel
flashman9116 小时前
python在word中插入图片
python·microsoft·自动化·word
hairenjing112313 小时前
使用 Mac 数据恢复从 iPhoto 图库中恢复照片
windows·stm32·嵌入式硬件·macos·word
初九之潜龙勿用1 天前
C#结合JS解决Word添加无效位图导致进程停滞的问题
javascript·ui·c#·word·asp.net
火星技术1 天前
Excel快速转换文档word工具
word·excel
小鲨鱼-LFSJXY2 天前
【数据分享】2024年我国省市县三级的生活服务设施数量(46类设施/Excel/Shp格式)
poi·数据分享·立方数据学社·生活服务设施
棱角~~2 天前
10款PDF转Word软件工具的使用感受及其亮点!!!
经验分享·pdf·word·学习方法
shujuwa662 天前
什么是开源软件(OSS)?
pdf·编辑器·电脑·word·开源软件
遇见小美好y3 天前
自己生成的页面,保存为图片,并下载word
前端·javascript·word