跳转至

在Java中读取Excel文件

简介

在Java开发中,读取Excel文件是一个常见的需求。无论是处理业务数据、进行数据分析,还是从外部数据源获取信息,掌握如何在Java中读取Excel文件都是一项重要的技能。本文将详细介绍在Java中读取Excel文件的基础概念、使用方法、常见实践以及最佳实践,帮助读者更好地处理这一任务。

目录

  1. 基础概念
  2. 使用方法
    • 使用Apache POI库
    • 使用EasyExcel库
  3. 常见实践
    • 读取简单Excel文件
    • 处理带表头的Excel文件
    • 处理不同Sheet
  4. 最佳实践
    • 内存管理
    • 错误处理
    • 性能优化
  5. 小结
  6. 参考资料

基础概念

Excel文件有不同的格式,常见的有 .xls(Excel 97-2003 格式) 和 .xlsx(Excel 2007及以上版本格式)。在Java中读取Excel文件,我们需要借助第三方库来解析这些文件格式。目前,最常用的库是Apache POI和EasyExcel。

  • Apache POI:一个开源的Java库,提供了一系列的API来处理各种Microsoft Office格式的文件,包括Excel。它功能强大,支持读取和写入不同版本的Excel文件。
  • EasyExcel:基于Apache POI封装的一个更轻量级、更易用的库。它专注于简化Excel文件的读写操作,特别适合处理大数据量的Excel文件。

使用方法

使用Apache POI库

  1. 添加依赖pom.xml 中添加Apache POI的依赖: xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>5.0.0</version> </dependency>
  2. 读取Excel文件示例 ```java 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;

    public class ApachePOIExample { public static void main(String[] args) { String filePath = "path/to/your/file.xlsx"; try (FileInputStream fis = new FileInputStream(new File(filePath)); Workbook workbook = new XSSFWorkbook(fis)) {

            Sheet sheet = workbook.getSheetAt(0);
            for (Row row : sheet) {
                for (Cell cell : row) {
                    CellType cellType = cell.getCellType();
                    if (cellType == CellType.STRING) {
                        System.out.print(cell.getStringCellValue() + "\t");
                    } else if (cellType == CellType.NUMERIC) {
                        if (DateUtil.isCellDateFormatted(cell)) {
                            System.out.print(cell.getDateCellValue() + "\t");
                        } else {
                            System.out.print(cell.getNumericCellValue() + "\t");
                        }
                    } else if (cellType == CellType.BOOLEAN) {
                        System.out.print(cell.getBooleanCellValue() + "\t");
                    }
                }
                System.out.println();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    

    } ```

使用EasyExcel库

  1. 添加依赖pom.xml 中添加EasyExcel的依赖: xml <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>3.1.1</version> </dependency>
  2. 读取Excel文件示例 首先创建一个实体类来映射Excel数据: ```java import com.alibaba.excel.annotation.ExcelProperty;

    public class ExcelData { @ExcelProperty("列1") private String column1; @ExcelProperty("列2") private String column2;

    // Getters and Setters
    public String getColumn1() {
        return column1;
    }
    
    public void setColumn1(String column1) {
        this.column1 = column1;
    }
    
    public String getColumn2() {
        return column2;
    }
    
    public void setColumn2(String column2) {
        this.column2 = column2;
    }
    

    } 然后编写读取代码:java import com.alibaba.excel.EasyExcel; import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.read.listener.ReadListener;

    import java.util.List;

    public class EasyExcelExample { public static void main(String[] args) { String filePath = "path/to/your/file.xlsx"; EasyExcel.read(filePath, ExcelData.class, new ReadListener() { @Override public void invoke(ExcelData data, AnalysisContext context) { System.out.println(data.getColumn1() + "\t" + data.getColumn2()); }

            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                System.out.println("读取完成");
            }
        }).sheet().doRead();
    }
    

    } ```

常见实践

读取简单Excel文件

上述示例代码展示了如何读取一个简单的Excel文件,其中包含基本的数据类型。

