【发布时间】:2020-05-03 18:40:39
【问题描述】:
我有以下代码:
@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 编码的,所有单元格都被格式化为文本。
很遗憾,某些特殊字符(在我的例子中:é、ç 和 Î,但我确信还有更多)无法正确读取。任何帮助将不胜感激。
【问题讨论】:
-
您是否尝试过删除 xl 文件中的单元格格式? teachucomp.com/remove-cell-formatting-in-excel-instructions
-
这可能是由于 Java 和 POI 使用 UTF-16 造成的吗?尝试将 excel 文件保存为 UTF-16,看看是否有帮助。
-
不幸的是,两者都不起作用。
-
这有点麻烦,但您可以尝试将 .xls 文件导出为 .csv。我相信 Excel 会在没有字节顺序标记的情况下保存它,因此在记事本中打开该文件并选择另存为 UTF-8。然后将其导入 Excel 并重新另存为 .xls,或者改为导入 .csv 文件。