1. EasyExcel の概要
EasyExcel の公式 Web サイトでは、Excel の従来の操作のほとんどは Apache POI によって操作されていると紹介されていますが、POI フレームワークは
完璧ではなく、使用プロセスが非常に煩雑で多くの欠陥があります。Excel
の動的操作は非常に煩雑であり、初心者が短時間で行うのは難しい、中から始める、
読み書きに大量のメモリが必要、データ量が多いとメモリオーバーフロー問題(OOM)が発生しやすい、上記の理由から, Alibaba は、使いやすく比較的メモリを節約できる Excel 操作フレームワーク EasyExcel をオープンソース化しました。
知らせ: easyExcel の基礎となる層は POI を使用して実装されます。
公式サイトアドレス: https: //www.yuque.com/easyexcel/doc/easyexcel
2. エクスポート
2.1 依存関係の導入
<!--引入easyexcel-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.0.4</version>
</dependency>
2.2 テストエンティティクラスの構築
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class User implements Serializable {
@ExcelProperty(value = {
"用户名"},index = 0)
private String userName;
@ExcelProperty(value = {
"年龄"},index = 1)
private Integer age;
@ExcelProperty(value = {
"地址"} ,index = 2)
private String address;
@ExcelProperty(value = {
"生日"},index = 3)
//注意:日期格式注解由alibaba.excel提供
// @DateTimeFormat("yyyy-MM-dd HH:mm")
private Date birthday;
}
エクスポートコード
public static void main(String[] args) {
//组装数据
ArrayList<User> users = new ArrayList<>();
for (int i = 0; i < 10; i++) {
User user = new User();
user.setAddress("西安" + i);
user.setUserName("张三" + i);
user.setBirthday(new Date());
user.setAge(10 + i);
users.add(user);
}
//不做任何注解处理时,表头名称与实体类属性名称一致
EasyExcel.write("D:\\用户.xlsx", User.class).sheet("用户信息").doWrite(users);
}
輸出効果
3. セルサイズの設定
次のアノテーションをクラスに追加します
@HeadRowHeight(value = 35) // 表头行高
@ContentRowHeight(value = 25) // 内容行高
@ColumnWidth(value = 50) // 列宽
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@HeadRowHeight(value = 35) // 表头行高
@ContentRowHeight(value = 25) // 内容行高
@ColumnWidth(value = 50) // 列宽
public class User implements Serializable {
@ExcelProperty(value = {
"用户名"},index = 0)
private String userName;
@ExcelProperty(value = {
"年龄"},index = 1)
private Integer age;
@ExcelProperty(value = {
"地址"} ,index = 2)
private String address;
@ExcelProperty(value = {
"生日"},index = 3)
//注意:日期格式注解由alibaba.excel提供
// @DateTimeFormat("yyyy-MM-dd HH:mm")
private Date birthday;
}
効果は次のとおりです。