簡體   English   中英

無法從數字單元格“Poi”中獲取文本值

[英]Cannot get a text value from a numeric cell “Poi”

我正在嘗試使用 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();

在這種情況下,格式化程序可以正常工作。

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

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

更新

好的,正如評論中所說,盡管這很有效,但它不是從 Excel 單元格中檢索數據的正確方法。

根據這里的手冊:

如果您想要為您的數字單元格獲取字符串值,請停止! 這不是這樣做的方法。 相反,要獲取數字或布爾值或日期單元格的字符串值,請改用 DataFormatter。

並根據DataFormatter API

DataFormatter 包含用於格式化存儲在單元格中的值的方法。 當您需要完全按照 Excel 中的數據顯示數據時,這對於報告和 GUI 演示很有用。 支持的格式包括貨幣、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.

Apache POI Javadocs中所述,您不應該使用cell.setCellType(Cell.CELL_TYPE_STRING)來獲取數字單元格的字符串值,因為您會丟失所有格式

相反,正如javadocs 解釋的那樣,您應該使用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
        }
 }

格式化程序將按原樣返回字符串單元格,對於數字單元格,會將樣式上的格式化規則應用於單元格的編號

使用代碼
cell.setCellType(Cell.CELL_TYPE_STRING);
在讀取字符串值之前,這可以幫助您。
我使用的是 POI 3.17 Beta1 版本,確保版本兼容性也..

使用DataFormatter解決了這個問題。 感謝“Gagravarr”的初始帖子。

DataFormatter formatter = new DataFormatter();

String empno = formatter.formatCellValue(cell0);
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;
}

不同細胞類型的輔助方法:

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";
}

使用它肯定有效的代碼,我修改了它。

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) {
        }
    }

}

這是解決錯誤的另一種方法:“無法從數字單元格“Poi”中獲取文本值”

轉到 Excel 工作表。 拖動並選擇要從 Excel 工作表中導入數據的數值。 轉到格式>數字>然后選擇“純文本”然后導出為.xlsx。 現在嘗試運行腳本

希望工作正常...!

無法從數字單元格“Poi”.img 中獲取文本值

如果您使用 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;
        }
    .....
    .....
  }
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();


    }

}

這將起作用:

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();
     }
public static List<SupplierSubmittedDataMapperModel> convertExcelToList(String NAME){

    List<SupplierSubmittedDataMapperModel> list = new ArrayList<>();
    try {
        FileInputStream file = new FileInputStream(new File(NAME));
        DataFormatter dataFormatter = new DataFormatter();
        XSSFWorkbook workbook = new XSSFWorkbook(file);
        XSSFSheet sheet = workbook.getSheetAt(2);
        
        int rowNumber = 2;
          Iterator<Row> iterator = sheet.iterator();
          while(iterator.hasNext()) {
              Row row=iterator.next();
              
              
              Iterator<Cell> cells = row.iterator();
              int cid = 0;
              SupplierSubmittedDataMapperModel sp = new SupplierSubmittedDataMapperModel();
             
              while(cells.hasNext()) {
                  Cell cell = cells.next();
                  String cellValue = dataFormatter.formatCellValue(cell.getRow().getCell(cid));
                  
                  switch(cid) {
                  case 0:
                      sp.setSectorType(cellValue);
                      break;
                  case 1:
                      sp.setPlatformFamily(cellValue);
                      break;
                  case 2:
                      sp.setT1Supplier(cellValue);
                      break;
                  case 3:
                      sp.setT2Supplier(cellValue);
                      break;
                  case 4:
                      sp.setDistribotor(cellValue);
                      break;
                  case 5:
                      sp.setT2PartCodeAtT1(cellValue);
                      break;
                  case 6:
                      sp.setT2PartNumber(cellValue);
                      break;
                  case 7:
                      sp.setLoA(cellValue);
                      break;
                  case 8:
                      sp.setMultiSource(cellValue);
                      break;
                  case 9:
                      sp.setQtyUsage(cellValue);
                      break;
                  case 10:
                      sp.setDataType(cellValue);
                      break;
                  case 11:
                      sp.setWeek22(cellValue);
                      break;
                  case 12:
                      sp.setWeek23(cellValue);
                      break;
                  case 13:
                      sp.setWeek23(cellValue);
                      break;
                  case 14:
                      sp.setWeek24(cellValue);
                      break;
                  case 15:
                      sp.setWeek25(cellValue);
                      break;
                  case 16:
                      sp.setWeek26(cellValue);
                      break;
                  case 17:
                      sp.setWeek27(cellValue);
                      break;
                  case 18:
                      sp.setWeek28(cellValue);
                      break;
                  case 19:
                      sp.setWeek29(cellValue);
                      break;
                  case 20:
                      sp.setWeek30(cellValue);
                      break;
                  case 21:
                      sp.setWeek31(cellValue);
                      break;
                  case 22:
                      sp.setWeek32(cellValue);
                      break;
                  case 23:
                      sp.setWeek33(cellValue);
                      break;
                  case 24:
                      sp.setWeek34(cellValue);
                      break;
                  case 25:
                      sp.setWeek35(cellValue);
                      break;
                  case 26:
                      sp.setWeek36(cellValue);
                      break;
                  case 27:
                      sp.setWeek37(cellValue);
                      break;
                  case 28:
                      sp.setWeek38(cellValue);
                      break;
                  case 29:
                      sp.setWeek39(cellValue);
                      break;
                  case 30:
                      sp.setWeek40(cellValue);
                      break;
                  case 31:
                      sp.setWeek41(cellValue);
                      break;
                  case 32:
                      sp.setWeek42(cellValue);
                      break;
                  case 33:
                      sp.setWeek43(cellValue);
                      break;
                  case 34:
                      sp.setWeek44(cellValue);
                      break;
                  case 35:
                      sp.setWeek45(cellValue);
                      break;
                  case 36:
                      sp.setWeek46(cellValue);
                      break;
                  case 37:
                      sp.setWeek47(cellValue);
                      break;
                  case 38:
                      sp.setWeek48(cellValue);
                      break;
                  case 39:
                      sp.setWeek49(cellValue);
                      break;
                  case 40:
                      sp.setWeek50(cellValue);
                      break;
                  case 41:
                      sp.setWeek51(cellValue);
                      break;
                  case 42:
                      sp.setWeek52(cellValue);
                      break;
                  case 43:
                      sp.setYear2023(cellValue);
                      break;
                  case 44:
                      sp.setYear2024(cellValue);
                      break;
                  case 45:
                      sp.setYear2059(cellValue);
                      break;
                  default :
                      break;
                      
                  
                  }
                  
                  cid++;
                  
              }
              list.add(sp);
             System.out.println(sp);
               }
          
          workbook.close();
        }catch(Exception e) {
        
        e.printStackTrace();
        }   
    return list;

}

您可以添加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++){
        // Row will be iterated and Cell will be 0 and 1 as per the example:   
        row.getCell(0).setCellType(CellType.STRING); // set Cell Type as String
        row.getCell(1).setCellType(CellType.STRING); // set Cell Type as String

        String j_username = sheet.getRow(i).getCell(0).getStringCellValue();
        String j_password = sheet.getRow(i).getCell(1).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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM