杰瑞科技汇

Java如何读取Excel并写入数据?

Java 读取Excel并写入数据

在Java中处理Excel文件,常用的库有Apache POI和EasyExcel,下面我将分别介绍这两种方法。

Java如何读取Excel并写入数据?-图1
(图片来源网络,侵删)

使用Apache POI

Apache POI是Java操作Office文档最常用的库。

添加依赖(Maven)

<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>

读取Excel示例

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.IOException;
public class ExcelReader {
    public static void main(String[] args) {
        String filePath = "path/to/your/file.xlsx";
        try (FileInputStream fis = new FileInputStream(filePath);
             Workbook workbook = new XSSFWorkbook(fis)) {
            // 获取第一个工作表
            Sheet sheet = workbook.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(cell.getNumericCellValue() + "\t");
                            break;
                        case BOOLEAN:
                            System.out.print(cell.getBooleanCellValue() + "\t");
                            break;
                        case FORMULA:
                            System.out.print(cell.getCellFormula() + "\t");
                            break;
                        default:
                            System.out.print("\t");
                    }
                }
                System.out.println();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

写入Excel示例

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
public class ExcelWriter {
    public static void main(String[] args) {
        String filePath = "path/to/output/file.xlsx";
        // 创建新的工作簿
        Workbook workbook = new XSSFWorkbook();
        // 创建工作表
        Sheet sheet = workbook.createSheet("Sheet1");
        // 创建标题行
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("姓名");
        headerRow.createCell(1).setCellValue("年龄");
        headerRow.createCell(2).setCellValue("性别");
        // 添加数据行
        Row dataRow1 = sheet.createRow(1);
        dataRow1.createCell(0).setCellValue("张三");
        dataRow1.createCell(1).setCellValue(25);
        dataRow1.createCell(2).setCellValue("男");
        Row dataRow2 = sheet.createRow(2);
        dataRow2.createCell(0).setCellValue("李四");
        dataRow2.createCell(1).setCellValue(30);
        dataRow2.createCell(2).setCellValue("女");
        try (FileOutputStream fos = new FileOutputStream(filePath)) {
            workbook.write(fos);
            System.out.println("Excel文件已成功写入");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

使用EasyExcel

EasyExcel是阿里巴巴开源的Excel处理库,性能更好,内存占用更少。

添加依赖(Maven)

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>3.1.1</version>
</dependency>

定义数据模型

import com.alibaba.excel.annotation.ExcelProperty;
public class UserData {
    @ExcelProperty("姓名")
    private String name;
    @ExcelProperty("年龄")
    private Integer age;
    @ExcelProperty("性别")
    private String gender;
    // getters and setters
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public Integer getAge() { return age; }
    public void setAge(Integer age) { this.age = age; }
    public String getGender() { return gender; }
    public void setGender(String gender) { this.gender = gender; }
}

读取Excel示例

import com.alibaba.excel.EasyExcel;
import java.util.List;
public class EasyExcelReader {
    public static void main(String[] args) {
        String filePath = "path/to/your/file.xlsx";
        List<UserData> list = EasyExcel.read(filePath)
                .head(UserData.class)
                .sheet()
                .doReadSync();
        for (UserData data : list) {
            System.out.println(data.getName() + ", " + data.getAge() + ", " + data.getGender());
        }
    }
}

写入Excel示例

import com.alibaba.excel.EasyExcel;
import java.util.ArrayList;
import java.util.List;
public class EasyExcelWriter {
    public static void main(String[] args) {
        String filePath = "path/to/output/file.xlsx";
        // 准备数据
        List<UserData> list = new ArrayList<>();
        list.add(new UserData("张三", 25, "男"));
        list.add(new UserData("李四", 30, "女"));
        // 写入Excel
        EasyExcel.write(filePath, UserData.class)
                .sheet("Sheet1")
                .doWrite(list);
        System.out.println("Excel文件已成功写入");
    }
}

注意事项

  1. 大文件处理:对于大文件,EasyExcel比Apache POI更优,因为它采用SAX模式读取,内存占用更小。
  2. 版本兼容:确保使用的库版本与你的Java版本兼容。
  3. 异常处理:在实际应用中,应该添加适当的异常处理。
  4. 性能优化:写入大量数据时,可以考虑使用WriteSheetWriteTable来优化性能。

选择哪种方法取决于你的具体需求,如果处理大文件或需要更好的性能,推荐使用EasyExcel;如果需要更全面的功能或处理旧版Excel文件,可以使用Apache POI。

分享:
扫描分享到社交APP
上一篇
下一篇