web-dev-qa-db-fra.com

Comment lire un fichier Excel en omettant les deux premières lignes

J'ai un fichier Excel de 111 lignes. Je dois omettre les deux premières lignes de la feuille, puis lire le fichier en utilisant Java et POI.

13
Priya

Vous devez ignorer les deux premières lignes à l'aide de rownum(). Voici l'exemple de code

HSSFWorkbook      workBook = new HSSFWorkbook (fileSystem);
HSSFSheet         sheet    = workBook.getSheetAt (0);
Iterator<HSSFRow> rows     = sheet.rowIterator ();

while (rows.hasNext ())
{
  HSSFRow row = rows.next ();
  // display row number in the console.
  System.out.println ("Row No.: " + row.getRowNum ());
  if(row.getRowNum()==0 || row.getRowNum()==1){
   continue; //just skip the rows if row number is 0 or 1
  }
}

Voici l'exemple complet

import org.Apache.poi.hssf.usermodel.HSSFCell;
import org.Apache.poi.hssf.usermodel.HSSFRichTextString;
import org.Apache.poi.hssf.usermodel.HSSFRow;
import org.Apache.poi.hssf.usermodel.HSSFSheet;
import org.Apache.poi.hssf.usermodel.HSSFWorkbook;
import org.Apache.poi.poifs.filesystem.POIFSFileSystem; 
import Java.io.FileInputStream;
import Java.io.FileNotFoundException;
import Java.io.IOException;
import Java.io.InputStream;

import Java.util.Iterator;

public class POIExcelReader
{

/** Creates a new instance of POIExcelReader */
public POIExcelReader ()
{}

@SuppressWarnings ("unchecked")
public void displayFromExcel (String xlsPath)
{
InputStream inputStream = null;

try
{
inputStream = new FileInputStream (xlsPath);
}
catch (FileNotFoundException e)
{
System.out.println ("File not found in the specified path.");
e.printStackTrace ();
}

POIFSFileSystem fileSystem = null;

try
{
fileSystem = new POIFSFileSystem (inputStream);

HSSFWorkbook      workBook = new HSSFWorkbook (fileSystem);
HSSFSheet         sheet    = workBook.getSheetAt (0);
Iterator<HSSFRow> rows     = sheet.rowIterator ();

while (rows.hasNext ())
{
HSSFRow row = rows.next ();
if(row.getRowNum()==0 || row.getRowNum()==1){
       continue; //just skip the rows if row number is 0 or 1
      }
// once get a row its time to iterate through cells.
Iterator<HSSFCell> cells = row.cellIterator ();

while (cells.hasNext ())
{
HSSFCell cell = cells.next ();

System.out.println ("Cell No.: " + cell.getCellNum ());

/*
 * Now we will get the cell type and display the values
 * accordingly.
 */
switch (cell.getCellType ())
{
    case HSSFCell.CELL_TYPE_NUMERIC :
    {

        // cell type numeric.
        System.out.println ("Numeric value: " + cell.getNumericCellValue ());

        break;
    }

    case HSSFCell.CELL_TYPE_STRING :
    {

        // cell type string.
        HSSFRichTextString richTextString = cell.getRichStringCellValue ();

        System.out.println ("String value: " + richTextString.getString ());

        break;
    }

    default :
    {

        // types other than String and Numeric.
        System.out.println ("Type not supported.");

        break;
    }
}
}
}
}
catch (IOException e)
{
e.printStackTrace ();
}
}

public static void main (String[] args)
{
POIExcelReader poiExample = new POIExcelReader ();
String         xlsPath    = "c://test//test.xls";

poiExample.displayFromExcel (xlsPath);
}
}
32
Murali Prasanth

Apache POI propose deux façons d'accéder aux lignes et aux cellules d'un fichier Excel. L'un est un itérateur qui vous donne toutes les entrées, l'autre consiste à boucler par index. (POI vous indiquera également les lignes/colonnes de début/fin). L'itérateur est souvent plus simple à utiliser, mais les deux sont tout aussi rapides.

Si vous avez des exigences spécifiques sur les lignes à récupérer, je vous suggère d'utiliser cette dernière. Votre code voudrait être quelque chose comme:

int FIRST_ROW_TO_GET = 2; // 0 based

Sheet s = wb.getSheetAt(0);
for (int i = FIRST_ROW_TO_GET; i < s.getLastRowNum(); i++) {
   Row row = s.getRow(i);
   if (row == null) {
      // The whole row is blank
   }
   else {
      for (int cn=row.getFirstCellNum(); cn<row.getLastCellNum(); cn++) {
         Cell c = row.getCell(cn, Row.RETURN_BLANK_AS_NULL);
         if (c == null) {
            // The cell is empty
         } else {
            // Process the cell
         }
      }
   }
}
6
Gagravarr