programing

처음 두 행을 제외한 엑셀 파일을 읽는 방법

stoneblock 2023. 7. 13. 20:21

처음 두 행을 제외한 엑셀 파일을 읽는 방법

저는 111줄의 엑셀 파일을 가지고 있습니다.나는 시트의 처음 두 줄을 생략하고 자바와 POI를 사용하여 파일을 읽어야 합니다.

다음을 사용하여 처음 두 행을 건너뜁니다.rownum()여기 샘플 코드가 있습니다.

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

다음은 완전한 예입니다.

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

Apache POI는 Excel 파일의 행과 셀에 액세스하는 두 가지 방법을 제공합니다.하나는 모든 항목을 제공하는 반복기이고, 다른 하나는 인덱스별로 루프업합니다. (POI는 시작/끝 행/열도 알려줍니다.)반복기는 종종 사용하기가 더 간단하지만 둘 다 똑같이 빠릅니다.

가져올 행에 대한 특정 요구 사항이 있으면 후자를 사용하는 것이 좋습니다.코드는 다음과 같습니다.

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

답변에서 벽화를 개선할 수 있습니다.예를 들어 40개 행을 건너뛰려면 다음을 사용합니다.

if (currentRow.getRowNum() <= 40) {
                    continue;
                }

언급URL : https://stackoverflow.com/questions/13639374/how-to-read-excel-file-omitting-first-two-rows