푸터 콘텐츠로 바로가기
엑셀 도구

자바에서 엑셀 파일을 읽는 방법 (튜토리얼)

Excel이란 무엇인가요?

Microsoft Excel 워크북은 사용자가 데이터를 효율적으로 조직하고 저장할 수 있는 스프레드시트 기반 소프트웨어입니다. 데이터를 행과 열을 사용하여 표 형식으로 저장하고 구성합니다. Excel 스프레드시트의 셀은 데이터를 저장하는 상자이며, 다양한 스타일, 서식 및 수식을 사용하여 조작할 수 있습니다.

Java에서 Excel 파일을 읽는 방법?

Excel 파일 읽기는 때때로 복잡할 수 있습니다. Excel 파일을 Java에서 읽는 것은 Excel의 셀 때문에 Java에서 Word 파일을 읽는 것과 약간 다릅니다. JDK는 Microsoft Excel 문서를 읽거나 쓰기 위한 직접적인 API를 제공하지 않습니다. 대신, 우리는 서드파티 라이브러리 Apache POI에 의존해야 합니다.

Apache POI 라이브러리

POI는 "Poor Obfuscation Implementation"의 약자입니다. Apache POI는 Microsoft 문서를 읽고 쓰기 위한 오픈 소스 Java 라이브러리입니다. Microsoft Office를 기반으로 한 다양한 파일 형식을 만들고 조작하는 방법을 제공합니다. Apache POI를 사용하여 Microsoft Office 파일 형식의 범위에서 만들기, 수정 및 디스플레이/읽기 작업을 수행할 수 있어야 합니다.

Apache POI 라이브러리 다운로드 및 설치

우선, POI JAR의 최신 버전을 다운로드합니다. http://poi.apache.org/download.html로 이동하여 Java에서 Excel 파일을 읽기 위한 Java API를 포함한 최신 ZIP 파일을 다운로드하십시오.

How to Read Excel Files in Java, Figure 1: Download Binary Distribution File

Apache POI JAR 파일 다운로드

ZIP 파일을 다운로드하면, 그것을 압축 해제하고 다음 JAR 파일을 프로젝트의 클래스 경로에 추가해야 합니다. 아래의 Excel 파일에서 읽기에서 설명합니다.

How to Read Excel Files in Java, Figure 2: JAR Files

Apache POI Jar 파일을 Java 클래스 경로에 추가하기

참고: 다른 파일들과 함께 libooxml-lib 파일도 복사하십시오.

POI의 클래스 및 인터페이스

다음은 사용 가능한 XLS 및 XLSX 파일 형식 지원 클래스입니다:

How to Read Excel Files in Java, Figure 3: Apache POI 클래스

Apache POI 클래스

POI에서 Java로 XLSXLSX 파일을 읽기 위한 다양한 Java 인터페이스와 클래스 목록은 다음과 같습니다:

Workbook 인터페이스는 HSSFWorkbookXSSFWorkbook 클래스에 의해 구현됩니다:

  • HSSFWorkbook: 이것은 XLS 파일의 클래스 표현입니다.
  • XSSFWorkbook: 이것은 XLSX 파일의 클래스 표현입니다.

Sheet 인터페이스는 HSSFSheetXSSFSheet 클래스에 의해 구현됩니다:

  • HSSFSheet: 이것은 XLS 파일의 시트를 나타내는 클래스입니다.
  • XSSFSheet: 이것은 XLSX 파일의 시트를 나타내는 클래스입니다.

Row 인터페이스는 HSSFRowXSSFRow 클래스에 의해 구현됩니다:

  • HSSFRow: 이것은 XLS 파일의 시트에 있는 행을 나타내는 클래스입니다.
  • XSSFRow: 이것은 XLSX 파일의 시트에 있는 행을 나타내는 클래스입니다.

