81,092
社区成员
发帖
与我相关
我的任务
分享
import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.rtf.RtfWriter2;
import java.awt.Color;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Iterator;
import java.util.List;
import javax.swing.JOptionPane;
public class RTFCreate {
public RTFCreate() {
}
public static void main(String[] args) { //main函数
RTFCreate rtfCreate = new RTFCreate();
try {
rtfCreate.createRTF();
JOptionPane.showMessageDialog(null, "表格已经成功创建");
} catch (MalformedURLException ex) {
JOptionPane.showMessageDialog(null, "表格导出出错,错误信息:" + ex
+ "\n错误原因可能是表格已经打开!");
ex.printStackTrace();
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(null, "表格导出出错,错误信息:" + ex
+ "\n错误原因可能是表格已经打开!");
ex.printStackTrace();
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "表格导出出错,错误信息:" + ex
+ "\n错误原因可能是表格已经打开!");
ex.printStackTrace();
} catch (DocumentException ex) {
JOptionPane.showMessageDialog(null, "表格导出出错,错误信息:" + ex
+ "\n错误原因可能是表格已经打开!");
ex.printStackTrace();
}
}
/**
* 生成word的方法
*/
public void createRTF() throws FileNotFoundException, DocumentException,
MalformedURLException, IOException {
// 创建word文档
Document document = new Document(PageSize.A4);
// 输入word文档
RtfWriter2.getInstance(document, new FileOutputStream("d:\\word.doc"));
document.open();
// 中文字体
BaseFont bfChinese = BaseFont.createFont("STSongStd-Light",
"UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font fontChinese = new Font(bfChinese, 12, Font.HELVETICA);
// 创建有3列的表格
Table table = new Table(3);
document.add(new Paragraph("生成rft文档!", fontChinese));
table.setBorderWidth(0);
table.setBorderColor(new Color(0, 0, 255));
table.setPadding(5);
table.setSpacing(0);
// 添加表头元素
Cell cell = new Cell("header");
cell.setHeader(true);
cell.setColspan(3);
table.addCell(cell);
table.endHeaders();// 表头结束
// 表格主体
cell = new Cell("Example cell with colspan 1 and rowspan 2");
cell.setRowspan(2);
// cell.setBorderColor(new Color(255, 0, 0));
table.addCell(cell);
table.addCell("1.1");
table.addCell("2.1");
table.addCell("1.2");
table.addCell("2.2");
table.addCell(new Paragraph("测试1", fontChinese));
table.addCell("big cell");
cell.setRowspan(2);
cell.setColspan(2);
table.addCell(cell);
table.addCell(new Paragraph("测试2", fontChinese));
Cell cell1 = new Cell("aaa");
cell1.setColspan(2);
Cell cell2 = new Cell("bbb");
cell2.setColspan(1);
table.addCell(cell1);
table.addCell(cell2);
document.add(table);
// 在表格末尾添加图片
// Image png = Image.getInstance("d:\\duck.jpg");
// document.add(png);
document.close();
}
}