java对excel文件里面的数据进行追加或者写入,修改等工具类

package com.ruoyi.web.controller.tool;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.enumVo.FileNameEnum;
import com.ruoyi.web.core.config.FileConfigProperties;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import javax.annotation.Resource;
import java.io.*;
import java.util.Collection;
import java.util.List;

@Component
public class FileDataUtil {
    @Resource
    FileConfigProperties fileConfigProperties;
    @Resource
    RedisCache redis;

    /**
     * 读取Excel文件数据
     *
     * @param fileNameVo 文件类型
     * @return 文件数据
     * @throws FileNotFoundException 文件不存在
     */
    public List<?> getFileDataList(FileNameEnum fileNameVo) throws FileNotFoundException {
        String fileName = fileNameVo.getFileName();
        File file = ResourceUtils.getFile(fileConfigProperties.getFilePath() + fileName);
        String fileLastTime = String.valueOf((file.lastModified()));
        String dataListKey = fileName + "Data";
        if (!redis.hasKey(fileName) || !redis.getCacheObject(fileName).equals(fileLastTime)) {
            redis.setCacheObject(fileName, fileLastTime);
            FileInputStream fileInputStream = null;
            try {
                fileInputStream = new FileInputStream(file);
                ExcelUtil<?> util = new ExcelUtil<>(fileNameVo.getEntityClass());
                List<?> dataList = util.importExcel(fileInputStream);
                if (!dataList.isEmpty()) {
                    redis.setCacheObject(dataListKey, dataList);
                }
                return dataList;
            } finally {
                if (fileInputStream != null) {
                    try {
                        fileInputStream.close();
                    } catch (IOException e) {
                        // 处理关闭文件流时可能出现的异常
                        e.printStackTrace();
                    }
                }
            }
        } else {
            return redis.getCacheObject(dataListKey);
        }
    }

    /**
     * 加载数据
     *
     * @param dataList 数据集
     * @param file     文件
     */
    public <T> void loadFileData(FileNameEnum file, List<T> dataList) throws Exception {
        try {
            dataList.clear();
            dataList.addAll((Collection<? extends T>) getFileDataList(file));
        } catch (Exception e) {
            throw new FileNotFoundException("加载文件数据时发生错误: " + e.getMessage());
        }
        if (dataList.isEmpty()) {
            throw new FileNotFoundException("文件数据为空");
        }

    }

    /**
     * 写入文件数据
     *
     * @param fileName 文件名
     * @param dataList 数据集
     */
    public void writeFileData(String fileName, List<String> dataList) {
        String filePath = fileConfigProperties.getFilePath() + fileName;
        try (FileInputStream fis = new FileInputStream(filePath);
             Workbook workbook = new XSSFWorkbook(fis);
             FileOutputStream fos = new FileOutputStream(filePath)
        ) {
            Sheet sheet = workbook.getSheet("Sheet1");
            // 定位到最后一行
            int lastRowNum = sheet.getLastRowNum();
            Row row = sheet.getRow(lastRowNum);
            //获取最后一行数据的序号值  并加1
            double rowIdDouble = Double.parseDouble(row.getCell(0).toString());
            int newRowId = (int) Math.round(rowIdDouble) + 1;
            // 创建新的行,并在最后一行的下一行追加数据
            Row newRow = sheet.createRow(lastRowNum + 1);
            newRow.createCell(0).setCellValue(newRowId);
            for (int i = 0; i < dataList.size(); i++) {
                newRow.createCell(i + 1).setCellValue(dataList.get(i));
            }
            // 保存Excel文件
            workbook.write(fos);
        } catch (IOException e) {
            // 处理异常
            System.out.println("对文件写入数据发生错误:" + e.getMessage());

        }
    }

    /*
     * 更新文件数据
     *
     * @param fileName 文件名
     * @param rowIndex 行索引(索引从0开始) 标题也占一列 也就是 id是多少就是更新第几行
     * @param columnIndex 第几列
     * @param new
     */
    public void updateFileData(String fileName, int rowIndex, int columnIndex, String newValue) {
        String filePath = fileConfigProperties.getFilePath() + fileName;
        try (FileInputStream fis = new FileInputStream(filePath);
             Workbook workbook = new XSSFWorkbook(fis);
             FileOutputStream fos = new FileOutputStream(filePath)
        ) {
            Sheet sheet = workbook.getSheet("Sheet1");
            Row row = sheet.getRow(rowIndex);//要更新的行的索引,(索引从0开始)
            columnIndex = columnIndex - 1;//(索引从0开始)
            if (row != null) {
                Cell cell = row.getCell(columnIndex, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
                if (cell == null) {
                    cell = row.createCell(columnIndex);
                }
                cell.setCellValue(newValue); // 设置新的单元格值
            }
            // 保存Excel文件
            workbook.write(fos);
        } catch (IOException e) {
            // 处理异常
            System.out.println("对文件数据进行更新发生错误:" + e.getMessage());
        }
    }
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小高求学之路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值