Cell 인터페이스는 HSSFCellXSSFCell 클래스에 의해 구현됩니다:

  • HSSFCell: 이것은 XLS 파일 행의 셀을 나타내는 클래스입니다.
  • XSSFCell: 이것은 XLSX 파일 행의 셀을 나타내는 클래스입니다.

Excel 파일에서 읽기

예제에서는 다음과 같은 Excel 파일을 Java에서 읽겠습니다:

How to Read Excel Files in Java, Figure 4: The Excel File to be Read

읽을 Excel 파일

Java에서 Excel 파일 읽기 단계

  1. Java IDE를 사용하여 Java 프로젝트를 만듭니다. 이 프로젝트에서는 Netbeans를 사용할 것입니다.
  2. 다음으로, 프로젝트에 lib 폴더를 만드십시오.
  3. 그런 다음, 다운로드한 JAR 파일들을 이전 단계에서 생성한 lib 폴더에 추가하십시오.
  4. 프로젝트 폴더 오른쪽 클릭 > 빌드 경로 설정 > 외부 JAR 파일 추가 > 위의 모든 JAR 파일 선택 > 적용 및 닫기를 통해 Class-Path을 설정하십시오.
  5. 이제 ReadExcelFileDemo라는 클래스 파일을 만듭니다.
  6. 'studentdata.xls'라는 이름의 Excel 파일을 만들고 위의 데이터 또는 다른 데이터를 작성합니다.

Java에서 Excel 파일을 읽기 위한 코드 샘플은 다음과 같습니다:

import java.io.File;  
import java.io.FileInputStream;  
import java.io.IOException;  
import org.apache.poi.hssf.usermodel.HSSFSheet;  
import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
import org.apache.poi.ss.usermodel.Cell;  
import org.apache.poi.ss.usermodel.FormulaEvaluator;  
import org.apache.poi.ss.usermodel.Row;  

public class ReadExcelFileDemo  {  
    public static void main(String[] args) throws IOException {  
        // Obtain input bytes from a file  
        FileInputStream fis = new FileInputStream(new File("C:\\demo\\studentdata.xls"));  

        // Creating workbook instance that refers to .xls file  
        HSSFWorkbook wb = new HSSFWorkbook(fis);   

        // Creating a Sheet object to retrieve the object  
        HSSFSheet sheet = wb.getSheetAt(0);  

        // Evaluating cell type   
        FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();  
        for (Row row : sheet) {  
            for (Cell cell : row) {
                switch (formulaEvaluator.evaluateInCell(cell).getCellType()) {  
                    case NUMERIC: // Field that represents numeric cell type  
                        // Getting the value of the cell as a number  
                        System.out.print(cell.getNumericCellValue() + "\t\t");   
                        break;  
                    case STRING: // Field that represents string cell type  
                        // Getting the value of the cell as a string  
                        System.out.print(cell.getStringCellValue() + "\t\t");  
                        break;
                }
            }
            System.out.println();  
        }

        // Closing the workbook to free resources
        wb.close();
    }
}
import java.io.File;  
import java.io.FileInputStream;  
import java.io.IOException;  
import org.apache.poi.hssf.usermodel.HSSFSheet;  
import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
import org.apache.poi.ss.usermodel.Cell;  
import org.apache.poi.ss.usermodel.FormulaEvaluator;  
import org.apache.poi.ss.usermodel.Row;  

public class ReadExcelFileDemo  {  
    public static void main(String[] args) throws IOException {  
        // Obtain input bytes from a file  
        FileInputStream fis = new FileInputStream(new File("C:\\demo\\studentdata.xls"));  

        // Creating workbook instance that refers to .xls file  
        HSSFWorkbook wb = new HSSFWorkbook(fis);   

        // Creating a Sheet object to retrieve the object  
        HSSFSheet sheet = wb.getSheetAt(0);  

        // Evaluating cell type   
        FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();  
        for (Row row : sheet) {  
            for (Cell cell : row) {
                switch (formulaEvaluator.evaluateInCell(cell).getCellType()) {  
                    case NUMERIC: // Field that represents numeric cell type  
                        // Getting the value of the cell as a number  
                        System.out.print(cell.getNumericCellValue() + "\t\t");   
                        break;  
                    case STRING: // Field that represents string cell type  
                        // Getting the value of the cell as a string  
                        System.out.print(cell.getStringCellValue() + "\t\t");  
                        break;
                }
            }
            System.out.println();  
        }

        // Closing the workbook to free resources
        wb.close();
    }
}
JAVA

