【问题标题】:Cannot get a text value from a numeric cell “Poi”无法从数字单元格“Poi”中获取文本值
【发布时间】:2015-05-08 13:47:12
【问题描述】:

我正在尝试在 Excel 中使用电子表格中的数据,但总是出现此错误,已尝试将工作表格式化为文本和数字,但错误仍然存​​在。

我看到有人使用它解决了cell.setCellType ( Cell.CELL_TYPE_STRING ) ;,但我不知道我的代码中的这段代码的位置。

WebElement searchbox = driver.findElement(By.name("j_username"));
WebElement searchbox2 = driver.findElement(By.name("j_password"));         

try {
    FileInputStream file = new FileInputStream(new File("C:\\paulo.xls")); 
    HSSFWorkbook workbook = new HSSFWorkbook(file);
    HSSFSheet sheet = workbook.getSheetAt(0);

    for (int i=1; i <= sheet.getLastRowNum(); i++){
        String j_username = sheet.getRow(i).getCell(0).getStringCellValue();
        String j_password = sheet.getRow(i).getCell(0).getStringCellValue();

        searchbox.sendKeys(j_username);
        searchbox2.sendKeys(j_password);
        searchbox.submit();  

        driver.manage().timeouts().implicitlyWait(10000, TimeUnit.MILLISECONDS);
    }

    workbook.close();
    file.close();
} catch (FileNotFoundException fnfe) {
    fnfe.printStackTrace();
} catch (IOException ioe) {
    ioe.printStackTrace();

【问题讨论】:

  • 你能放置完整的堆栈跟踪错误消息吗?
  • sheet.getRow(i).getCell(0).toString() 呢?
  • @Abdull 你的评论比官方的回答更重要:) 解决了我的问题
  • 如果您需要字符串形式的数字类型,请尝试 cell.getRawValue():stackoverflow.com/questions/13563747

标签: java apache-poi


【解决方案1】:

格式化程序在这种情况下可以正常工作。

import org.apache.poi.ss.usermodel.DataFormatter;

FileInputStream fis = new FileInputStream(workbookName);
Workbook workbook = WorkbookFactory.create(fis);
Sheet sheet = workbook.getSheet(sheetName);
DataFormatter formatter = new DataFormatter();
String val = formatter.formatCellValue(sheet.getRow(row).getCell(col));
list.add(val);   //Adding value to list

【讨论】:

  • 这个东西对我不起作用,它的输出类似于:SUM(I38+D39+F39-G39-H39)
  • @SGaber,您需要提供一个公式评估器作为formatCellValue 方法的第二个参数,然后它甚至可以正确格式化公式。
【解决方案2】:

罢工>

    Cell cell = sheet.getRow(i).getCell(0);
    cell.setCellType ( Cell.CELL_TYPE_STRING );
    String j_username = cell.getStringCellValue();

更新

好的,正如在 cmets 中所说的那样,尽管这很有效,但它不是从 Excel 单元格中检索数据的正确方法。

根据手册here

如果您想要为您的数字单元格获取一个字符串值, 停止!。这不是这样做的方法。相反,用于获取字符串 数值或布尔值或日期单元格的值,请改用 DataFormatter。

并根据DataFormatter API

DataFormatter 包含用于格式化存储在 细胞。 这对于报告和 GUI 演示很有用,当您 需要完全按照 Excel 中显示的方式显示数据。 支持的格式 包括货币、SSN、百分比、小数、日期、电话号码、 邮政编码等

因此,显示数字单元格值的正确方法如下:

 DataFormatter formatter = new DataFormatter(); //creating formatter using the default locale
 Cell cell = sheet.getRow(i).getCell(0);
 String j_username = formatter.formatCellValue(cell); //Returns the formatted value of a cell as a String regardless of the cell type.

