tutorial poi para ooxml libreria example descargar java apache-poi

java - para - No se puede obtener un valor de texto de una celda numérica "Poi"



java apache poi documentation (11)

Como se explica en los documentos here , no debe usar cell.setCellType(Cell.CELL_TYPE_STRING) para obtener el valor de cadena de una celda numérica, ya que perderá todo el formato

En cambio, como here los here , debe usar DataFormatter

Lo que hace DataFormatter es tomar el valor de coma flotante que representa la celda almacenada en el archivo, junto con las reglas de formato aplicadas, y le devuelve una cadena que se parece a la celda en Excel.

Entonces, si buscas una Cadena de la celda, parecida a como la tenías en Excel, simplemente haz lo siguiente:

// 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 } }

El formateador devolverá las celdas de cadena tal cual, y para las celdas numéricas aplicará las reglas de formato en el estilo al número de la celda

Estoy tratando de consumir datos de una hoja de cálculo en Excel, pero siempre de este error, ya traté de formatear la hoja de trabajo a texto y número y aún persiste el error.

Vi a una persona que lo usaba resolvió cell.setCellType ( Cell.CELL_TYPE_STRING ) ; pero no sé dónde encajo este pasaje en mi código.

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();


El formateador funcionará bien en este caso.

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


Este es uno de los otros métodos para resolver el error: "No se puede obtener un valor de texto de una celda numérica" ​​Poi ""

Ir a la hoja de Excel. Arrastre y seleccione los números que está importando Datos desde la hoja de Excel. Vaya a Formato> Número> Luego seleccione "Texto sin formato" y luego exporte como .xlsx. Ahora intenta ejecutar el script

La esperanza funciona bien ...!

No se puede obtener un valor de texto de una celda numérica "Poi" .img


Esto funcionará:

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(); }


Si está procesando en filas con cellIterator ... entonces esto funcionó para mí ...

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


Usa ese código, definitivamente funciona y lo modifiqué.

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


Usando el DataFormatter este problema se resuelve. Gracias a "Gagravarr" por la publicación inicial.

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


usa el código
cell.setCellType(Cell.CELL_TYPE_STRING);
antes de leer el valor de la cadena, que puede ayudarte.
Estoy usando POI versión 3.17 versión Beta1, seguro que la compatibilidad de la versión también ...


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

ACTUALIZAR

Ok, como se ha dicho en los comentarios, a pesar de que esto funciona, no es un método correcto para recuperar datos de una celda de Excel.

De acuerdo con el manual here :

Si lo que desea hacer es obtener un valor de cadena para su celda numérica, ¡deténgase! Esta no es la manera de hacerlo. En su lugar, para obtener el valor de cadena de una celda numérica, booleana o de fecha, use DataFormatter en su lugar.

Y de acuerdo con la API DataFormatter

DataFormatter contiene métodos para formatear el valor almacenado en una celda. Esto puede ser útil para informes y presentaciones de GUI cuando necesita mostrar los datos exactamente como aparecen en Excel. Los formatos admitidos incluyen moneda, número de seguro social, porcentajes, decimales, fechas, números de teléfono, códigos postales, etc.

Entonces, la forma correcta de mostrar el valor de la celda numérica es la siguiente:

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.


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(); } }


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