CHƯƠNG III. LẬP TRÌNH JAVA VỚI POI
4. Các kỹ thuật nâng cao
4.2. Đọc và hiển thị 1 file excel bất kỳ
4.2.1. Trường hợp file có chủ ý xác định
Trong lập trình, người ta sẽ thường lưu file và đọc file theo 1 chuẩn cố định dùng để lưu trữ và hiển thị, ta sẽ dùng phương pháp sau:
Nhắc lại, Interface Iterator
Iterator trong Java là một interface được sử dụng để thay thế Enumerations trong Java Collection Framework. Bạn có thể sử dụng interator để:
Duyệt các phần tử từ đầu đến cuối của một collection.
Iterator cho phép xóa phần tử khi lặp một collection.
Các phương thức của Iterator trong Java Có ba phương thức trong Iterator như sau:
Phương thức Mô tả
public boolean hasNext() Nó trả về true nếu iterator còn phần tử kế tiếp phần tử đang duyệt.
public object next() Nó trả về phần tử hiện tại và di chuyển con trỏ trỏ tới phần tử tiếp theo.
public void remove() Nó loại bỏ phần tử cuối được trả về bởi Iterator. Nó hiếm khi được sử dụng.
Code:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class huy { // Khai báo hằng
public static final String FILEPATH = "student.xlsx"; public static final byte COLUMN_INDEX_studentID = 0;
public static final byte COLUMN_INDEX_firstName = 1;
public static final byte COLUMN_INDEX_lastName = 2;
public static final byte COLUMN_INDEX_age = 3;
public static final byte COLUMN_INDEX_mathPoints = 4;
public static final byte COLUMN_INDEX_physicsPoints = 5;
public static final byte COLUMN_INDEX_chemistryPoints = 6;
/**
* Hàm in tiêu đề ra Console * @param firstRow
*/
public static void printHeader(Row firstRow) { String[] s=
{firstRow.getCell(COLUMN_INDEX_studentID).getStringCellVa lue(),
firstRow.getCell(COLUMN_INDEX_firstName).getStringCellValue(),
firstRow.getCell(COLUMN_INDEX_lastName).getStringCellValue(), firstRow.getCell(COLUMN_INDEX_age).getStringCellValue(),
firstRow.getCell(COLUMN_INDEX_mathPoints).getStringCellValue() ,
firstRow.getCell(COLUMN_INDEX_physicsPoints).getStringCellValu e(),
firstRow.getCell(COLUMN_INDEX_chemistryPoints).getStringCellVa lue()};
for(int i=0;i<s.length;i++) { System.out.print(s[i]+" ");
}
System.out.println();
}
/**
* Hàm in danh sách student * @param list
*/
public static void printListStudent(List<Student> list) { for(Student student:list) {
System.out.println(student);
} } /**
* Gán giá trị từ Excel tương ứng vào List<Student>
* @param currentRow * @param list * @param fmt * @return */
public static List<Student> listOfStudent(Row currentRow,List<Student> list, DataFormatter fmt) {
Student student = new Student();
student.setStudentId(currentRow.getCell(COLUMN_INDEX_stud entID).getStringCellValue());
student.setFirstName(currentRow.getCell(COLUMN_INDEX_firs tName).getStringCellValue());
student.setLastName(currentRow.getCell(COLUMN_INDEX_lastN ame).getStringCellValue());
student.setAge(Byte.parseByte(fmt.formatCellValue(current Row.getCell(COLUMN_INDEX_age))));
student.setMathPoints(Float.parseFloat(fmt.formatCellValu e(currentRow.getCell(COLUMN_INDEX_mathPoints))));
student.setPhysicsPoints(Float.parseFloat(fmt.formatCellV alue(currentRow.getCell(COLUMN_INDEX_physicsPoints))));
student.setChemistryPoints(Float.parseFloat(fmt.formatCel lValue(currentRow.getCell(COLUMN_INDEX_chemistryPoints))) );
list.add(student);
return list;
}
/**
* Hàm luồng đầu vào *
* @param filepath * @throws IOException */
public static FileInputStream inputExcel(String filepath) throws IOException {
FileInputStream fis = new FileInputStream(new File(filepath));
return fis;
}
* Hàm đọc dữ liệu từ Excel nhưng lưu vào List<Student>
* @param student * @param filepath * @throws IOException */
public static void readExcel2(List<Student>
student,String filepath) throws IOException { // Đôdi tượng workbook cho file XSLX.
XSSFWorkbook workbook = new XSSFWorkbook(inputExcel(filepath));
// Lẫdy ra sheet đẫPu tiên từ workbook XSSFSheet Sheet = workbook.getSheetAt(0);
//Tạo DataFormatter đê> định dạng và nhận giá trị cu>a mô.i ô dưới dạng Chuô.i
DataFormatter fmt = new DataFormatter();
// Lẫdy ra Iterator cho tẫdt ca> các dòng cu>a sheet hiện tại.
Iterator<Row> iterator = Sheet.iterator();
// Nó tra> vêP phẫPn tư> hiện tại và di chuyê>n con tro> tro>
tới phẫPn tư> tiêdp theo.
Row firstRow = iterator.next();
printHeader(firstRow);
while (iterator.hasNext())//Nó tra> vêP true nêdu iterator còn phẫPn tư> kêd tiêdp phẫPn tư> đang duyệt..
{
Row currentRow = iterator.next();
listOfStudent(currentRow, student, fmt);
}
printListStudent(student);
workbook.close();
}
public static void main(String[] args) { //Tạo một danh sách Học sinh mới
List<Student> listOfStudent = new ArrayList<Student>();
try {
readExcel2(listOfStudent, FILEPATH);
} catch (IOException e) {
System.out.println("Không đọc được dữ liệu");
} }
}
Kết quả chạy :
Màn hình Console