通过poi(3.8)写xls文件,需求如下:生成学生信息统计表
学生类:
class Student {
private String name;
private String gender;
private int age;
private String sclass;
private int score;
public Student() {
super();
}
public Student(String name, String gender, int age, String sclass, int score) {
super();
this.name = name;
this.gender = gender;
this.age = age;
this.sclass = sclass;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSclass() {
return sclass;
}
public void setSclass(String sclass) {
this.sclass = sclass;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public String toString() {
return "Student [age=" + age + ", gender=" + gender + ", name=" + name + ", sclass="
+ sclass + ", score=" + score + "]";
}
}
数据准备:
private static List<Student> studentList = null;
static {
studentList = new ArrayList<Student>();
studentList.add(new Student("张三", "男", 23, "一班", 94));
studentList.add(new Student("王五", "男", 21, "一班", 87));
studentList.add(new Student("李四", "女", 20, "一班", 92));
studentList.add(new Student("赵六", "女", 22, "一班", 83));
}
具体操作:
public static void generateExcel(String filePath) {
// 先创建工作簿对象
HSSFWorkbook workbook2003 = new HSSFWorkbook();
// 创建工作表对象并命名
HSSFSheet sheet = workbook2003.createSheet("学生信息统计表");
// 遍历集合对象创建行和单元格
for (int i = 0; i < studentList.size(); i++) {
// 取出Student对象
Student student = studentList.get(i);
// 创建行
HSSFRow row = sheet.createRow(i);
// 开始创建单元格并赋值
HSSFCell nameCell = row.createCell(0);
nameCell.setCellValue(student.getName());
HSSFCell genderCell = row.createCell(1);
genderCell.setCellValue(student.getGender());
HSSFCell ageCell = row.createCell(2);
ageCell.setCellValue(student.getAge());
HSSFCell sclassCell = row.createCell(3);
sclassCell.setCellValue(student.getSclass());
HSSFCell scoreCell = row.createCell(4);
scoreCell.setCellValue(student.getScore());
}
// 生成文件
File file = new File(filePath);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
workbook2003.write(fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
main调用:
public static void main(String[] args) {
generateExcel("student.xls");
}