java生成pdf和excel的方法(四)

2014-11-24 10:51:03 · 作者: · 浏览: 2
ont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font FontChinese = new Font(bfChinese, 12, Font.NORMAL);
在上面的代码中设置了中文字体的显示,你只要使用下面的代码就可以包中文加到PDF中了
String title = "我爱喝咖啡";
Paragraph t = new Paragraph(title, FontChinese);
doc.add(t);
如果你觉得这样设置很麻烦的话,呵呵,那你要自己扩展它的源代码了,设置字体全部在那个BaseFont里边。
编辑表格
iText中的表格很像HTML中表格的使用不过它有一个cell代表一个格子,基本上这里的Table和Swing中的Table对象是一致的,比如上面代码中对于表格的设置:
//定义一个表格
Table table = new Table(2);
//设置表格边框
table.setBorderWidth(1);
Cell cell = new Cell("Matrix III");
cell.setHeader(true);
//分列
cell.setColspan(2);
cell.setBackgroundColor(Color.blue);
table.addCell(cell);
放置图片
现在你一定知道如何把一个图片加到文档中了,没错只要声明一个Image对象就可以了,这里的Image和AWT中的Image使用方法是一样的。
//定义一个图片
Image jpeg = Image.getInstance("C:/matrix.jpg");
//图片居中
jpeg.setAlignment(Image.ALIGN_CENTER);
结束
有关iText的使用我就大致介绍这些,更深入的东西只有大家参考源代码自己体会了。
2.java生成excel:
简单小程序,具体的找个老的项目研究一下。
public class CreateSimpleExcelToDisk {
/**
* @作者:heasen
* @日期:2010-3-24
* @功能:手工构建一个简单格式的Excel
*/
private static List getStudent() throws Exception{
List list = new ArrayList();
SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd");
Student user1 = new Student(1,"张三",16,df.parse("1997-03-12"));
Student user2 = new Student(2,"李四",17,df.parse("1996-08-12"));
Student user3 = new Student(3,"王五",26,df.parse("1985-11-12"));
list.add(user1);
list.add(user2);
list.add(user3);
return list;
}
public static void main(String[] args) throws Exception {
//第一步,创建一个webbook,对应一个Excel文件
HSSFWorkbook wb = new HSSFWorkbook();
//第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet sheet = wb.createSheet("学生表一");
//第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
HSSFRow row = sheet.createRow((int)0);
//第四步,创建单元格,并设置值表头 设置表头居中
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); //创建一个居中格式
HSSFCell cell = row.createCell((short)0);
cell.setCellValue("学号"); cell.setCellStyle(style);
cell = row.createCell((short)1);
cell.setCellValue("姓名"); cell.setCellStyle(style);
cell = row.createCell((short)2);
cell.setCellValue("年龄"); cell.setCellStyle(style);
cell = row.createCell((short)3);
cell.setCellValue("生日"); cell.setCellStyle(style);
//第五步,写入实体数据 实际应用中这些数据从 数据库得到,
List list = CreateSimpleExcelToDisk.getStudent();
for(int i=0;i
row = sheet.createRow((int)i+1);
Student stu = (Student) list.get(i);
//第四步,创建单元格,并设置值
row.createCell((short)0).setCellValue((double)stu.getId());
row.createCell((short)1).setCellValue(stu.getNam