CHƯƠNG III. LẬP TRÌNH JAVA VỚI POI
4. Các kỹ thuật nâng cao
4.1. Tạo và ghi một list đối tượng
Trong thực tế, ta không thể ghi một file excel một cách bừa bài mà chúng ta cần phải ghi một cách tuần tự, các bước rõ ràng. Sau đây là một ví dụ:
Tạo một class Student
public class Student {
private String studentId; private String firstName; private String lastName; private byte age;
private float mathPoints; private float physicsPoints; private float chemistryPoints; // Constructor
public Student() { }
public Student(String studentId, String firstName, String lastName, byte age, float mathPoints, float physicsPoints,
float chemistryPoints) { this.studentId = studentId; this.firstName = firstName; this.lastName = lastName; this.age = age;
this.mathPoints = mathPoints; this.physicsPoints = physicsPoints; this.chemistryPoints = chemistryPoints; }
// Getter methods
public String getStudentId() { return studentId;
}
public String getFirstName() { return firstName;
}
public String getLastName() { return lastName;
}
public byte getAge() { return age; }
public float getMathPoints() { return mathPoints; }
public float getPhysicsPoints() { return physicsPoints; }
public float getChemistryPoints() { return chemistryPoints; }
// Setter methods
public void setStudentId(String studentId) { this.studentId = studentId;
}
public void setFirstName(String firstName) { this.firstName = firstName;
}
public void setLastName(String lastName) { this.lastName = lastName;
}
public void setAge(byte age) { this.age = age;
}
public void setMathPoints(float mathPoints) { this.mathPoints = mathPoints;
}
public void setPhysicsPoints(float physicsPoints) { this.physicsPoints = physicsPoints;
}
public void setChemistryPoints(float chemistryPoints) { this.chemistryPoints = chemistryPoints;
}
// Other methods
@Override
public String toString() {
return "Student [studentId=" + studentId + ", firstName=" + firstName + ", lastName=" + lastName + ", age="
+ age + ", mathPoints=" + mathPoints + ", physicsPoints=" + physicsPoints + ", chemistryPoints="
+ chemistryPoints + "]"; }
}
Ghi danh sách vừa tạo vào Excel CODE:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
/**
* Hàm sinh ngẫ.u nhiên một List students *
* @param size * @return */
public static List<Student> generateArrayStudent(int size) { // Tạo danh sách id học sinh, tên, tên đệm, điê>m các môn String[] studentId = { "a", "ba", "c1", "a2", "e", "h",
"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "A",
"a3", "c4", "abc12", "abc11", "abc13", "abc14",
"11" };
String[] firstName = { "Anh", "Chi", " Hùng", "Linh",
"Huy", "Hòa", "Trang", "HuyêPn", "Thúy", "Trang", "Hưng",
"Hùng", "Tài", "Toàn", "Bình", "Long", "Vũ" };
String[] lastName = { "Nguyê.n", "Nguyê.n Văn", "Doãn",
"Doãn Chí", "Phạm", "TrẫPn", "Phạm", "Phạm Thị",
"Phạm Văn" };
// Danh sách trung gian
List<Student> list = new ArrayList<Student>();
// Sinh ngẫ.u nhiên
for (int = 0; < i i size; ++) {i // khở>i tạo cho từng học sinh
list.add(new Student(studentId[(int) (Math.random()
* studentId.length)],
lastName[(int) (Math.random() * lastName.length)],
firstName[(int) (Math.random() * firstName.length)], (byte) (Math.random() * 5 + 18),
(float) (Math.random() * 10), (float) (Math.random() * 10), (float) (Math.random() * 10)));
}
return list; /**}
* Hàm ghi Excel * @param student * @param filePath * @throws IOException */
public static void writeExcels(List<Student> student, String filePath) throws IOException {
//Tạo Workbook định dạng xlsx
XSSFWorkbook workbook = new XSSFWorkbook();
// Tạo trang tính từ Workbook vừa tạo
XSSFSheet sheet0 = workbook.createSheet("Student INFO");
byte rowIndex = 0;
//Ghi tiêu đêP vào Excel
writeHeader(sheet0, rowIndex++);
// Ghi danh sách Student vào Excel
writeStudent(sheet0, rowIndex++, student);
outputExcel(workbook, filePath);
workbook.close();
} /**
* In ra console *
* @param student */
public static void printList(List<Student> student) { System.out.println("Danh sách Student đê> ghi vào file excel: ");
for (Student index : student) {
System.out.println(index.toString());
} }
/**
* Hàm ghi tiêu đêP vào Excel *
* @param sheet * @param rowIndex */
public static void writeHeader(XSSFSheet sheet, byte rowIndex) {
// tạo row tại vị trí index
Row row = sheet.createRow(rowIndex);
// tạo cell
Cell cell = row.createCell(COLUMN_INDEX_studentID);
cell.setCellValue("ID");
cell = row.createCell(COLUMN_INDEX_firstName);
cell.setCellValue("First name");
cell = row.createCell(COLUMN_INDEX_lastName);
cell.setCellValue("Last name");
cell = row.createCell(COLUMN_INDEX_age);
cell.setCellValue("Age");
cell = row.createCell(COLUMN_INDEX_mathPoints);
cell.setCellValue("Math Points");
cell = row.createCell(COLUMN_INDEX_physicsPoints);
cell.setCellValue("Physic Points");
cell = row.createCell(COLUMN_INDEX_chemistryPoints);
cell.setCellValue("Chemistry Points");
}
/**
* Hàm ghi dữ liệu vào Excel *
* @param sheet * @param rowNum * @param list */
public static void writeStudent(XSSFSheet sheet, int rowNum, List<Student> list) {
for (Student students : list) {
Row row = sheet.createRow(rowNum++);
Cell cell = row.createCell(COLUMN_INDEX_studentID);
cell.setCellValue(students.getStudentId());
cell = row.createCell(COLUMN_INDEX_firstName);
cell.setCellValue(students.getFirstName());
cell = row.createCell(COLUMN_INDEX_lastName);
cell.setCellValue(students.getLastName());
cell = row.createCell(COLUMN_INDEX_age);
cell.setCellValue(students.getAge());
cell = row.createCell(COLUMN_INDEX_mathPoints);
cell.setCellValue(students.getMathPoints());
cell = row.createCell(COLUMN_INDEX_physicsPoints);
cell.setCellValue(students.getPhysicsPoints());
cell = row.createCell(COLUMN_INDEX_chemistryPoints);
cell.setCellValue(students.getChemistryPoints());
} } /**
* Hàm luôPng xuẫdt *
* @param workbook * @param filePath * @throws IOException */
public static void outputExcel(XSSFWorkbook workbook, String filePath) throws IOException {
FileOutputStream fos = new FileOutputStream(new File(filePath));
workbook.write(fos);
}
public static void main(String[] args) { //Sinh ngẫ.u nhiên Danh sách 50Student
List<Student> student = generateArrayStudent(50);
//In danh sách 50 Student ra console printList(student);
//Ghi Excel try {
writeExcels(student, FILEPATH);
System.out.println("Ghi thành công !");
} catch (IOException ) {e
System.out.println("Ghi không thành công !");
} }
}
Kết quả chạy :
Màn hình console
Dữ liệu sau khi ghi vào file Excel: