Java POI Excel 工具类详解:ExcelUtils

在日常开发工作中,处理Excel文件是非常常见的需求之一。无论是读取Excel文件中的数据还是向Excel文件写入数据,都需要一个可靠且易于使用的工具类。本文将介绍一个基于Java POI库的Excel工具类——ExcelUtils,它可以帮助你轻松地处理Excel文件。

介绍

ExcelUtils 是一个简单而强大的工具类,它提供了读取和写入Excel文件的功能。这个工具类可以处理含有公式的单元格,并且支持将Excel文件读取为 List<Map<String, String>> 格式,方便后续的数据处理。

功能

  1. 读取Excel文件
  2. 将Excel文件读取为 List<Map<String, String>> 格式,方便进行数据处理。
  3. 支持含有公式的单元格,并能正确计算公式的结果。
  4. 写入Excel文件
  5. 将 List<Map<String, String>> 数据写入Excel文件。
  6. 自动处理表头和数据行。

使用示例

1. 添加依赖

为了使用ExcelUtils,首先需要在项目中添加Apache POI的依赖。如果你使用Maven,可以在pom.xml文件中添加如下依赖:

Xml

深色版本

1<dependencies>
2    <!-- Other dependencies -->
3    <dependency>
4        <groupId>org.apache.poi</groupId>
5        <artifactId>poi</artifactId>
6        <version>5.2.2</version>
7    </dependency>
8    <dependency>
9        <groupId>org.apache.poi</groupId>
10        <artifactId>poi-ooxml</artifactId>
11        <version>5.2.2</version>
12    </dependency>
13</dependencies>

2. 读取Excel文件

Java

深色版本

1import java.io.IOException;
2import java.util.List;
3import java.util.Map;
4
5public class Main {
6    public static void main(String[] args) {
7        try {
8            List<Map<String, String>> data = ExcelUtils.readExcelAsMap("path/to/your/file.xlsx");
9            
10            // 打印读取的数据
11            for (Map<String, String> row : data) {
12                for (Map.Entry<String, String> entry : row.entrySet()) {
13                    System.out.print(entry.getKey() + ": " + entry.getValue() + "\t");
14                }
15                System.out.println();
16            }
17        } catch (IOException e) {
18            e.printStackTrace();
19        }
20    }
21}

3. 写入Excel文件

Java

深色版本

1import java.io.IOException;
2import java.util.ArrayList;
3import java.util.LinkedHashMap;
4import java.util.List;
5import java.util.Map;
6
7public class Main {
8    public static void main(String[] args) {
9        List<Map<String, String>> data = new ArrayList<>();
10        Map<String, String> row1 = new LinkedHashMap<>();
11        row1.put("Name", "John Doe");
12        row1.put("Age", "30");
13        row1.put("Role", "Developer");
14        data.add(row1);
15
16        Map<String, String> row2 = new LinkedHashMap<>();
17        row2.put("Name", "Jane Doe");
18        row2.put("Age", "28");
19        row2.put("Role", "Designer");
20        data.add(row2);
21
22        try {
23            ExcelUtils.writeExcel("path/to/output/file.xlsx", data);
24        } catch (IOException e) {
25            e.printStackTrace();
26        }
27    }
28}

代码实现

下面是ExcelUtils工具类的完整实现:

Java

深色版本

