public class JunitTest {
@Test
public void dataToExcel() throws ParseException{
List<Student> list =this.getData();
//创建一个HSSFWorkbook对象
HSSFWorkbook wb = new HSSFWorkbook();
//创建一个名称为“Student_grade”的SHEET
HSSFSheet sheet = wb.createSheet("Student_grade");
//创建一个居中的显示样式
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//创建第一列(标题)并在该列创建单元格
HSSFRow row =sheet.createRow(0);
HSSFCell cell= row. createCell(0);
//单元格填充内容
cell.setCellValue("编号");
//单元格设置居中样式
cell.setCellStyle(style);
cell= row. createCell(1);
cell.setCellValue("姓名");
cell.setCellStyle(style);
cell= row. createCell(2);
cell.setCellValue("学号");
cell.setCellStyle(style);
cell= row. createCell(3);
cell.setCellValue("性别");
cell.setCellStyle(style);
cell= row. createCell(4);
cell.setCellValue("出生日期");
cell.setCellStyle(style);
cell= row. createCell(1);
int index=1;
for(Student stu :list){
row = sheet.createRow(index++);
row.createCell(0).setCellValue(stu.getId());
row.createCell(1).setCellValue(stu.getStudentName());
row.createCell(2).setCellValue(stu.getStudentNo());
row.createCell(3).setCellValue(stu.getGender());
row.createCell(4).setCellValue(stu.getBirthday());
}
//将创建好的表格写出去
try {
FileOutputStream out = new FileOutputStream("D:/aa.xls");
wb.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//数据准备
public List<Student> getData() throws ParseException{
/*ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext*.xml");
IZoneJobTasksService zone=(IZoneJobTasksService) ctx.getBean("zoneJobTasksService");
*/
List<Student> list = new ArrayList<Student>();
SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd");
Student stu1= new Student("0001", "Jim", "20110705001", "Boy", df.parse("1989-03-26"));
Student stu2= new Student("0002", "ploy", "20110705002", "Girl", df.parse("1989-03-26"));
Student stu3= new Student("0003", "Tom", "20110705003", "Boy", df.parse("1989-03-26"));
Student stu4= new Student("0004", "Hans", "20110705004", "Girl", df.parse("1989-03-26"));
Student stu5= new Student("0005", "Jones", "20110705005", "Girl", df.parse("1989-03-26"));
list.add(stu1);
list.add(stu2);
list.add(stu3);
list.add(stu4);
list.add(stu5);
return list;
}
}