公司有个项目, 要用java生成word文档, 在网上找来找去也没有找到好的生成word文档的库, 找到apache的POI可以使用, 但是所有的release版中也没有支持word的class. 只能从svn上下载源代码编译.
后来发现java支持rtf格式的文档, word也支持, 于是乎便使用此产生word文档了. 呵呵..
java支持的rtf文档功能不是很强大, 我们可以借助于一些开源的库, 比如: itext就可以很好的支持. itext上有很多例子, 有兴趣的可以上去看一下, 这里就不摘录了.
但是itext比较大要1.4M, 不是很喜欢. 在sf上找来找去, 发现一个更小的库, 尽管功能不是很强大, 基本的功能都有, 他就是srw(Simple RTF Writer目前它的版本是0.6,好久都没有人维护了).
srw内置了很多例子, 例如: 我们要写一个简单的rtf, 我们只需要这么写:
public class TestSimpleRtf {
private static final String FILE_NAME = "out_testsimplertf.rtf";
public static void main(String[] args) {
try {
// RTF Dokument generieren (in Querformat)
RTFDocument doc = new RTFDocument(PageSize.DIN_A4_QUER);
// Anzeige-Zoom und Ansicht definieren
doc.setViewscale(RTFDocument.VIEWSCALE_FULLPAGE); // Anzeige-Zoom auf "komplette Seite" einstellen
doc.setViewkind(RTFDocument.VIEWKIND_PAGELAYOUT); // ViewMode auf Seitenlayout stellen
Paragraph absatz = new Paragraph(18, 0, 16, Font.ARIAL, new TextPart("Simple RTF Writer Testdokument"));
absatz.setAlignment(Paragraph.ALIGN_CENTER);
doc.addParagraph(absatz);
File savefile = new File(FILE_NAME);
doc.save(savefile);
System.out.println("Neues RTF Dokument erstellt: " + savefile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
}
}
用法很简单, 但是功能很少, 比如没有table的功能, 不能设置打印方向等问题. 不过这个基本上就够用了.
后来, 我们的项目要求横向打印, 这可难坏了. 没办法, 自己查找word的rtf格式库, 拓展横向打印功能, 目前已经完成...
import com.itseasy.rtf.RTFDocument;
import com.itseasy.rtf.text.PageSize;
public class MyRTFDocument extends RTFDocument {
public static final int ORIENTATION_PORTRAIT = 0;
public static final int ORIENTATION_LANDSCAPE = 1;
private int orientation;
/**
*
*/
public MyRTFDocument() {
super();
}
/**
* @param arg0
*/
public MyRTFDocument(PageSize arg0) {
super(arg0);
}
/* (non-Javadoc)
* @see com.itseasy.rtf.RTFDocument#getDocumentAsString()
*/
protected String getDocumentAsString() {
StringBuffer sb = new StringBuffer(super.getDocumentAsString());
int pos = -1;
if (ORIENTATION_LANDSCAPE == orientation) {
pos = sb.indexOf("paperw");
if (pos > 0) {
sb.insert(pos, "lndscpsxn");
}
}
pos = 0;
while((pos = sb.indexOf("pardplain", pos)) > 0){
pos = sb.indexOf("{", pos);
sb.insert(pos, "dbchaf2");
}
return sb.toString();
}
/**
* @return Returns the orientation.
*/
public int getOrientation() {
return orientation;
}
/**
* @param orientation The orientation to set.
*/
public void setOrientation(int orientation) {
this.orientation = orientation;
}
}
java2word 是一个在java程序中调用 MS Office Word 文档的组件(类库)。该组件提供了一组简单的接口,以便java程序调用他的服务操作Word 文档。
这些服务包括:
打开文档、新建文档、查找文字、替换文字,
插入文字、插入图片、插入表格,
在书签处插入文字、插入图片、插入表格等。
填充数据到表格中读取表格数据
1.1版增强的功能:
@指定文本样式,指定表格样式。如此,则可动态排版word文档。
@填充表格数据时,可指定从哪行哪列开始填充。配合输入数据的大小,你可以修改表中的任意部分,甚至只修改一个单元格的内容。
@合并单元格。