如何将 hssfcell 转换为 java 中的字符串

how to convert hssfcell to string in java

我有一段代码让我很困惑(我把这行加粗了)

Exception in thread "main" java.lang.ClassCastException: org.apache.poi.hssf.usermodel.HSSFCell cannot be cast to java.lang.String
    at com.codi.excel.ExcelRead.main(ExcelRead.java:36)

我的代码如下-

HSSFWorkbook wb = new HSSFWorkbook(input);
            HSSFSheet sheet = wb.getSheetAt(0);
            List MobileSeries=new ArrayList();
            MobileSeries = findRow(sheet, cellContent);

            if(MobileSeries !=null){
                for(Iterator iter=MobileSeries.iterator();iter.hasNext();){
                    **String mobileSeries=(String)iter.next();**
                    String LidPattern=extractNumber(mobileSeries);
                    if (lid.startsWith(LidPattern)) {
                    System.out.println("This is a mobile number");

你能帮帮我吗

尝试访问单元格并从中提取值。以下代码段应该对您有所帮助:

Cell cell = iter.next();
cell.getStringCellValue()

在迭代工作表的行时,检查 HSSFCell 单元格是否属于 String 类型。

InputStream fileInputStream = null;
HSSFWorkbook hssfWorkbook;
HSSFSheet sheet;
HSSFRow row;
HSSFCell cell;
Iterator rowIterator, cellIterator;

// Put these loc in a try-catch block
fileInputStream = new FileInputStream("/path/to/TestExcel.xls");
hssfWorkbook = new HSSFWorkbook(fileInputStream);
sheet = hssfWorkbook.getSheetAt(0);
rowIterator = sheet.rowIterator();

while (rowIterator.hasNext()) {
    row = (HSSFRow) rowIterator.next();
    cellIterator = row.cellIterator();
    while (cellIterator.hasNext()) {
        cell = (HSSFCell) cellIterator.next();

        if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
            String someVariable = cell.getStringCellValue();
        } else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
            // Handle numeric type
        } else {
          // Handle other types
        }
    }
    // Other code
}

Apache POI 为您提供了方便的 class 来做到这一点 - DataFormatter

使用 DataFormatter,对于字符串单元格,您将获得当前内容,对于数字或日期单元格,值将根据应用于单元格的格式/样式规则进行格式化,然后作为已应用的字符串。

要遍历工作簿中的所有行和单元格,获取它们的值,following the pattern in the docs,只需执行如下操作:

Workbook wb = WorkbookFactory.create(input);
Sheet sheet = wb.getSheetAt(0);
DataFormatter formatter = new DataFormatter();
for (Row r : sheet) {
   for (Cell c : r) {
       String value = formatter.formatCellValue(c);
   }
}

简单!