산출:

Id    Names
1     Zeeshan
2     Shoaib
3     Umar
4     Rizwan
5     Ahsan
Id    Names
1     Zeeshan
2     Shoaib
3     Umar
4     Rizwan
5     Ahsan
SHELL

XLSX 파일을 읽는 단계는 같은데, 아래 두 가지 주요 점에서 다릅니다:

  • 첫째, 파일 형식을 .xlsx로 변경합니다. 같은 파일 'studentdata'를 사용할 수 있지만 .xlsx 확장자를 사용해야 합니다.
  • 둘째, Java Apache POI를 가져오는 방식에서 차이가 있습니다. 코드는 다음과 같습니다.
import java.io.File;  
import java.io.FileInputStream;  
import java.util.Iterator;  
import org.apache.poi.ss.usermodel.Cell;  
import org.apache.poi.ss.usermodel.Row;  
import org.apache.poi.xssf.usermodel.XSSFSheet;  
import org.apache.poi.xssf.usermodel.XSSFWorkbook;  

public class XLSXReaderExample  {

    public static void main(String[] args) {  
        try {  
            File file = new File("C:\\demo\\studentdata.xlsx");  
            FileInputStream fis = new FileInputStream(file);  

            // Creating Workbook instance that refers to .xlsx file  
            XSSFWorkbook wb = new XSSFWorkbook(fis);   
            XSSFSheet sheet = wb.getSheetAt(0); 

            // Iterating over rows using iterator
            Iterator<Row> itr = sheet.iterator();
            while (itr.hasNext()) {  
                Row row = itr.next();  

                // Iterating over each column in a row
                Iterator<Cell> cellIterator = row.cellIterator();   
                while (cellIterator.hasNext()) {  
                    Cell cell = cellIterator.next();  
                    switch (cell.getCellType()) {  
                        case NUMERIC: // Field that represents numeric cell type  
                            // Getting the value of the cell as a number  
                            System.out.print(cell.getNumericCellValue() + "\t\t");   
                            break;
                        case STRING: // Field that represents string cell type  
                            // Getting the value of the cell as a string  
                            System.out.print(cell.getStringCellValue() + "\t\t");  
                            break;
                    }
                }
                System.out.println("");  
            }  

            // Closing the workbook to free resources
            wb.close();
        } catch (Exception e) {  
            e.printStackTrace();  
        }
    }
}
import java.io.File;  
import java.io.FileInputStream;  
import java.util.Iterator;  
import org.apache.poi.ss.usermodel.Cell;  
import org.apache.poi.ss.usermodel.Row;  
import org.apache.poi.xssf.usermodel.XSSFSheet;  
import org.apache.poi.xssf.usermodel.XSSFWorkbook;  

public class XLSXReaderExample  {

    public static void main(String[] args) {  
        try {  
            File file = new File("C:\\demo\\studentdata.xlsx");  
            FileInputStream fis = new FileInputStream(file);  

            // Creating Workbook instance that refers to .xlsx file  
            XSSFWorkbook wb = new XSSFWorkbook(fis);   
            XSSFSheet sheet = wb.getSheetAt(0); 

            // Iterating over rows using iterator
            Iterator<Row> itr = sheet.iterator();
            while (itr.hasNext()) {  
                Row row = itr.next();  

                // Iterating over each column in a row
                Iterator<Cell> cellIterator = row.cellIterator();   
                while (cellIterator.hasNext()) {  
                    Cell cell = cellIterator.next();  
                    switch (cell.getCellType()) {  
                        case NUMERIC: // Field that represents numeric cell type  
                            // Getting the value of the cell as a number  
                            System.out.print(cell.getNumericCellValue() + "\t\t");   
                            break;
                        case STRING: // Field that represents string cell type  
                            // Getting the value of the cell as a string  
                            System.out.print(cell.getStringCellValue() + "\t\t");  
                            break;
                    }
                }
                System.out.println("");  
            }  

            // Closing the workbook to free resources
            wb.close();
        } catch (Exception e) {  
            e.printStackTrace();  
        }
    }
}
JAVA

