NỘI DUNG BÀI HỌC

✅ Đọc File Excel để lấy data test
✅ Ghi data mới vào lại File Excel


Cài đặt thư viện Apache Poi

Sử dụng Maven để cài thư viện Apache POI vào pom.xml của dự án Maven của bạn. Hiện tại Anh Tester đang sử dụng Apache Poi phiên bản 5.x.x, tất cả các phiên bản mới nhất có thể được tìm thấy tại đây

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi</artifactId>
	<version>5.2.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi-ooxml</artifactId>
	<version>5.2.5</version>
</dependency>

(Cập nhật ngày: 25/11/2023)

Bản Apache POI Common mới này cần có thư viện Commons IO bổ trợ mới chạy êm được:

<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.16.1</version>
</dependency>

(Cập nhật ngày: 08/04/2024)


Tiếp theo tạo class để lưu các hàm xử lý Excel. Cụ thể An đặt là ExcelHelper. Bỏ trong package helpers chung với PropertiesHelper ở bài trước.

Hàm set Excel file theo Sheet cần dùng

Tại đây đặt tên hàm là setExcelFile với 2 đối số là đường dẫn đến Excel PathSheet Name

import java.awt.Color;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.poi.ss.usermodel.*;

public class ExcelHelper {

    private FileInputStream fis;
    private FileOutputStream fileOut;
    private Workbook wb;
    private Sheet sh;
    private Cell cell;
    private Row row;
    private CellStyle cellstyle;
    private Color mycolor;
    private String excelFilePath;
    private Map<String, Integer> columns = new HashMap<>();

