学无先后,达者为师

网站首页 编程语言 正文

EasyExcel 3.X 简单写入Excel文件数据

作者:杜小舟 更新时间: 2022-08-05 编程语言

文章目录

      • POM依赖
      • 创建实体类
      • 写入Excel文件

POM依赖

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

创建实体类

根据你想要的Excel文件表头创建对应的实体类:

import com.alibaba.excel.annotation.ExcelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@NoArgsConstructor
@AllArgsConstructor
@Data
@Builder
public class WaiteExcel {

    // value 是excel文件的表头   index 是第几列
    @ExcelProperty(value = "用户名", index = 0)
    private String name;

    @ExcelProperty(value = "年龄", index = 1)
    private String age;

    @ExcelProperty(value = "性别", index = 2)
    private String gender;

}

写入Excel文件

public static void main(String[] args) {
	// 写入文件的路径
	final String excelFilePath = "D:/waiteExcel.xlsx";
	try {
		// 判断文件是否存在, 不存在则创建
		File file = new File(excelFilePath);
		if (!file.exists()) {
			file.createNewFile();
		}

		// 向Excel中写入数据
		EasyExcel.write(excelFilePath, WaiteExcel.class)
				.sheet("写入的Sheet") // Sheet 自定义名称
				.doWrite(handleWaiteExcelList()); // 写入的数据(此处写入的是一个列表)
	} catch (IOException e) {
		log.error("{}", e);

	} catch (Exception e) {
		log.error("{}", e);

	}
}

在我的电脑D盘中就成功创建了waiteExcel文件
**打印日志:**


waiteExcel文件中的数据也被写入进来了
在这里插入图片描述





End


原文链接:https://blog.csdn.net/weixin_43657300/article/details/126155836

栏目分类
最近更新