我正在尝试从 Excel 工作表中读取一个值,并通过比较 webelement 中的值将其输入到文本字段中。
如何从单元格中获取此值作为字符串而不是数字?下面给出了读写excel的代码
public String getValueFromCell(int iRowNumber, int iColNumber)
{
XSSFRow row = sheet.getRow(iRowNumber);
Cell cell = row.getCell(iColNumber);
return cell == null ? "" : cell.toString();
}
/**
* returns no. of rows of excel sheet
*
* @return
*/
public int getRowCount()
{
return sheet.getLastRowNum();
}
/**
* returns no. of columns of excel sheet
*
* @param sheetName
* @return
*/
public int getColumnCount(String sheetName)
{
sheet = workbook.getSheet(sheetName);
row = sheet.getRow(0);
return row.getLastCellNum();
}
/**
* return row number of a String value
*
* @param value
* @return
*/
public int getRowNumber(String value)
{
XSSFSheet indexsheet = workbook.getSheet("Index");
for(int i = 0; i <= indexsheet.getLastRowNum(); i++)
{
row = indexsheet.getRow(i);
if(value.equalsIgnoreCase(row.getCell(0).getStringCellValue()))
{
return i + 1;
}
}
return 0;
}
/**
* sets data in a cell
*
* @param path
* @param sheetName
* @param colName
* @param rowNum
* @param data
* @return
*/
public boolean setCellData(String path, String sheetName, String colName, int rowNum, String data)
{
try
{
if(rowNum <= 0)
return false;
int index = workbook.getSheetIndex(sheetName);
int colNum = -1;
if(index == -1)
return false;
sheet = workbook.getSheetAt(index);
row = sheet.getRow(0);
for(int i = 0; i < row.getLastCellNum(); i++)
{
if(row.getCell(i).getStringCellValue().trim().equals(colName))
colNum = i;
}
if(colNum == -1)
return false;
sheet.autoSizeColumn(colNum);
row = sheet.getRow(rowNum - 1);
if(row == null)
row = sheet.createRow(rowNum - 1);
cell = row.getCell(colNum);
if(cell == null)
cell = row.createCell(colNum);
cell.setCellValue(data);
}
catch(Exception e)
{
e.printStackTrace();
return false;
}
return true;
}
}
据我所知,我们可以通过两种方式实现这一目标。
方法一: Excel 数值前加撇号(')。例如,如果您在 excel 中有 1234,则替换为 '1234。添加撇号会将数字转换为字符串。
方法二:通过Java处理。例如,做这样的事情,
String value = new String("value read from Excel");
注意:我还没有测试过方法 2,但它确实有效。
希望这可以帮助。谢谢。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句