POI - Traverse the rows and columns of a workbook to get the contents of a cell

foreword

This article is mainly to read Excel documents and read content by traversing rows and columns. Among them, the content type of the cell needs to be judged and read separately.

example

public static void main(String[] args) throws Exception
{
  //input stream
  InputStream is = new FileInputStream("f:\\poi\\ffff.xls");
  //File system
  POIFSFileSystem fs = new POIFSFileSystem(is);
  //define the workbook
  HSSFWorkbook wb = new HSSFWorkbook(fs);
  //Get the first sheet page
  HSSFSheet hssfSheet = wb.getSheetAt(0);
  if(hssfSheet == null){
    return;
  }
  
  //traverse row row
  for(int rowNum = 0; rowNum<=hssfSheet.getLastRowNum();rowNum++){
    // get each row
    HSSFRow row = hssfSheet.getRow(rowNum);
    if(row == null){
      continue;
    }
    
    //traverse the column cell
    for(int cellNum = 0; cellNum<=row.getLastCellNum();cellNum++){
      // get each column
      HSSFCell cell = row.getCell(cellNum);
      if(cell == null){
        continue;
      }
      
      System.out.print(" "+getValue(cell));
    }
    System.out.println();
  }
  
}
/**
 * Different types correspond to different value ranges
 * @param cell
 * @return
 */
private static String getValue(HSSFCell cell){
  if(cell.getCellType()==HSSFCell.CELL_TYPE_BOOLEAN){
    return String.valueOf(cell.getBooleanCellValue());
  }else if(cell.getCellType()==HSSFCell.CELL_TYPE_NUMERIC){
    return String.valueOf(cell.getNumericCellValue());
  }
  
    return String.valueOf(cell.getStringCellValue());
}

Summary: The method of reading the value here is not very perfect. When reading the value of the number, the integer will read the decimal point.



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324599685&siteId=291194637