今天尝试使用itext导出数据库中所有表的列信息,效果还可以。
首先需要引入两个jar包
iText-2.1.7.jar
itext-rtf-2.1.7.jar
下面是导出方法,一个很小的例子,只用到了表格
/**
*
* @param fname 文件名
* @param tl 数据
* @throws Exception
*/
public static void exportToWord(String fname,List<TableInfo> tl) throws Exception
{
Document doc = new Document(PageSize.A4);//新建一个Document对象,并设置大小
RtfWriter2.getInstance(doc, new FileOutputStream("f://"+fname+".doc")); //创建一个Writer,将doc对象与流关联起来
doc.open();
RtfFont contextFont = new RtfFont("仿宋_GB2312", 9, Font.NORMAL, Color.BLACK); //设置字体
RtfFont titleFont = new RtfFont("仿宋_GB2312", 12, Font.BOLD, Color.BLACK); //设置字体
Cell[] cellHeaders = new Cell[6];//用作标题的单元格数组
cellHeaders[0]=new Cell(new Phrase("序号", contextFont));
cellHeaders[1]=new Cell(new Phrase("列名", contextFont));
cellHeaders[2]=new Cell(new Phrase("类型", contextFont));
cellHeaders[3]=new Cell(new Phrase("长度", contextFont));
cellHeaders[4]=new Cell(new Phrase("是否可为空", contextFont));
cellHeaders[5]=new Cell(new Phrase("描述", contextFont));
for (TableInfo t : tl) {
Paragraph title = new Paragraph(t.getTname());
title.setAlignment(Element.ALIGN_CENTER);
title.setFont(titleFont);
doc.add(title);
Table table=new Table(6, t.getColumns().size()+1);//创建表(宽,高)
table.setAlignment(Element.ALIGN_CENTER);//设置居中
for(int i=0;i<6;i++)
{
table.addCell(cellHeaders[i]);//添加表头
}
List<ColumnInfo> cl=t.getColumns();
for (int i=0;i<cl.size();i++) {
//遍历数据,向表格中添加单元格
table.addCell(new Cell(new Phrase(String.valueOf(i+1),contextFont)));
table.addCell(new Cell(new Phrase(cl.get(i).getColumnName(),contextFont)));
table.addCell(new Cell(new Phrase(cl.get(i).getType(),contextFont)));
table.addCell(new Cell(new Phrase(String.valueOf(cl.get(i).getLength()),contextFont)));
table.addCell(new Cell(new Phrase(cl.get(i).getNullable(),contextFont)));
table.addCell(new Cell());
}
doc.add(table);
doc.add(new Paragraph());
}
doc.close();
System.out.println("导出成功");
}