JAVA路上的积累

来源:互联网 发布:域名管理中心 编辑:程序博客网 时间:2024/06/04 18:39

今天在学习利用poi导出Excel.

1.导入jar包。

2.创建workbook工作簿 对应一个Excel

HSSFWorkbook wb = new HSSFWorkbook();

3.创建表空间 Sheet

HSSFSheet sheet = wb.createSheet();

4.创建Row

HSSFRow row =sheet.creatRow(0);

5.创建单元格和单元格格式

HSSFCellStyle style=wb.createCellStyle();

style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//创建居中格式

HSSFCell cell=row.createCell(shor(i));

cell.setCellValue(param);

cell.setCellStyle(style);

FileOutputStream out = new FileOutputStream(path);

wb.write(out);

out.close;

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

public class CreateSimpleExcelToDisk {
 private static List<Student> getStudent() throws Exception{
  List<Student> list = new ArrayList<Student>();
  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;
 }

 /**
  * @param args
  */
 public static void main(String[] args)throws Exception {
  // 第一步,创建一个webbook,对应一个Excel文件 
   HSSFWorkbook wb = new HSSFWorkbook();
  // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet 
   HSSFSheet sheet = wb.createSheet();
  // 第三步,在sheet中添加表头第0行,
   
   HSSFRow row =sheet.createRow(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<list.size();i++){
    row =sheet.createRow(i+1);
    Student stu=(Student) list.get(i);
    row.createCell((short)0).setCellValue(stu.getId());
    row.createCell((short)1).setCellValue(stu.getName());
    row.createCell((short)2).setCellValue(stu.getAge());
    row.createCell((short)3).setCellValue(new SimpleDateFormat("yyyy-mm-dd").format(stu.getBirth()));
   }
   FileOutputStream out = new FileOutputStream("E:/student.xls");
   wb.write(out);
   out.close();
 }

}

---------------------------------------------------------------------------------------------------------------------------------------------

SimpleDateFormat 字符串转日期格式

String str="1949-10-01";

SimpleDateFormat sf = new SimpleDateFormat("yyyy-mm-dd");

Date date =sf.parse(str);

newSimpleDateFormat("yyyy年mm月dd日").format(date);//将日期转为指定的格式















0 0