POI使用模板文件创建目录

1、创建模板文件
  • 创建模板文件如format.docx,创建几个标题,并插入目录
    在这里插入图片描述
  • 将标题删除,只留目录
    在这里插入图片描述
2、复制模板文件
	private File copyFile(String tempPath, String targetPath) throws Exception {
		File temp= new File(tempPath);
		File target= new File(targetPath);
		FileInputStream in = null;
		FileOutputStream out = null;
		try {
			in = new FileInputStream(temp);
			out = new FileOutputStream(target);
			byte[] buffer = new byte[1024];
			while (in.read(buffer) != -1) {
				out.write(buffer);
			}
			out.flush();
			return target;
		} finally {
			in.close();
			out.close();
		}
	}
3、打开word
/**
	 * 打开Word
	 * 
	 * @param filePath 文件全路径
	 */
	public static XWPFDocument open(String filePath) throws Exception {
		InputStream is = null;
		try {
			is = new FileInputStream(filePath);
			return new XWPFDocument(is);
		} finally {
			is.close();
		}
	}
4、添加文档内容
public void setContent(XWPFDocument doc){
	// 标题1,1级大纲
	XWPFParagraph para1 = doc.createParagraph();
	// 关键行// 1级大纲
	para1.setStyle("1");
	XWPFRun run1 = para1.createRun();
	// 标题内容
	run1.setText("标题1");
	
	// 标题2,2级大纲
	XWPFParagraph para2 = doc.createParagraph();
	// 关键行// 2级大纲
	para2.setStyle("2");
	XWPFRun run2 = para2.createRun();
	// 标题内容
	run2.setText("标题2");
	
	// 正文
	XWPFParagraph paraX = doc.createParagraph();
	XWPFRun runX = paraX.createRun();
	for(int i=0;i<100;i++) {
		// 正文内容
		runX.setText("正文\r\n");
	}
}
5、更新目录
public static void main(String[] args) {
	String tempPath = "D:\\test\\poi\\word\\format.docx"; //模板文件路径
	String targetPath = "D:\\test\\poi\\word\\test.docx";//生成文件路径
	//复制模板
	File file = copyFile(tempPath ,targetPath);
	//打开word
	XWPFDocument doc = open(targetPath);
	//添加内容
	setContent(doc);
	//更新目录
	doc.enforceUpdateFields();
	//word写入到文件
	FileOutputStream fos;
	try {
		fos = new FileOutputStream(targetPath);
		doc.write(fos);
		fos.close();
	} catch (Exception e) {
		e.printStackTrace();
	}
}
6、结果展示

在这里插入图片描述
选择是
在这里插入图片描述

评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值