Một số phương thức của các class XSSFWorkbook, XSSFSheet, Row, Cell 12 -1.1.. - Apache POI cũng cung cấp SXSSF API là một phần mở rộng của XSSF để làm việc với các trang tính excel rất
GIỚI THIỆU VỀ APACHE POI
APACHE POI là gì ?
Apache POI là một thư viện mã nguồn mở của Java, cho phép tạo và thao tác các định dạng tệp khác nhau dựa trên Microsoft Office Với Apache POI, người dùng có thể thực hiện các thao tác tạo, sửa đổi và hiển thị/đọc trên các định dạng tệp văn bản của Microsoft, giúp khắc phục hạn chế của Java khi không cung cấp hỗ trợ tích hợp cho các tệp văn bản này Thư viện này cung cấp Java API để thao tác với các định dạng tệp khác nhau dựa trên tiêu chuẩn Office Open XML (OOXML) và tiêu chuẩn OLE2 của Microsoft, và được phát hành theo Giấy phép Apache (V2.0).
Một số tính năng quan trọng
- APACHE POI cung câp xử lý dựa trên luồng phù hợp với các tệp lớp và yêu cầu ít bộ nhớ hơn.
- APACHE có khả năng xử lý cả hai định dạng XLSX, XLS.
- Apache POI chứa triển khai HSSF cho định dạng tệp Excel ’97 (-
- Apache POI HSSF và XSSF API cung cấp các cơ chế để đọc, ghi hoặc sửa đổi bảng tính excel.
- Apache POI cũng cung cấp SXSSF API là một phần mở rộng của XSSF để làm việc với các trang tính excel rất lớn.
- SXSSF API yêu cầu ít bộ nhớ hơn và phù hợp khi làm việc với các bảng tính rất lớn và bộ nhớ heap bị hạn chế.
- Có hai mô hình để lựa chọn - mô hình sự kiện và mô hình người dùng Mô hình sự kiện yêu cầu ít bộ nhớ hơn vì tệp excel được đọc bằng mã thông báo và yêu cầu xử lý chúng Mô hình người dùng hướng đối tượng hơn và dễ sử dụng.
Apache POI cung cấp hỗ trợ tuyệt vời cho các tính năng bổ sung của Excel, bao gồm làm việc với công thức, tạo kiểu ô bằng cách tô màu và đường viền, cũng như tùy chỉnh phông chữ Ngoài ra, thư viện này còn hỗ trợ thêm các tính năng như đầu trang và chân trang, xác thực dữ liệu, hình ảnh và siêu liên kết, giúp người dùng có thể tạo ra các tài liệu Excel chuyên nghiệp và đa dạng.
Các thành phần sử dụng trong APACHE POI
- HSSF (Horrible Spreadsheet Format): dùng để đọc hoặc ghi các trang tính theo các định dạng XLS.
- XSSF (XML Spread Sheet Format): dùng để đọc hoặc ghi các trang tính theo các định dạng XLSX.
POIFS (Poor Obfuscation Implementation File System) is the fundamental component of all other POI components, serving as a crucial element for reading various files in a clear manner.
- HWPF (Horrible Word Processor Format): dùng để đọc hoặc ghi các trang Word theo định dạng doc, docx.
- HSLF (Horrible Slide Layout Format): dùng để đọc hoặc ghi các trang Presentation theo định dạng ppt, pttx.
Cài đặt môi trường
Nếu đang làm việc trên một Project Maven thì phải thêm POI dependency vào file pom.xml đoạn code sau:
org.apache.poi
Để thêm vào Eclipse: đi theo Window -> Show view -> Other -> Maven -> Maven Repositories.
Nếu Không dùng Maven thì vào trang chủ POI để tải xuống Sau đó thêm external JAR file cho Project đó.
Hướng dẫn cài đặt APACHE POI cho Eclipse bằng cách thêm thư viện ngoài:
B2: Sau khi tạo, mở Property của project, chọn phần Library
B4: Browse và add tất cả thư viện APACHE POI vào Classpath, bấm Apply.
Như vậy là quá trình cài đặt môi trường đã hoàn thành
SỬ DỤNG POI TRONG JAVA
Nhắc lại một số khái niệm chính của phần mềm bảng tính Excel
Workbook chính là một cửa sổ làm việc của file Excel, nó chứa một hoặc nhiều worksheet.
Worksheet chính là một trang tính, mỗi một trang tính đều có tên và chỉ thuộc một Workbook duy nhất.
Row và Column chính là hàng và cột của 1 trang tính.
Cell là một trang tính, được xác định bởi cột và hàng, ví dụ như ô a1,a2,d7.
Các Interface cà Class của thư viện APACHE POI
Workbook: Interface đại diện cho 1 Excel workbook XSSFWorkbook và
SXSSFWorkbook là những class implement từ nó.
Sheet: Interface đại diện cho 1 Excel worksheet XSSFSheet và
SXSSFSheet là các class implement từ Sheet.
Row: Đại diện cho một cột trong Excel worksheet Có XSSFCell và
CellStyle: Đại diện cho style, format của một cột trong Excel file.
XSSFCellStyle là một implement class chúng ta sẽ thao tác trực tiếp với nó.
LẬP TRÌNH JAVA VỚI POI
Một số phương thức của các class XSSFWorkbook, XSSFSheet, Row, Cell
XSSFWorkbook() Khởi tạo 1 SpreadsheetML workbook mới.
XSSFWorkbook(java.io.File file) Khởi tạo 1 đối tượng XSSFWorkbook từ 1 file cho sẵn.
XSSFWorkbook(java.io.FileInputStre am is)
Constructs a XSSFWorkbook object, by buffering the whole stream into memory and then opening an OPCPackage object for it. XSSFWorkbook(OPCPackage pkg) Khởi tạo 1 đối tượng XSSFWorkbook từ 1 đối OpenXML4J Package, xem thêm http://poi.apache.org/oxml4j/. XSSFWorkbook(PackagePart part) Khởi tạo 1 đối tượng XSSFWorkbook
XSSFWorkbook(java.lang.String path)
Khởi tạo 1 đối tượng XSSFWorkbook với đường dẫn
Khởi tạo 1 SpreadsheetML workbook mới.
- Một số Methods hay dùng
XSSFSheet createSheet(int sheetNum); khởi tạo 1 sheet mới
XSSFSheet createSheet(int sheetNum, String name);
Khởi tạo 1 sheet mới(num, name); void close(); Đóng file
Tạo font int addPicture(byte [] pictureData, int format);
Thêm dữ liêu ảnh dạng byte
Contructor Mô tả protected XSSFSheet() Khởi tạo 1 Sheet mới protected XSSFSheet(PackagePart path) Khởi tạo 1 sheet từ 1 package và relationship có sẵn 1.1.1 Một số method hay dùng
Modifier and Type Method java.lang.String getSheetName();
Trả về String sheet name short getTopRow();
Trả về giá trị dòng đầu tiên void createRow(int rownum);
XSSFRow(org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRow row, XSSFSheet sheet) Khởi tạo 1
1.1.3.Một số methods hay dùng
Trả về độ cao hiệ tại row void removeCell(Cell cell);
Trả về XSSFCellStyle của cả Row
XSSFCell XSSFRow ( row, org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell cell
1.1.5 Một số methods hay dùng
Modifier and Type Method void setCellValue(boolean bool)
Thiết Đặt giá trị boolean cell void setCellValue(int value);
Thiết đặt giá trị int cho cell void setCellStyle
String getStringCellValues() trả về giá trị String của cell
Tạo và ghi file excel đầu tiên
File và set giá trị file excel Để tạo workbook rất đơn giản, chúng ta cần thực hiện những bước sau đây :B1 Tạo 1 Workbook.
B2 Tạo 1 Worksheet cho workbook vừa tạo.
B3 Tạo Row cho worksheet vừa tạo.
B4 Tạo Cell cho Row vừa tạo.
B5 Gán giá trị cho cell đó.
To begin with, the necessary libraries are imported, including java.io.File, java.io.FileNotFoundException, java.io.FileOutputStream, java.io.IOException, org.apache.poi.ss.usermodel.Cell, org.apache.poi.ss.usermodel.Row, org.apache.poi.xssf.usermodel.XSSFSheet, and org.apache.poi.xssf.usermodel.XSSFWorkbook These libraries are essential for handling file operations and working with Excel spreadsheets using the Apache POI library The class "test" is then defined, containing the main method where the program execution starts, taking an array of strings as arguments.
// Tạo 1 worksheet từ workbook vừa tạo
XSSFSheet sheet = workbook.createSheet( "Sheet1" ); // Tạo 1 row (hàng) tại vị trí 0
// Tạo 1 cell (ô) tại vị trí 0 của row
// Gán giá trị cho cell đó cell.setCellValue( "My first Excel" );
// Như vậy tại cell[0] của row[0] hay cách khác tại ô vị trí A1 sẽ có giá trị dạng String "My First Excel" try {
FileOutputStream fos = new FileOutputStream( new
File( "My First Excel Program.xlsx" )); workbook write( fos );
System.out.println("Ghi thành Công");
Kết quả chạy chương trình: Đọc và hiển thị file Excel
Here's the rewritten paragraph:To proceed, we will read the file created earlier This involves importing necessary Java libraries, including File, FileInputStream, and Apache POI for Excel operations We will then create a main class, 'Read', with a main method that throws IOException, allowing us to handle potential errors during file reading operations.
// tạo luồng file đầu vào
FileInputStream fis = new FileInputStream( new
File( "My First Excel Program.xlsx" ));
// Tạo 1 XSSFWorkbook có đầu vào
XSSFWorkbook workbook = new XSSFWorkbook( fis ); // Lấy sheet tại vị trí 0
// Lấy dòng tại vị trí 0
// Lấy giá trị cell tại vị trí 0
Kết quả chạy chương trình:
Một số kỹ thuật cơ bản trong Excel với APACHE POI
3.1 Set font chữ cho workbook trong java bằng APACHE POI import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.File; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class testFont { public static void main(String[] args ) {
Font font = workbook createFont(); font.setFontName( "Times New Romans" ); font.setBold( true ); font.setItalic( true );
CellStyle style = workbook.createCellStyle(); style setFont( font );//Thêm font vào cho style //Tạo Sheet
XSSFSheet sheet = workbook.createSheet( "Test" ); //Tạo row
Cell cell = row createCell(0); cell.setCellValue("Chúc thầy và gia đình mạnh khỏe!"); cell setCellStyle( style );
FileOutputStream fos = new FileOutputStream( new
File( "testFont.xlsx" )); workbook write( fos );
3.2.Tô màu chữ và tô màu ô trong Excel import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.ss.usermodel.FillPatternType; public class testStyleRow { public static void main(String[] args ) {
Font font = workbook createFont(); font.setFontName( "Times New Romans" ); font.setBold( true ); font.setItalic( true ); font.setColor(IndexedColors RED1 getIndex()); // Tạo Style
Here is a rewritten paragraph that captures the meaning of the original code snippet, optimized for SEO:"To customize the appearance of a cell in a workbook, create a CellStyle object using the `workbook.createCellStyle()` method Then, set the font for the style using the `setFont()` method, passing in a font object Additionally, set the fill background color to yellow by retrieving the index of the yellow color using `IndexedColors.YELLOW.getIndex()` and applying it to the style with `setFillBackgroundColor()` Finally, add a diamond pattern to the style using `setFillPattern()` with the `FillPatternType.DIAMONDS` parameter."
XSSFSheet sheet = workbook.createSheet( "Test" ); // Tạo row
Cell cell = row createCell(0); cell.setCellValue("Chúc thầy và gia đình mạnh khỏe!"); cell setCellStyle( style );
FileOutputStream fos = new FileOutputStream( new
File( "teststyle.xlsx" )); workbook write( fos );
// TODO Auto-generated catch block e.printStackTrace();
3.3 Fomula- Công thức trong excel import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.util.CellReference; import org.apache.poi.xssf.usermodel.XSSFSheet; public class testFormula { public static void main(String[] args ) {
XSSFSheet sheet = workbook.createSheet("Test Formula");
// Tạo row tại vị trí 0
//Tạo cell tại vị trí 0 của row
//Gán giá trị cell.setCellValue(431);
// tạo row tại vị trí 1 row = sheet createRow(1);
// tạo cell tại vi trí 0 của row cell = row createCell(0); cell.setCellValue(542);
//Tạo row tại vị trí 2 row = sheet createRow(2);
//tạo cell với kiểu formula (Công thức) cell = row createCell(0, CellType FORMULA ); cell.setCellFormula( "sum(a1:a2)" ); try {
FileOutputStream fos = new FileOutputStream( new
File( "testformula.xlsx" )); workbook write( fos );
// TODO Auto-generated catch block e.printStackTrace();
Sau khi chạy, kết quả: Ô A1 và A2 chứa hai giá trị, trong khi đó ô A3 là kiều Formula (Công thức).
Các kỹ thuật nâng cao
4.1 Tạo và ghi một list đối tượng
Trong thực tế, việc ghi file Excel đòi hỏi sự tuần tự và rõ ràng Việc ghi dữ liệu một cách bừa bãi có thể dẫn đến sai sót và khó khăn trong việc quản lý dữ liệu sau này Do đó, việc xác định các bước cụ thể để ghi file Excel là rất quan trọng.
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 ;
} 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 ;
@Override public String toString() { return "Student [studentId=" + studentId + ", firstName=" + firstName + ", lastName=" + lastName + ", age="
+ age + ", mathPoints=" + mathPoints + ", physicsPoints=" + physicsPoints + ", 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
*/ public static List 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" ,
String[] firstName = { "Anh" , "Chi" , " Hùng" , "Linh" ,
"Huy" , "Hòa" , "Trang" , "HuyêP n" , "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ẫP n" , "Phạm" , "Phạm Thị" ,
List list = new ArrayList();
// 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)));
*/ public static void writeExcels(List student , String filePath) throws IOException {
//Tạo Workbook định dạng xlsx
// 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();
*/ public static void printList(List 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
*/ public static void writeHeader(XSSFSheet sheet , byte rowIndex) {
// tạo row tại vị trí index
Row row = sheet createRow( rowIndex );
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
*/ public static void writeStudent(XSSFSheet sheet , int rowNum , List list ) { for (Student students : list ) {
Row row = sheet createRow( rowNum ++);
To populate a row with student data, create cells at specific column indexes and set their values accordingly Start by creating a cell at the COLUMN_INDEX_studentID and set its value to the student's ID using cell.setCellValue(students.getStudentId()) Repeat this process for the first name, last name, age, math points, physics points, and chemistry points at their respective column indexes, such as COLUMN_INDEX_firstName, COLUMN_INDEX_lastName, COLUMN_INDEX_age, COLUMN_INDEX_mathPoints, COLUMN_INDEX_physicsPoints, and COLUMN_INDEX_chemistryPoints.
*/ 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
//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 !" ); }
Dữ liệu sau khi ghi vào file Excel:
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:
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 Iterator cung cấp các hàm quan trọng để điều hướng và thao tác trên các phần tử trong một tập hợp dữ liệu Hàm hasNext() trả về true nếu iterator còn phần tử kế tiếp phần tử đang duyệt, giúp kiểm soát quá trình lặp Khi sử dụng hàm next(), nó sẽ trả về phần tử hiện tại và di chuyển con trỏ tới phần tử tiếp theo, cho phép truy cập tuần tự đến từng phần tử Cuối cùng, hàm remove() cho phép loại bỏ phần tử cuối được trả về bởi Iterator, mặc dù nó hiếm khi được sử dụng trong thực tế.
Here is a rewritten paragraph based on the provided code:"To efficiently read and process Excel files in Java, import necessary libraries such as `java.io.File`, `java.io.FileInputStream`, and `org.apache.poi` packages Utilize `DataFormatter` to format data, `Row` to iterate through rows, and `XSSFSheet` and `XSSFWorkbook` to access and manipulate Excel worksheets and workbooks Create a class, such as `huy`, to encapsulate the logic for reading and processing Excel files, leveraging `ArrayList` and `Iterator` to handle data storage and iteration By following this approach, developers can effectively parse and extract data from Excel files using Java."
// 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
*/ public static void printHeader(Row firstRow) {
{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 định dạng và nhận giá trị cu >a mô i ô dưới dạng Chuô i
// Lẫd y ra Iterator cho tẫd t ca > các dòng cu>a sheet hiện tại.
Iterator iterator = Sheet.iterator();
// Nó tra > vêP phẫP n tư> hiện tại và di chuyê> n con tro > tro > tới phẫP n tư> tiêd p theo.
Row firstRow = iterator.next(); printHeader(firstRow); while (iterator.hasNext())//Nó tra > vêP true nêd u iterator còn phẫP n tư> kêd tiêd p phẫP n tư> đang duyệt
Row currentRow = iterator.next(); listOfStudent(currentRow, student, fmt);
} public static void main(String[] args) {
//Tạo một danh sách Học sinh mới
List listOfStudent = new ArrayList(); try { readExcel2(listOfStudent, FILEPATH);
System.out.println( "Không đọc được dữ liệu" ); }
4.2.2 Trường hợp file có chủ ý không xác định
Here's a rewritten paragraph based on the provided Java code, optimized for SEO:"Reading Excel files in Java can be efficiently achieved using the Apache POI library, which provides a comprehensive set of APIs for working with Microsoft Office file formats By importing the necessary classes, such as `XSSFWorkbook`, `XSSFSheet`, `Row`, `Cell`, and `FormulaEvaluator`, developers can create a Java class to read Excel files The `FileInputStream` class is used to read the Excel file, while the `Iterator` interface is utilized to iterate over the rows and cells in the spreadsheet With the Apache POI library, Java developers can easily extract data from Excel files, including cell values and formulas, and perform various operations on the data."
// Khai báo hằng public static final String FILEPATH = "student.xlsx" ;
* Hàm luôP ng đẫP u vào
*/ public static FileInputStream inputExcel(String filepath ) throws IOException {
FileInputStream fis = new FileInputStream( new
/** * Hàm lẫd y giá trị ô và in ra màn hình
*/ private static Object getAndPrintCellValue(Cell cell ) { CellType cellType = cell.getCellType();
Object cellValue = null ; switch ( cellType ) { case _NONE ://Không có giá trị, không tôP n tại, rô ng System out print( "" );
System out print( "\t" ); break; case BOOLEAN :
System out print( cell getBooleanCellValue()); System out print( "\t" ); break; case BLANK :// Trôd ng
System out print( "\t" ); break; case FORMULA :// Công thức
System out print( cell getCellFormula()); System out print( "\t" );
XSSFWorkbook workbook = (XSSFWorkbook) cell.getSheet().getWorkbook();
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
// In ra giá trị từ công thức
System out print( evaluator evaluate( cell ).getNumberValue()); break; case NUMERIC :
System out print( cell getNumericCellValue()); System out print( "\t" ); break; case STRING :
System out print( cell getStringCellValue()); System out print( "\t" ); break; case ERROR :
System out print( "\t" ); break; default break : ;
*/ public static void readExcel(String filepath ) throws
// Đôd i tượng workbook cho file XSLX.
// Lẫd y ra sheet đẫP u tiên từ workbook
// Lẫd y ra Iterator cho tẫdt ca> các Hàng cu >a sheet
Iterator rowIterator = sheet.iterator(); while ( rowIterator hasNext()) {
Row row = rowIterator.next();// Nó tra > vêP phẫP n tư> hiện tại và di chuyê> n con tro > tro > tới phẫP n tư> tiêd p theo.
// Lẫd y Iterator cho tẫd t ca > các Ô cu >a dòng hiện tại.
Iterator cellIterator = row.cellIterator(); while ( cellIterator hasNext()) // Nó tra > vêP true nêd u iterator còn phẫP n tư> kêd tiêd p phẫP n tư> đang duyệt.
{ Cell cell = cellIterator.next();// Nó tra > vêP phẫP n tư> hiện tại và di chuyê> n con tro > tro > tới phẫP n tư> tiêd p
// theo. getAndPrintCellValue(cell);//In ra console
} public static void main(String[] args ) { try { readExcel( FILEPATH );
System out println( "Không đọc được dữ liệu" ); }