在Java中读取Excel中的数据
在实际开发过程中,经常会遇到需要从Excel中读取数据的情况。在Java中,我们可以通过一些库来实现这个功能,比如Apache POI。本文将介绍如何使用Apache POI来读取Excel中的数据。
Apache POI简介
Apache POI是一个开源的Java类库,用于处理Microsoft Office格式文件,如Word、Excel和PowerPoint。通过Apache POI,我们可以读取、写入和操作这些文件。在本文中,我们将重点介绍如何使用Apache POI读取Excel文件中的数据。
准备工作
在开始之前,我们需要先导入Apache POI的相关依赖。我们可以在pom.xml
文件中添加以下依赖:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.3</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
然后我们就可以开始编写Java代码来读取Excel中的数据了。
读取Excel中的数据
假设我们有一个名为data.xlsx
的Excel文件,其中包含以下数据:
姓名 | 年龄 | 性别 |
---|---|---|
小明 | 20 | 男 |
小红 | 22 | 女 |
小李 | 25 | 男 |
我们希望读取这些数据并在控制台上进行输出。下面是我们的Java代码:
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
import java.io.InputStream;
public class ReadExcel {
public static void main(String[] args) {
try {
InputStream inp = new FileInputStream("data.xlsx");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
switch (cell.getCellType()) {
case STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
case NUMERIC:
System.out.print((int) cell.getNumericCellValue() + "\t");
break;
default:
System.out.print(cell.toString() + "\t");
}
}
System.out.println();
}
inp.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
在上面的代码中,我们首先创建了一个InputStream
对象来读取Excel文件,然后使用WorkbookFactory.create()
方法创建一个Workbook
对象。接着我们获取第一个Sheet,并遍历其中的每一行和每一个单元格,根据单元格的类型输出对应的值。
总结
通过Apache POI,我们可以方便地读取Excel文件中的数据,为我们在实际工作中处理数据提供了很大的便利。希望本文对你有所帮助,如果有任何疑问或建议,欢迎留言交流。
erDiagram
CUSTOMER ||--o{ ORDER : places
ORDER ||--|{ LINE-ITEM : contains
CUSTOMER }|..| CUSTOMER-ADDRESS : "billing address"
CUSTOMER-ADDRESS }|..| CUSTOMER : "Is part of"
journey
title My working day
section Go to work
Make tea: 5: Me
Go out the door: 10: Me
section Get the bus
Wait for the bus: 5: Me
Get on the bus: 10: Me
section Work
Work on the presentation: 120: Me
section Go back home
Get on the bus: 10: Me
Wait for the bus: 5: Me
section Walk home
Walk to home: 15: Me
通过上面的代码示例和说明,我们学习了如何使用Apache POI在Java中读取Excel中的数据。希