EasyExcel 追加写入
跳到导航
跳到搜索
这个代码数据量不是特别大可以用;
数据量小,inMemory 可以传 true;
package org.example.easyexcel;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.example.domain.User;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.util.Collections;
import java.util.List;
public class EasyExcelWriteTest {
/**
* 测试追加
*/
@Test
public void testAppendWrite() {
User user = new User();
user.setName(String.valueOf(RandomUtil.randomChinese()));
List<User> data = Collections.singletonList(user);
String path = "F:\\record\\2026\\01\\27\\test_append" + ExcelTypeEnum.XLSX.getValue();
String tmpPath = "F:\\record\\2026\\01\\27\\tmp_" + System.currentTimeMillis() + ExcelTypeEnum.XLSX.getValue();
File file = new File(path);
File tmpFile = new File(tmpPath);
if (!file.exists()) {
EasyExcel.write(file)
.head(User.class)
.sheet(0)
.doWrite(data);
return;
}
EasyExcel.write(tmpFile)
.withTemplate(file)
// .inMemory(true)
.inMemory(false)
.sheet(0)
.needHead(false)
.doWrite(data);
if (tmpFile.exists()) {
file.delete();
tmpFile.renameTo(file);
}
}
}