跳至页脚内容
EXCEL 工具

如何在 Java 中读取 Excel 文件(教程)

什么是Excel?

Microsoft Excel工作簿是一种基于电子表格的软件,可以让用户高效地组织和存储数据。 它以表格形式存储和组织数据,即使用行和列。 Excel电子表格中的单元格是保存数据的框,可以使用不同的样式、格式和公式进行操作。

如何在Java中读取Excel文件?

有时候读取Excel文件可能会很复杂。 在Java中读取Excel文件与读取Word文件有点不同,因为Excel有单元格。 JDK没有提供直接读取或写入Microsoft Excel文档的API。 相反,我们必须依赖第三方库Apache POI

Apache POI库

POI代表“Poor Obfuscation Implementation”。Apache POI是一个开源Java库,设计用于读取和写入Microsoft文档。 它提供了一种基于Microsoft Office创建和操作各种文件格式的方法。使用Apache POI,一个人应该能够在一系列Microsoft Office文件格式上进行创建、修改和显示/读取操作。

下载并安装Apache POI库

首先,我们将下载最新版本的POI JARs。 导航到http://poi.apache.org/download.html并下载最新的ZIP文件,其中将包含在Java中读取Excel文件的Java API。

class="content-img-align-center">
class="center-image-wrapper"> How to Read Excel Files in Java, Figure 1: Download Binary Distribution File

class="content__image-caption">下载Apache POI JAR文件

当您下载ZIP文件时,您需要解压缩它并将以下JAR文件添加到项目的classpath中。 这在下面的从Excel文件读取进行了解释。

class="content-img-align-center">
class="center-image-wrapper"> How to Read Excel Files in Java, Figure 2: JAR Files

class="content__image-caption">将Apache POI Jar文件添加到Java classpath中

注意:还需复制libooxml-lib中的文件以及其他文件。

POI中的类和接口

以下是可以使用的支持XLS和XLSX文件格式的类列表:

class="content-img-align-center">
class="center-image-wrapper"> How to Read Excel Files in Java, Figure 3: Apache POI Classes

class="content__image-caption">Apache 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文件读取

在我们的例子中,我们将在Java中读取以下Excel文件:

class="content-img-align-center">
class="center-image-wrapper"> How to Read Excel Files in Java, Figure 4: The Excel File to be Read

class="content__image-caption">将读取的Excel文件

在Java中读取Excel文件的步骤

  1. 使用任何Java IDE创建一个Java项目。我们将在这个项目中使用Netbeans。
  2. 接下来,在项目中创建一个lib文件夹。
  3. 然后,将下载的JAR文件添加到上一步创建的lib文件夹中。
  4. 设置Class-Path,方法是右键单击项目文件夹 > 构建路径 > 添加外部JARs文件 > 选择所有上述JAR文件 > 应用并关闭。
  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”可以被使用,但有.xslx的扩展名。
  • 其次,我们导入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是一个独立的.NET库,通过C#便于读取和编辑Microsoft Excel文档。 它既不需要安装Microsoft Excel,也不依赖于Interop。

通过使用IronXL,开发人员可以通过编写几行代码和快速的性能轻松处理所有与Excel相关的计算。 这可能是用于诸如增加两个单元格、计算列的总和、将整个列添加到Excel表格、将整个行添加到Excel表格中、单列和多列行求和,或其他许多通过IronXL的有用功能轻松完成的任务。

IronXL完全支持.NET Framework、.NET Core、移动、Xamarin、Azure Linux和macOS。

IronXL功能集

  • 加载、读取和编辑来自XLS/XLSX/CSV/TSV的数据。
  • 保存和导出到XLS/XLSX/CSV/TSV/JSON。
  • System.Data对象 —— 作为System.Data.DataSetSystem.Data.DataTable对象处理Excel电子表格。
  • 公式 —— 与Excel公式一起工作。
  • 范围 —— ["A1:B10"]语法易于使用。
  • 排序 —— 排序行、列和范围。
  • 样式 —— 视觉样式、字体和字体大小、背景图案、边框、对齐和数字格式。

以下是在C#中使用IronXL读取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);
        }
    }
}
Imports IronXL
Imports System.Linq

Public Class ExcelReaderExample
	Public Shared Sub Main(ByVal args() As String)
		' Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
		Dim workbook As WorkBook = WorkBook.Load("test.xlsx")
		Dim sheet As WorkSheet = workbook.WorkSheets.First()

		' Select cells easily in Excel notation and return the calculated value
		Dim cellValue As Integer = sheet("A2").IntValue

		' Read from Ranges of cells elegantly
		For Each cell In sheet("A2:A10")
			Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
		Next cell
	End Sub
End Class
$vbLabelText   $csharpLabel

使用IronXL使得开发者的工作变得更加轻松。 其简单且易于使用的代码使得软件在处理Excel文件时不易产生错误。

下载IronXL并今天就将它用于您的项目。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。