您的位置:首页 > 运维架构 > Apache

JAVA利用Apache Poi写Excel文件

2016-06-12 08:28 531 查看
接着上次的利用Apache Poi读Excel文件

http://blog.csdn.net/ankh_zxy/article/details/51636589

本次文章参考自

http://www.cnblogs.com/bmbm/archive/2011/12/08/2342261.html

再次直奔主题



修改过的Student类

public class Student {
private String no;
private String name;
private Date startTime;
private long time;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getNo() {
return no;
}

public void setNo(String no) {
this.no = no;
}

public Date getStartTime() {
return startTime;
}

public void setStartTime(Date startTime) {
this.startTime = startTime;
}

public long getTime() {
return time;
}

public void setTime(long time) {
this.time = time;
}

public List<Student> getStudents() {
List<Student> list = new ArrayList<Student>();
for (int i = 0; i < 4; i++) {
Student student = new Student();
student.setNo("3140000" + i);
student.setName("Student" + i);
student.setStartTime(new Date());
student.setTime(900L + i);
list.add(student);
}
return list;
}
}


WriteExcel类

public class WriteExcel {
public void createExcel(List<Student> list) {
//创建一个webbook,对应一个Excel文件
XSSFWorkbook wb = new XSSFWorkbook();
//在webbook中添加一个sheet,对应Excel文件中的sheet
XSSFSheet sheet = wb.createSheet("学生表一");
//在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
XSSFRow row = sheet.createRow(0);
//创建单元格,并设置值表头 设置表头居中
XSSFCellStyle style = wb.createCellStyle();
style.setAlignment(XSSFCellStyle.ALIGN_CENTER);

XSSFCell 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);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (int i = 0; i < list.size(); i++) {
row = sheet.createRow(i + 1);
Student student = list.get(i);
row.createCell(0).setCellValue(student.getNo());
row.createCell(1).setCellValue(student.getName());
row.createCell(2).setCellValue(sdf.format(student.getStartTime()));
String time = String.valueOf((student.getTime() - student.getTime() % 60) / 60 + "m" + student.getTime() % 60 + "s");
row.createCell(3).setCellValue(time);
}
try {
sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String fileName = sdf.format(new Date());
FileOutputStream fos = new FileOutputStream("E:\\test\\" + fileName + ".xls");
wb.write(fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}


Client类进行测试

public class Client {
public static void main(String[] args) throws IOException {
WriteExcel writeExcel = new WriteExcel();
Student student = new Student();
writeExcel.createExcel(student.getStudents());
}
}


再次声明文章参考自:

http://www.cnblogs.com/bmbm/archive/2011/12/08/2342261.html

谢谢。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java