산출:

Id    Names
1     Zeeshan
2     Shoaib
3     Umar
4     Rizwan
5     Ahsan
Id    Names
1     Zeeshan
2     Shoaib
3     Umar
4     Rizwan
5     Ahsan
SHELL

IronXL C# 라이브러리

IronXL은 C#으로 Microsoft Excel 문서를 읽고 편집할 수 있게 해주는 독립형 .NET 라이브러리입니다. Microsoft Excel이 설치되어 있지 않아도 되고 Interop에 의존하지도 않습니다.

IronXL을 사용하여 개발자는 간단히 몇 줄의 코드로 모든 Excel 관련 계산을 쉽게 수행하고 빠른 성능을 제공합니다. 이것은 두 셀을 더하거나, 열의 총합을 계산하거나, Excel 테이블에 전체 열을 추가하거나, Excel 테이블에 전체 행을 추가하거나, 단일 및 다중 행 열 합계를 수행하거나, IronXL의 유용한 기능을 통해 쉽게 수행할 수 있는 많은 다른 작업들이 될 수 있습니다.

IronXL은 .NET Framework, .NET Core, Mobile, Xamarin, Azure Linux 및 macOS를 완전히 지원합니다.

IronXL 기능 세트

  • XLS/XLSX/CSV/TSV에서 데이터 로드, 읽기 및 편집하기.
  • XLS/XLSX/CSV/TSV/JSON으로 저장 및 내보내기.
  • System.Data 객체 — Excel 스프레드시트를 System.Data.DataSetSystem.Data.DataTable 객체로 작업하십시오.
  • 수식 — Excel 수식과 작업.
  • 범위 — ["A1:B10"] 구문은 사용하기 쉬움.
  • 정렬 — 행, 열 및 범위 정렬.
  • 스타일 — 시각적 스타일, 글꼴과 글꼴 크기, 배경 패턴, 테두리, 정렬 및 숫자 형식.

아래는 IronXL을 사용하여 C#에서 Excel 파일을 읽는 코드 예제입니다:

using IronXL;
using System.Linq;

public class ExcelReaderExample
{
    public static void Main(string[] args)
    {
        // Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
        WorkBook workbook = WorkBook.Load("test.xlsx");
        WorkSheet sheet = workbook.WorkSheets.First();

        // Select cells easily in Excel notation and return the calculated value
        int cellValue = sheet["A2"].IntValue;

        // Read from Ranges of cells elegantly
        foreach (var cell in sheet["A2:A10"]) {
            Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
        }
    }
}
using IronXL;
using System.Linq;

public class ExcelReaderExample
{
    public static void Main(string[] args)
    {
        // Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
        WorkBook workbook = WorkBook.Load("test.xlsx");
        WorkSheet sheet = workbook.WorkSheets.First();

        // Select cells easily in Excel notation and return the calculated value
        int cellValue = sheet["A2"].IntValue;

        // Read from Ranges of cells elegantly
        foreach (var cell in sheet["A2:A10"]) {
            Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
        }
    }
}
$vbLabelText   $csharpLabel

IronXL을 사용하면 개발자의 작업이 훨씬 쉬워집니다. 그 간단하고 사용하기 쉬운 코드 덕분에 소프트웨어가 Excel 파일과 작업할 때 버그에 더 적게 노출됩니다.

IronXL 다운로드하여 지금 프로젝트에 사용하세요.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me