    public void setExcelFile(String ExcelPath, String SheetName){
        try {
            File f = new File(ExcelPath);

            if (!f.exists()) {
                System.out.println("File doesn't exist.");
            }

            fis = new FileInputStream(ExcelPath);
            wb = WorkbookFactory.create(fis);
            sh = wb.getSheet(SheetName);

            if (sh == null) {
                throw new Exception("Sheet name doesn't exist.");
            }

            this.excelFilePath = ExcelPath;

            //adding all the column header names to the map 'columns'
            sh.getRow(0).forEach(cell ->{
                columns.put(cell.getStringCellValue(), cell.getColumnIndex());
            });

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

 

Hàm get Cell data từ Excel File

Hàm getCellData(String columnName, int rowIndex) là hàm chúng ta sẽ gọi ra để dùng. Còn hàm getCellData(int columnIndex, int rowIndex) để xử lý thôi. Kiểu viết lại cho nó gọn ý mà.

public String getCellData(int columnIndex, int rowIndex) {
    try {
        cell = sh.getRow(rowIndex).getCell(columnIndex);
        String CellData = null;
        switch (cell.getCellType()) {
        case STRING:
            CellData = cell.getStringCellValue();
            break;
        case NUMERIC:
            if (DateUtil.isCellDateFormatted(cell)) {
                CellData = String.valueOf(cell.getDateCellValue());
            } else {
                CellData = String.valueOf((long) cell.getNumericCellValue());
            }
            break;
        case BOOLEAN:
            CellData = Boolean.toString(cell.getBooleanCellValue());
            break;
        case BLANK:
            CellData = "";
            break;
        }
        return CellData;
    } catch (Exception e) {
        return "";
    }
}

//Gọi ra hàm này nè
public String getCellData(String columnName, int rowIndex) {
    return getCellData(columns.get(columnName), rowIndex);
}


🔆 Gọi ra dùng lại thì gọi hàm setExcelFile trước để khai báo File Excel cần dùng xong đến gọi getCellData để lấy data theo từng ô


Chuẩn bị file Excel như sau:

[Selenium Java] Bài 24: Đọc File Excel để lấy data test | Anh Tester

Ví dụ đọc từ file testData.xlsx tại Sheet1 với các giá trị bên dưới (nhớ chú ý link kẻo sai)

  • cột username dòng 1 (dòng và cột bắt đầu từ 0) nghĩa là thứ tự 2 của excel á
  • cột password dòng 1
  • cột pin dòng 1

public static void main(String []args) throws Exception {
    ExcelHelper excel = new ExcelHelper();
    excel.setExcelFile("./testData.xlsx", "Sheet1");
    
    System.out.println(excel.getCellData("userName", 1));
    System.out.println(excel.getCellData("password", 1));
    System.out.println(excel.getCellData("pin", 1));
}


Hàm ghi data vào lại File Excel theo từng Cell

Bạn chỉ cần truyền tham số tuần tự cho hàm setCellData(String text, int columnIndex, int rowIndex)
(giá trị cần ghi - vị trí dòng - vị trí cột)

Hoặc hàm setCellData(String text, String columnName, int rowIndex) lấy theo tên cột

//set by column index
public void setCellData(String text, int columnIndex, int rowIndex) {
    try {
        row = sh.getRow(rowIndex);
        if (row == null) {
            row = sh.createRow(rowIndex);
        }
        cell = row.getCell(columnIndex);

        if (cell == null) {
            cell = row.createCell(columnIndex);
        }
        cell.setCellValue(text);

        XSSFCellStyle style = (XSSFCellStyle) wb.createCellStyle();
        style.setFillPattern(FillPatternType.NO_FILL);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);

        cell.setCellStyle(style);

        fileOut = new FileOutputStream(excelFilePath);
        wb.write(fileOut);
        fileOut.flush();
        fileOut.close();
    } catch (Exception e) {
        e.getMessage();
    }
}

//set by column name
public void setCellData(String text, String columnName, int rowIndex) {
    try {
        row = sh.getRow(rowIndex);
        if (row == null) {
            row = sh.createRow(rowIndex);
        }
        cell = row.getCell(columns.get(columnName));

        if (cell == null) {
            cell = row.createCell(columns.get(columnName));
        }
        cell.setCellValue(text);

        XSSFCellStyle style = (XSSFCellStyle) wb.createCellStyle();
        style.setFillPattern(FillPatternType.NO_FILL);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);

        cell.setCellStyle(style);

        fileOut = new FileOutputStream(excelFilePath);
        wb.write(fileOut);
        fileOut.flush();
        fileOut.close();
    } catch (Exception e) {
        e.getMessage();
    }
}


🔆 Gọi hàm setCellData ra dùng lại:

public static void main(String []args) throws Exception {
    ExcelHelper excel = new ExcelHelper();
    excel.setExcelFile("./testData.xlsx", "Sheet1");

    //Ghi giá trị "pass" vào dòng 1 cột 3 (dòng và cột bắt đầu tính từ 0)
    excel.setCellData("pass", 3, 1);
}


🔆 Kết quả như bên dưới:

[Selenium Java] Bài 24: Đọc File Excel để lấy data test | Anh Tester


Yeah xong rồi đó. Mở rộng hơn thì chúng ra có thể lấy ra nhiều dòng thì sẽ dùng vòng lặp FORDataProvider của TestNG cung cấp.

DataProvider sẽ học tiếp theo ở bài sau nhé !!

Teacher

Teacher

Anh Tester

Software Quality Engineer

Đường dẫu khó chân vẫn cần bước đi
Đời dẫu khổ tâm vẫn cần nghĩ thấu

Cộng đồng Automation Testing Việt Nam:

🌱 Telegram Automation Testing:   Cộng đồng Automation Testing
🌱 
Facebook Group Automation: Cộng đồng Automation Testing Việt Nam
🌱 
Facebook Fanpage: Cộng đồng Automation Testing Việt Nam - Selenium
🌱 Telegram
Manual Testing:   Cộng đồng Manual Testing
🌱 
Facebook Group Manual: Cộng đồng Manual Testing Việt Nam

Chia sẻ khóa học lên trang

Bạn có thể đăng khóa học của chính bạn lên trang Anh Tester để kiếm tiền

Danh sách bài học