处理带表头的Excel文件

如果Excel文件带有表头,可以在读取时进行相应的处理。例如,在Apache POI中,可以通过获取第一行作为表头,然后根据表头信息来解析后续行的数据。

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.ArrayList;
import java.util.List;

public class HeaderExcelExample {
    public static void main(String[] args) {
        String filePath = "path/to/your/file.xlsx";
        try (FileInputStream fis = new FileInputStream(new File(filePath));
             Workbook workbook = new XSSFWorkbook(fis)) {

            Sheet sheet = workbook.getSheetAt(0);
            Row headerRow = sheet.getRow(0);
            List<String> headers = new ArrayList<>();
            for (Cell cell : headerRow) {
                headers.add(cell.getStringCellValue());
            }

            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                for (int j = 0; j < headers.size(); j++) {
                    Cell cell = row.getCell(j);
                    CellType cellType = cell.getCellType();
                    if (cellType == CellType.STRING) {
                        System.out.print(cell.getStringCellValue() + "\t");
                    } else if (cellType == CellType.NUMERIC) {
                        if (DateUtil.isCellDateFormatted(cell)) {
                            System.out.print(cell.getDateCellValue() + "\t");
                        } else {
                            System.out.print(cell.getNumericCellValue() + "\t");
                        }
                    } else if (cellType == CellType.BOOLEAN) {
                        System.out.print(cell.getBooleanCellValue() + "\t");
                    }
                }
                System.out.println();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

处理不同Sheet

在Excel文件中,可能包含多个Sheet。可以通过指定Sheet的索引或名称来读取不同的Sheet。

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;

public class MultipleSheetsExample {
    public static void main(String[] args) {
        String filePath = "path/to/your/file.xlsx";
        try (FileInputStream fis = new FileInputStream(new File(filePath));
             Workbook workbook = new XSSFWorkbook(fis)) {

            int numberOfSheets = workbook.getNumberOfSheets();
            for (int i = 0; i < numberOfSheets; i++) {
                Sheet sheet = workbook.getSheetAt(i);
                System.out.println("Sheet: " + sheet.getSheetName());
                for (Row row : sheet) {
                    for (Cell cell : row) {
                        CellType cellType = cell.getCellType();
                        if (cellType == CellType.STRING) {
                            System.out.print(cell.getStringCellValue() + "\t");
                        } else if (cellType == CellType.NUMERIC) {
                            if (DateUtil.isCellDateFormatted(cell)) {
                                System.out.print(cell.getDateCellValue() + "\t");
                            } else {
                                System.out.print(cell.getNumericCellValue() + "\t");
                            }
                        } else if (cellType == CellType.BOOLEAN) {
                            System.out.print(cell.getBooleanCellValue() + "\t");
                        }
                    }
                    System.out.println();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

最佳实践

内存管理

当处理大文件时,内存管理非常重要。EasyExcel采用了基于事件驱动的方式,在读取数据时不会一次性将所有数据加载到内存中,因此更适合处理大数据量的Excel文件。而Apache POI在处理大文件时,可以通过迭代器的方式逐行读取数据,避免一次性加载整个文件。

错误处理

在读取Excel文件时,可能会遇到各种错误,如文件格式不正确、文件不存在等。应该进行全面的错误处理,以确保程序的稳定性。例如,在读取文件前检查文件是否存在,在读取过程中捕获可能的 IOExceptionIllegalStateException 等异常。

性能优化

为了提高读取Excel文件的性能,可以采取以下措施: - 尽量减少不必要的对象创建和销毁。 - 对于频繁读取Excel文件的场景,可以考虑缓存已读取的数据。 - 在使用Apache POI时,可以使用 FormulaEvaluator 来优化公式计算。

小结

本文详细介绍了在Java中读取Excel文件的相关知识,包括基础概念、使用Apache POI和EasyExcel库的方法、常见实践以及最佳实践。通过掌握这些内容,读者可以根据具体的需求选择合适的库和方法,高效地读取Excel文件,处理业务数据。

参考资料