无法从与java的seleniumwebdriver excel表中的数值
我的Java
public class Readexcel { public void readfile(String filepath, String filename, String sheetname) throws IOException { File file = new File(filepath+"\\"+filename); FileInputStream fis = new FileInputStream(file); // for creating .xlsx workbook Workbook wb = new XSSFWorkbook(fis); // for reading the sheet by its name Sheet sh = wb.getSheet(sheetname); //find the total rows in sheet int rowcount = sh.getLastRowNum()-sh.getFirstRowNum(); // create a loop to create for(int i=0;i<rowcount+1;i++) { Row row= sh.getRow(i); // create a loop to print cell values for(int j=0;j<row.getLastCellNum();j++) { Cell cell= row.getCell(j); switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: System.out.print(row.getCell(j).getStringCellValue() + " "); break; case Cell.CELL_TYPE_NUMERIC: System.out.print(row.getCell(j).getNumericCellValue() + " "); break; } System.out.print(row.getCell(j).getStringCellValue()+"||"); } System.out.println(); } } public static void main(String...strings) throws IOException { Readexcel re = new Readexcel(); String filepath = "F://Excelsheet"; re.readfile(filepath,"Book1.xlsx","Sheet1"); } }
通过使用上面的代码,我得到一个错误“无法从数字单元格中获取文本值”。 任何帮助? 另外我的输出没有正确的alignment。 所有的string都显示一个一个。 输出应该是这样的
Username Password john 123 rambo 456
但我越来越像输出
Username password john
改变你的for循环后// create a loop to print cell values
注释:
for (int j = 0; j < row.getLastCellNum(); j++) { Cell cell = row.getCell(j); switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: System.out.print(row.getCell(j).getStringCellValue() + " "); break; case Cell.CELL_TYPE_NUMERIC: System.out.print((int)row.getCell(j).getNumericCellValue() + " "); break; } }
开关是识别单元格的types。 对于数字单元格,您必须使用getNumericCellValue()
而不是getStringCellValue()
对于第二个问题,使用System.out.print()
而不是System.out.println()
来打印双引号之间的内容,并将打印光标移动到下一行。
编辑:
这是我的readFile()函数的样子:
public void readfile(String filepath, String filename, String sheetname) throws IOException { File file = new File(filepath+"\\"+filename); FileInputStream fis = new FileInputStream(file); // for creating .xlsx workbook Workbook wb = new XSSFWorkbook(fis); // for reading the sheet by its name Sheet sh = wb.getSheet(sheetname); // find the total rows in sheet int rowcount = sh.getLastRowNum() - sh.getFirstRowNum(); // create a loop to create for (int i = 0; i < rowcount + 1; i++) { Row row = sh.getRow(i); // create a loop to print cell values for (int j = 0; j < row.getLastCellNum(); j++) { Cell cell = row.getCell(j); switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: System.out.print(row.getCell(j).getStringCellValue() + " "); break; case Cell.CELL_TYPE_NUMERIC: System.out.print((int)row.getCell(j).getNumericCellValue() + " "); break; } } System.out.println(); } }
编辑2
更改System.out.print(row.getCell(j).getNumericCellValue() + " ");
对于System.out.print((int)row.getCell(j).getNumericCellValue() + " ");
在Cell.CELL_TYPE_NUMERIC
情况下