java 一些 HWPF POI 文档构建示例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13455762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Some HWPF POI document building examples
提问by Marc de Verdelhan
I'm looking for examples of building non-trivial Word (97-2003) documents with POI. I already reached to create one with "Hello World":
我正在寻找使用POI构建非平凡 Word (97-2003) 文档的示例。我已经用“Hello World”创建了一个:
package com.mygroup.myapp.poi.word;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import org.apache.log4j.Logger;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.CharacterRun;
import org.apache.poi.hwpf.usermodel.Range;
public class DocFileWriter {
private static final Logger LOGGER = Logger.getLogger(DocFileWriter.class);
private static final String FILE_EXTENSION = ".doc";
private static final URL EMPTY_DOC_URL = DocFileWriter.class.getClassLoader().getResource("empty.doc");
private String pathname;
private HWPFDocument document;
/**
* Constructor
* @param pathname the target path name (e.g.: "/tmp/test.doc", etc.)
* @throws IOException
*/
public DocFileWriter(String pathname) throws IOException {
if (!pathname.endsWith(FILE_EXTENSION)) {
throw new RuntimeException("The file name must ends with " + FILE_EXTENSION);
}
this.pathname = pathname;
try {
document = new HWPFDocument(EMPTY_DOC_URL.openStream());
} catch (IOException e) {
LOGGER.error("Empty document resource missing");
throw e;
}
}
/**
* Adds a "Hello World!" to the document.
*/
public void addHelloWorld() {
Range range = document.getRange();
CharacterRun charRun = range.insertBefore("Hello World!");
charRun.setFontSize(18);
charRun.setItalic(true);
}
/**
* Writes the document on disk.
*/
public void writeDocument() {
try {
document.write(new FileOutputStream(new File(pathname)));
} catch (FileNotFoundException e) {
LOGGER.error("The file cannot be created", e);
} catch (IOException e) {
LOGGER.error("Unable to write the document", e);
}
}
}
Now I'd like to add:
现在我想补充:
- a picture
- a blank page
- a header (only one string)
- a footer (only one string)
- a table (10 rows, 3 columns)
- 照片
- 空白页
- 一个标题(只有一个字符串)
- 页脚(只有一个字符串)
- 一张表(10 行,3 列)
Would you have some pointers/examples about that?
你有关于这个的一些指示/例子吗?
Thank you.
谢谢你。
回答by Marc de Verdelhan
As indicated hereHWPF is an orphan subproject of POI. There's no way to write complex old .doc files from scratch. Adding pictures/headers/footers/tables is only managed by XWPF and .docx format.
正如这里所指出的,HWPF 是 POI 的一个孤儿子项目。没有办法从头开始编写复杂的旧 .doc 文件。添加图片/页眉/页脚/表格仅由 XWPF 和 .docx 格式管理。
So I chose to use RTF (with a .doc extension). Here are some solution to build RTF reports:
所以我选择使用 RTF(带有 .doc 扩展名)。以下是构建 RTF 报告的一些解决方案: