EXCEL 工具

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

什么是 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 是一个开源的 Java 库,旨在用于读取和写入 Microsoft 文档。 它提供了一种基于 Microsoft Office 创建和处理各种文件格式的方法。使用 Apache POI,人们应该能够对一系列 Microsoft Office 文件格式执行创建、修改和显示/读取操作。

下载并安装 Apache POI 库

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

如何用 Java 读取 Excel 文件,图 1:下载二进制分发文件

下载 Apache POI JAR 文件

下载 ZIP 文件后,需要解压缩并将以下 JAR 文件添加到项目的类路径中。 这在下面的从Excel文件读取中进行了说明。

如何用 Java 读取 Excel 文件,图 2:JAR 文件

将 Apache POI Jar 文件添加到 Java classpath 中

注意:还需要将 lib 和 ooxml-lib 中的文件与其他文件一起复制。

POI 中的类和接口

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

How to Read Excel Files in Java, Figure 3: 阿帕奇 POI 类

阿帕奇 POI 类

以下是 Java 中用于读取 XLSXLSX 文件的 POI 中不同接口和类的列表:

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 文件:

如何用 Java 读取 Excel 文件,图 4:要读取的 Excel 文件

将读取的 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  {  
        //obtaining 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 Cell.CELL_TYPE_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 Cell.CELL_TYPE_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();  
        }
    }
}
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  {  
        //obtaining 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 Cell.CELL_TYPE_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 Cell.CELL_TYPE_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();  
        }
    }
}
JAVA

输出:

IdNames
1Zeeshan
2Shoaib
3Umar
4Rizwan
5Ahsan

除以下两个要点外,阅读 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); 
            Iterator<Row> itr = sheet.iterator();
            while (itr.hasNext()) {  
                Row row = itr.next();  
                Iterator<Cell> cellIterator = row.cellIterator();   //iterating over each column  
                while (cellIterator.hasNext()) {  
                    Cell cell = cellIterator.next();  
                    switch (cell.getCellType()) {  
                        case Cell.CELL_TYPE_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 Cell.CELL_TYPE_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("");  
            }  
        } 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); 
            Iterator<Row> itr = sheet.iterator();
            while (itr.hasNext()) {  
                Row row = itr.next();  
                Iterator<Cell> cellIterator = row.cellIterator();   //iterating over each column  
                while (cellIterator.hasNext()) {  
                    Cell cell = cellIterator.next();  
                    switch (cell.getCellType()) {  
                        case Cell.CELL_TYPE_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 Cell.CELL_TYPE_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("");  
            }  
        } catch(Exception e) {  
            e.printStackTrace();  
        }
    }
}
JAVA

输出:

IdNames
1Zeeshan
2Shoaib
3Umar
4Rizwan
5Ahsan

IronXL C# 库

IronXL 是一个独立的 .NET 库,可用 C# 读取和编辑 Microsoft Excel 文档。 译文既不要求安装 Microsoft Excel,也不依赖 Interop。

使用 IronXL.Excel,开发人员只需编写几行代码,就能毫不费力地执行所有与 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 对象——以 System.Data.DataSetSystem.Data.DataTable 对象的形式处理 Excel 电子表格。
  • 公式 - 可使用 Excel 公式。
  • 范围 — ["A1:B10"] 语法易于使用。
  • 排序 - 对行、列和范围进行排序。
  • 样式 - 视觉样式、字体和字体大小、背景图案、边框、对齐方式和数字格式。

    以下是使用 IronXL.Excel 在 C# 中读取 Excel 文件的代码示例:

using IronXL;
using System.Linq;

//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;

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

'Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
Private workbook As WorkBook = WorkBook.Load("test.xlsx")
Private sheet As WorkSheet = workbook.WorkSheets.First()

'Select cells easily in Excel notation and return the calculated value
Private 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
$vbLabelText   $csharpLabel

与 IronXL 合作,开发人员的工作将变得更加轻松。 其代码简单易用,使软件在处理 Excel 文件时不易出现错误。

下载 IronXL 并立即将其用于您的项目。

雷根·彭
软件工程师
Regan毕业于雷丁大学,拥有电子工程学士学位。在加入Iron Software之前,他的前工作职位要求他专注于单一任务;他在Iron Software最喜欢的是能进行多种工作,无论是增加销售价值、技术支持、产品开发还是营销。他喜欢了解开发人员如何使用Iron Software的库,并利用这些知识不断改进文档和开发产品。
< 前一页
使用 .NET Regex Tester 测试您的 Regex 模式
下一步 >
如何在Excel中切换列