我正在寻找使用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);
}
}
}
现在我想补充一下:
你会有一些关于这方面的指示/例子吗?
谢谢。
答案 0 :(得分:2)
如所示here HWPF是POI的孤儿子项目。没有办法从头开始编写复杂的旧.doc文件。添加图片/页眉/页脚/表格仅由XWPF和.docx格式管理。
所以我选择使用RTF(扩展名为.doc)。以下是构建RTF报告的一些解决方案: