本文介绍了使用 Apache-POI 自动格式化 Word的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 XWPFDocument 中使用带有 Apache-POI 的 word 自动格式化功能.

I'd like to use the autoformat feature of word with Apache-POI in an XWPFDocument.

我的意思是,如果您键入例如自动格式化---"并按回车,在word文档的页面上画一条水平线.

By autoformat I mean, if you type e.g. "---" and press return, a horizontal line is drawn across the page of the word document.

我想在标题中使用它.

我试过了

XWPFHeader header = doc.createHeader(HeaderFooterType.FIRST);
paragraph = header.createParagraph();
paragraph.setAlignment(ParagraphAlignment.LEFT);
run = paragraph.createRun();
run.setText("---\r");

run.setText("---\r\n");

run.setText("---");
run.addCarriageReturn();

这些都不起作用.

是否可以将自动格式化功能与 POI 一起使用?

Is it even possible to use the autoformat function with POI?

问候,迈克

我正在使用 POI 4.0.0,顺便说一句...

I'm using POI 4.0.0, btw...

推荐答案

Autoformat 是 Word 的 GUI 的一项功能.但是 apache poi 正在创建存储在 *.docx 文件中的内容.自动套用格式将---" 替换为段落的底部边框线后,文件中仅存储该段落的底部边框线.

The Autoformat is a feature of Word's GUI. But apache poi is creating what is stored in a *.docx file. After the Autoformat has replaced "---" with a bottom border line of the paragraph, only this bottom border line of the paragraph is stored in the file.

所以:

import java.io.*;

import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.wp.usermodel.HeaderFooterType;

public class CreateWordHeader {

 public static void main(String[] args) throws Exception {

  XWPFDocument doc = new XWPFDocument();

  // the body content
  XWPFParagraph paragraph = doc.createParagraph();
  XWPFRun run = paragraph.createRun();
  run.setText("The Body...");

  // create header
  XWPFHeader header = doc.createHeader(HeaderFooterType.FIRST);
  paragraph = header.createParagraph();
  paragraph.setAlignment(ParagraphAlignment.LEFT);
  run = paragraph.createRun();
  run.setText("First Line in Header...");

  // bottom border line of the paragraph = what Autoformat creates after "---"[Enter]
  paragraph.setBorderBottom(Borders.SINGLE);

  paragraph = header.createParagraph();
  paragraph.setAlignment(ParagraphAlignment.LEFT);
  run = paragraph.createRun();
  run.setText("Next Line in Header...");

  FileOutputStream out = new FileOutputStream("CreateWordHeader.docx");
  doc.write(out);
  doc.close();
  out.close();


 }
}

这篇关于使用 Apache-POI 自动格式化 Word的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 12:12