首页 > 解决方案 > 读取包含特殊 (UTF-8) 字符的 Excel 单元格值 - Selenium/Java

问题描述

我有以下代码:

    @Test(groups = {"customer"}, dataProvider = "customerData", dataProviderClass = Testdata.class, priority = 0)
    public void createCustomer(String cName, String cAddress, String cAddress2, String cCity, String cState, String cZip, String cContact, 
        String cPhone) throws InterruptedException {        
        NAV.customer.create(driver, wait, js);
        NAV.customer.edit(driver, wait, js, cName, cAddress, cAddress2, cCity, cState, cZip, cContact, cPhone);
        NAV.windowClose(driver, wait, js);
    }

并使用以下代码读取我的 Excel 文件:

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class Testdata {
    public static Object[][] getExcel(String filepath, String sheetName) throws InvalidFormatException, IOException {
        FileInputStream file = new FileInputStream(filepath);
        XSSFWorkbook wb = new XSSFWorkbook(file);
        XSSFSheet sheet = wb.getSheet(sheetName);
        int rowCount = sheet.getLastRowNum();
        int column = sheet.getRow(0).getLastCellNum();
        Object[][] data = new Object[rowCount][column];
        for (int i = 1; i <= rowCount; i++) {
            XSSFRow row = sheet.getRow(i);
            for (int j = 0; j < column; j++) {
                XSSFCell cell = row.getCell(j);
                DataFormatter formatter = new DataFormatter();
                String val = formatter.formatCellValue(cell);
                data[i - 1][j] = val;
            }
        }
        wb.close();
        return data;
    }
}

我使用 Selenium 3.14(UTF-8 文本文件编码)和 Apache POI 4.1.0。我的 Excel 文件是 UTF-8 编码的,所有单元格都被格式化为文本。

不幸的是,某些特殊字符(在我的例子中:é、ç 和 Î,但我确信还有更多)无法正确读取。任何帮助将非常感激。

标签: javaexcelseleniumutf-8

解决方案


我不确定您的特定字符,但是当我阅读具有 / \ [ ] * 的表格时?or : 在它的名字中,例如,它用“_”替换那些无效字符

尝试在任何有特殊字符的地方用“_”替换工作表名称。


推荐阅读