liusuyi
2024-06-06 f37c91a84345f925e41cd26bf5d22ed1a2594bdf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.ruoyi.utils.excel;
 
import com.alibaba.excel.EasyExcel;
import com.ruoyi.common.config.ARDConfig;
import com.ruoyi.common.constant.Constants;
 
import java.io.File;
import java.util.ArrayList;
import java.util.List;
 
/**
 * @ClassName: TestEasyExcel
 * @Description:
 * @Author: 刘苏义
 * @Date: 2023年04月28日14:09
 * @Version: 1.0
 **/
public class EasyExcelUtil {
 
 
    private static void main(String[] args) throws Exception {
        //实现excel写的操作
        // 设置写入文件夹地址和excel文件名
        String fileName = "G:\\java.xlsx";
        // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
        //write方法两个参数 ,第一个参数文件路径名称,第二个参数实体类class
        EasyExcel.write(fileName, ExcelData.class).sheet("第一个sheet").doWrite(data("11"));
    }
 
    //循环设置要添加的数据,最终封装到list集合中
    private static List<ExcelData> data(String data) {
        List<ExcelData> list = new ArrayList<ExcelData>();
        ExcelData excelData = new ExcelData();
        excelData.setName(data);
        list.add(excelData);
        return list;
    }
 
    public static void writeAppend(String fileName, String msg) {
        File file = new File(fileName);
        File parentDir = file.getParentFile();
        if (!parentDir.exists()) {
            parentDir.mkdirs(); // 创建文件所在的目录,包括父目录
        }
        // 本地临时录像地址
        String tempExcel = ARDConfig.getProfile() + Constants.LOCAL_EXCEL_TEMP_PREFIX + "/temp.xlsx";
        File tempFile = new File(tempExcel);
        List<ExcelData> existingData = new ArrayList<>();
        if (file.exists()) {
            // 读取已有数据
            existingData = EasyExcel.read(file).head(ExcelData.class).sheet().doReadSync();
            // 去除重复数据
            boolean exist = existingData.stream().anyMatch(excelData -> excelData.getName().equals(msg));
            if (exist) {
                return;
            }
        }
        if (!existingData.isEmpty()) {
            // 第二次按照原有格式,不需要表头,追加写入
            EasyExcel.write(file, ExcelData.class).needHead(false)
                    .withTemplate(file).file(tempFile).sheet().doWrite(data(msg));
        } else {
            // 第一次写入需要表头
            EasyExcel.write(file, ExcelData.class).sheet("井不存在").doWrite(data(msg));
        }
 
        if (tempFile.exists()) {
            file.delete();
            tempFile.renameTo(file);
        }
    }
 
}