You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java导出Excel时避免覆盖已有文件并按Windows规则自动重命名的方法

Java实现导出文件自动重命名(避免覆盖原有文件)

实现逻辑

  • 拆分目标文件名的基础名称和后缀
  • 从序号1开始循环拼接生成基础名(序号).后缀格式的新文件名
  • 校验生成的文件名在目标路径是否存在,找到第一个不存在的文件名即可使用
  • 支持自动创建不存在的输出目录,避免路径不存在报错

完整修改后代码

import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;

public class ExcelExport {
    public static void main(String[] args) throws IOException {
        File excel = new File("C:\\TEST\\Test.xlsx");
        try (FileInputStream fis = new FileInputStream(excel);
             XSSFWorkbook book = new XSSFWorkbook(fis)) {

            // 定义输出配置
            String outputDirPath = "C:\\TEST\\Output\\";
            String baseFileName = "Test";
            String suffix = ".xlsx";

            // 自动创建输出目录
            File outputDir = new File(outputDirPath);
            if (!outputDir.exists()) {
                outputDir.mkdirs();
            }

            // 获取可用的输出文件
            File outputFile = getAvailableFile(outputDirPath, baseFileName, suffix);

            // 写入文件
            try (FileOutputStream outputStream = new FileOutputStream(outputFile)) {
                book.write(outputStream);
            }
        }
    }

    /**
     * 获取不存在冲突的可用文件对象
     * @param outputDir 输出目录路径
     * @param baseName 基础文件名
     * @param suffix 文件后缀
     * @return 可用的文件对象
     */
    private static File getAvailableFile(String outputDir, String baseName, String suffix) {
        File file = new File(outputDir + baseName + suffix);
        int count = 1;
        // 如果文件存在就循环生成带序号的文件名
        while (file.exists()) {
            file = new File(outputDir + String.format("%s(%d)%s", baseName, count, suffix));
            count++;
        }
        return file;
    }
}

补充说明

  • 如果你的原始文件名是动态获取的,可以用如下代码拆分基础名和后缀:
    String fullFileName = "Test.xlsx";
    int dotIndex = fullFileName.lastIndexOf(".");
    String baseName = fullFileName.substring(0, dotIndex);
    String suffix = fullFileName.substring(dotIndex);
    
  • 路径中的反斜杠在Java字符串中必须转义为\\,也可以替换为正斜杠/避免转义问题
  • 如果你需要调整命名规则,直接修改getAvailableFile方法中的文件名拼接逻辑即可

内容的提问来源于stack exchange,提问作者Hanamant Jadhav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 15:06:04