【讨论】:

  • for (int i=1; i
  • 犯了三个错误类型不匹配:无法从 HSSFCell 转换为 Table.Cell CELL_TYPE_STRING 无法解析或不是字段 Table.Cell 类型的 getStringCellValue() 方法未定义
  • 电子表格中只有数字 89550536100002595717
  • 不要这样做! POI javadocs are very clear 这不是正确的方法!
  • @Gagravarr,你是对的。我不知道这个,稍后会修复我的答案。
【解决方案3】:

正如Apache POI Javadocs 中所述,您不应该使用cell.setCellType(Cell.CELL_TYPE_STRING) 来获取数字单元格的字符串值,因为您会丢失所有格式

作为javadocs explain,您应该使用DataFormatter

DataFormatter 所做的是将表示单元格的浮点值存储在文件中,以及应用于它的格式规则,并返回一个字符串,该字符串看起来就像 Excel 中的单元格所做的那样。

所以,如果你在寻找单元格的字符串,看起来就像在 Excel 中看到的一样,只需执行以下操作:

 // Create a formatter, do this once
 DataFormatter formatter = new DataFormatter(Locale.US);

 .....

 for (int i=1; i <= sheet.getLastRowNum(); i++) {
        Row r = sheet.getRow(i);
        if (r == null) { 
           // empty row, skip
        } else {
           String j_username = formatter.formatCellValue(row.getCell(0));
           String j_password =  formatter.formatCellValue(row.getCell(1));

           // Use these
        }
 }

格式化程序将按原样返回字符串单元格,对于数字单元格,会将样式上的格式化规则应用于单元格的编号

【讨论】:

  • 这个东西对我不起作用,它的输出类似于:SUM(I38+D39+F39-G39-H39)
【解决方案4】:

使用代码
cell.setCellType(Cell.CELL_TYPE_STRING);
在读取字符串值之前,这可以帮助您。
我正在使用 POI 版本 3.17 Beta1 版本, 确保版本兼容性也..

【讨论】:

    【解决方案5】:

    使用DataFormatter 解决了这个问题。感谢“Gagravarr”的初始帖子。

    DataFormatter formatter = new DataFormatter();
    
    String empno = formatter.formatCellValue(cell0);
    

    【讨论】:

    • 这个东西对我不起作用,它的输出类似于:SUM(I38+D39+F39-G39-H39)
    【解决方案6】:
    CellType cell = row.getCell(j).getCellTypeEnum();
    
    switch(cell) {
        case NUMERIC:
            intVal = row.getCell(j).getNumericCellValue();
            System.out.print(intVal);
            break;
        case STRING:
            stringVal = row.getCell(j).getStringCellValue();
            System.out.print(stringVal);
            break;
    }
    

    【讨论】:

      【解决方案7】:

      不同细胞类型的辅助方法:

      private static String returnStringValue(Cell cell) {
          CellType cellType = cell.getCellType();
      
          switch (cellType) {
              case NUMERIC:
                  double doubleVal = cell.getNumericCellValue();
                  return String.valueOf(doubleVal);
              case STRING:
                  return cell.getStringCellValue();
              case ERROR:
                  return String.valueOf(cell.getErrorCellValue());
              case BLANK:
                  return "";
              case FORMULA:
                  return cell.getCellFormula();
              case BOOLEAN:
                  return String.valueOf(cell.getBooleanCellValue());
          }
          return "error decoding string value of the cell";
      }
      

      【讨论】:

        【解决方案8】:

        使用它确实有效的代码,我对其进行了修改。

        import java.io.FileInputStream;
        import java.io.IOException;
        import java.sql.Connection;
        import java.sql.DriverManager;
        import java.sql.PreparedStatement;
        import org.apache.poi.poifs.filesystem.POIFSFileSystem;
        //import org.apache.poi.ss.usermodel.Row;
        import org.apache.poi.ss.usermodel.*;
        
        public class TestApp {
        
            public static void main(String[] args) throws Exception {
        
                try {
        
                    Class forName = Class.forName("com.mysql.jdbc.Driver");
                    Connection con = null;
                    con = DriverManager.getConnection("jdbc:mysql://localhost/tables", "root", "root");
                    con.setAutoCommit(false);
                    PreparedStatement pstm = null;
                    FileInputStream input = new FileInputStream("C:\\Users\\Desktop\\a1.xls");
                    POIFSFileSystem fs = new POIFSFileSystem(input);
                    Workbook workbook;
                    workbook = WorkbookFactory.create(fs);
                    Sheet sheet = workbook.getSheetAt(0);
                    Row row;
                    for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                        row = (Row) sheet.getRow(i);
                        String name = row.getCell(0).getStringCellValue();
                        String add = row.getCell(1).getStringCellValue();
        
                        int  contact = (int) row.getCell(2).getNumericCellValue();
        
                        String email = row.getCell(3).getStringCellValue();
        
                        String sql = "INSERT INTO employee (name, address, contactNo, email) VALUES('" + name + "','" + add + "'," + contact + ",'" + email + "')";
                        pstm = (PreparedStatement) con.prepareStatement(sql);
                        pstm.execute();
                        System.out.println("Import rows " + i);
                    }
                    con.commit();
                    pstm.close();
                    con.close();
                    input.close();
                    System.out.println("Success import excel to mysql table");
                } catch (IOException e) {
                }
            }
        
        }
        

        【讨论】:

        • 如果您不添加库文件,例如 1) dom4j-1.6.jar 2) xmlbeans-2.3.0.jar 3) poi-ooxml-schemas-3.9.jar 4) poi-,很可能会发生这种情况ooxml-3.9.jar 5) poi-3.10-FINAL.jar
        【解决方案9】:

        这是解决错误的另一种方法:“无法从数字单元格“Poi”获取文本值”

        转到 Excel 工作表。拖动并选择要从 Excel 工作表中导入数据的数值。转到格式>数字>然后选择“纯文本”然后导出为.xlsx。现在尝试运行脚本

        希望工作顺利...!

        Cannot get a text value from a numeric cell “Poi”.img

        【讨论】:

          【解决方案10】:

          如果您正在使用 cellIterator.... 进行行处理,那么这对我有用 ....

            DataFormatter formatter = new DataFormatter();   
            while(cellIterator.hasNext())
            {                         
                  cell = cellIterator.next();
                  String val = "";            
                  switch(cell.getCellType()) 
                  {
                      case Cell.CELL_TYPE_NUMERIC:
                          val = String.valueOf(formatter.formatCellValue(cell));
                          break;
                      case Cell.CELL_TYPE_STRING:
                          val = formatter.formatCellValue(cell);
                          break;
                  }
              .....
              .....
            }
          

          【讨论】:

            【解决方案11】:
            public class B3PassingExcelDataBase {
            
            
                @Test()
                //Import the data::row start at 3 and column at 1: 
                public static void imortingData () throws IOException {
            
                    FileInputStream  file=new         FileInputStream("/Users/Downloads/Book2.xlsx");
                    XSSFWorkbook book=new XSSFWorkbook(file);
                    XSSFSheet sheet=book.getSheet("Sheet1");
            
                    int rowNum=sheet.getLastRowNum();
                    System.out.println(rowNum);
            
                    //get the row and value and assigned to variable to use in application
                    for (int r=3;r<rowNum;r++) {
            
                        // Rows stays same but column num changes and this is for only one person. It iterate for other.
                         XSSFRow currentRow=sheet.getRow(r);
            
                         String fName=currentRow.getCell(1).toString();
                         String lName=currentRow.getCell(2).toString();
                         String phone=currentRow.getCell(3).toString();
                         String email=currentRow.getCell(4).toString()
            
                           //passing the data
                            yogen.findElement(By.name("firstName")).sendKeys(fName);    ;
                            yogen.findElement(By.name("lastName")).sendKeys(lName); ;
                            yogen.findElement(By.name("phone")).sendKeys(phone);    ;
            
                    }
            
                    yogen.close();
            
            
                }
            
            }
            

            【讨论】:

              【解决方案12】:

              这将起作用:

              WebElement searchbox = driver.findElement(By.name("j_username"));
              WebElement searchbox2 = driver.findElement(By.name("j_password"));         
              
              
              try {
              
                    FileInputStream file = new FileInputStream(new File("C:\\paulo.xls")); 
                    HSSFWorkbook workbook = new HSSFWorkbook(file);
              
                    HSSFSheet sheet = workbook.getSheetAt(0);
              
                  for (int i=1; i <= sheet.getLastRowNum(); i++){
              
                          HSSFCell j_username = sheet.getRow(i).getCell(0)
                          HSSFCell j_password = sheet.getRow(i).getCell(0)
              
                          //Setting the Cell type as String
                          j_username.setCellType(j_username.CELL_TYPE_STRING)
                          j_password.setCellType(j_password.CELL_TYPE_STRING)
              
                          searchbox.sendKeys(j_username.toString());
                          searchbox2.sendKeys(j_password.toString());
              
              
                          searchbox.submit();       
              
                          driver.manage().timeouts().implicitlyWait(10000, TimeUnit.MILLISECONDS);
              
                  }
              
                    workbook.close();
                    file.close();
              
                   } catch (FileNotFoundException fnfe) {
                    fnfe.printStackTrace();
                   } catch (IOException ioe) {
                    ioe.printStackTrace();
                   }
              
              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2019-03-14
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多