当前位置:首页 > 编程知识 > 正文

Java读取Excel文件内容并输出示例

在Java中,经常需要读取Excel文件的内容并输出,这涉及到对Apache POI库的使用。下面将详细讲解如何使用Java进行Excel文件的读取并输出。

一、环境及库的准备

在开始编码前,我们需要保证Java环境安装完毕。并且要在项目中引入Apache POI这个库。

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.17</version>
</dependency>

二、代码实现读取Excel文件内容

以下是完整的Java代码,包括主方法中的调用以及Excel文件读取的方法。

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;

public class ReadExcelFile {
    public static void main(String[] args) {
        try {
            readExcel("Sample.xlsx");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void readExcel(String fileName) throws IOException {
        FileInputStream excelFile = new FileInputStream(new File(fileName));
        Workbook workbook = new XSSFWorkbook(excelFile);
        Sheet datatypeSheet = workbook.getSheetAt(0);
        Iterator<Row> rowIterator = datatypeSheet.iterator();
        while (rowIterator.hasNext()) {
            Row currentRow = iterator.next();
            Iterator<Cell> cellIterator = currentRow.iterator();
            while (cellIterator.hasNext()) {
                Cell currentCell = cellIterator.next();
                if (currentCell.getCellType() == CellType.STRING) {
                    System.out.print(currentCell.getStringCellValue() + " ");
                } else if (currentCell.getCellType() == CellType.NUMERIC) {
                    System.out.print(currentCell.getNumericCellValue() + " ");
                }
            }
            System.out.println();
        }
    }
}

三、运行程序并查看结果

如果Excel文件路径和文件名填写正确,正确配置了Apache POI库,并且Excel文件有内容,运行程序后,控制台就可以看到Excel文件内容的输出了。

java -jar ReadExcelFile.jar