EXCEL 工具

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

发布 2023年二月23日
分享:

Excel 是什么?

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

如何用 Java 读取 Excel 文件?

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

Apache POI 库

POI 是 "Poor Obfuscation Implementation" 的缩写。 Apache POI 是一个开源 Java 库,用于读写微软文档。它提供了一种创建和操作基于 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 类

下面列出了 POI 中不同的 Java 接口和类,用于用 Java 读取 XLSXLSX 文件:

工作簿接口由 HSSFWorkbookXSSFWorkbook 类实现。

  • HSSFWorkbook:这是 XLS 文件的类表示。
  • XSSFWorkbook:这是 XLSX 文件的类表示。

Sheet 接口由 HSSFSheetXSSFSheet 类实现。

  • HSSFSheet:这是一个表示 XLS 文件中工作表的类。
  • XSSFSheet:这是一个表示 XLSX 文件中工作表的类。

行接口由 HSSFRowXSSFRow 类实现。

  • HSSFRow:这是一个表示 XLS 文件工作表中一行的类。
  • XSSFRow:该类表示 XLSX 文件工作表中的一行。

单元格接口由 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 文件">"应用并关闭",设置 "类路径"。

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

输出:

IdNames
1Zeeshan
2Shoaib
3Umar
4Rizwan
5Ahsan

IronXL C# 库

IronXL 是一个独立的.NET 库,便于使用 C# 阅读和编辑 Microsoft Excel 文档。它既不要求安装 Microsoft Excel,也不依赖于 Interop.NET Framework。

使用 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 对象--以 System.Data.DataSetSystem.Data.DataTable 对象的形式处理 Excel 电子表格。
  • 公式 - 可使用 Excel 公式。
  • 范围["A1:B10] 语法易于使用。
  • 排序 - 对行、列和范围进行排序。

  • 样式 - 视觉样式、字体和字体大小、背景图案、边框、对齐方式和数字格式。

以下是使用 IronXL 在 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
VB   C#

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

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

< 前一页
.NET 正则表达式测试器(开发人员使用方法)
下一步 >
如何在Excel中切换列

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 988,189 查看许可证 >