1import org.apache.poi.ss.usermodel.*;
2import org.apache.poi.ss.formula.FormulaEvaluator;
3import org.apache.poi.xssf.usermodel.XSSFWorkbook;
4
5import java.io.File;
6import java.io.FileInputStream;
7import java.io.FileOutputStream;
8import java.io.IOException;
9import java.util.*;
10
11public class ExcelUtils {
12
13    private static final String FILE_EXTENSION_XLS = ".xls";
14    private static final String FILE_EXTENSION_XLSX = ".xlsx";
15
16    /**
17     * 读取Excel文件中的数据,并将其转换为 List<Map<String, String>>。
18     *
19     * @param filePath Excel文件的路径。
20     * @return 读取的数据列表。
21     * @throws IOException 如果文件读取失败。
22     */
23    public static List<Map<String, String>> readExcelAsMap(String filePath) throws IOException {
24        List<Map<String, String>> data = new ArrayList<>();
25
26        try (FileInputStream fis = new FileInputStream(new File(filePath))) {
27            Workbook workbook = WorkbookFactory.create(fis);
28            Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表
29            FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
30            List<String> headers = new ArrayList<>();
31
32            // 读取头部信息
33            Row headerRow = sheet.getRow(0);
34            for (Cell headerCell : headerRow) {
35                headers.add(headerCell.getStringCellValue());
36            }
37
38            for (Row row : sheet) {
39                if (row.getRowNum() == 0) continue; // 跳过头部行
40                Map<String, String> rowData = new LinkedHashMap<>();
41                for (int i = 0; i < headers.size(); i++) {
42                    Cell cell = row.getCell(i);
43                    if (cell != null) {
44                        CellType cellType = cell.getCellType();
45                        if (cellType == CellType.FORMULA) {
46                            // 使用公式评估器来计算公式的结果
47                            CellValue cellValue = evaluator.evaluate(cell);
48                            rowData.put(headers.get(i), getStringCellValue(cellValue));
49                        } else if (cellType == CellType.NUMERIC) {
50                            rowData.put(headers.get(i), Double.toString(cell.getNumericCellValue()));
51                        } else if (cellType == CellType.STRING) {
52                            rowData.put(headers.get(i), cell.getStringCellValue());
53                        } else if (cellType == CellType.BLANK) {
54                            rowData.put(headers.get(i), "");
55                        }
56                    } else {
57                        rowData.put(headers.get(i), "");
58                    }
59                }
60                data.add(rowData);
61            }
62
63            workbook.close();
64        }
65
66        return data;
67    }
68
69    /**
70     * 写入数据到Excel文件。
71     *
72     * @param filePath 文件路径。
73     * @param data     要写入的数据列表。
74     * @throws IOException 如果文件写入失败。
75     */
76    public static void writeExcel(String filePath, List<Map<String, String>> data) throws IOException {
77        Workbook workbook = createWorkbook(filePath);
78        Sheet sheet = workbook.createSheet("Sheet1");
79
80        // 写入头部
81        Row headerRow = sheet.createRow(0);
82        int colIndex = 0;
83        if (!data.isEmpty()) {
84            for (String header : data.get(0).keySet()) {
85                Cell cell = headerRow.createCell(colIndex++);
86                cell.setCellValue(header);
87            }
88        }
89
90        // 写入数据
91        for (int i = 0; i < data.size(); i++) {
92            Row row = sheet.createRow(i + 1); // 从第二行开始写入数据
93            Map<String, String> rowData = data.get(i);
94            colIndex = 0;
95            for (String value : rowData.values()) {
96                Cell cell = row.createCell(colIndex++);
97                cell.setCellValue(value);
98            }
99        }
100
101        try (FileOutputStream fos = new FileOutputStream(filePath)) {
102            workbook.write(fos);
103            workbook.close();
104        }
105    }
106
107    /**
108     * 创建Workbook实例。
109     *
110     * @param filePath 文件路径。
111     * @return Workbook实例。
112     */
113    private static Workbook createWorkbook(String filePath) {
114        if (filePath.endsWith(FILE_EXTENSION_XLSX)) {
115            return new XSSFWorkbook();
116        } else if (filePath.endsWith(FILE_EXTENSION_XLS)) {
117            return new org.apache.poi.hssf.usermodel.HSSFWorkbook();
118        } else {
119            throw new IllegalArgumentException("Unsupported file extension: " + filePath);
120        }
121    }
122
123    /**
124     * 获取单元格的值(字符串形式)。
125     *
126     * @param cellValue 包含计算结果的 CellValue 对象。
127     * @return 单元格的值。
128     */
129    private static String getStringCellValue(CellValue cellValue) {
130        switch (cellValue.getCellType()) {
131            case NUMERIC:
132                return Double.toString(cellValue.getNumberValue());
133            case STRING:
134                return cellValue.getStringValue();
135            default:
136                return ""; // 对于其他类型,返回空字符串
137        }
138    }
139}

结论

ExcelUtils 提供了一个简单易用的接口来处理Excel文件,无论是读取还是写入,都只需要几行代码即可完成。通过使用这个工具类,你可以快速集成Excel处理功能到你的Java应用中,提高开发效率。

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值