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

Aspose JSON转Excel优化需求:按日期建文件夹并带时间戳保存文件

实现按日期创建文件夹并以时间戳命名Excel输出文件

代码实现

import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import com.aspose.cells.Workbook;

public class converter1 {
    public static void main(String[] args) throws Exception {   
        LocalDateTime now = LocalDateTime.now();
        
        // 格式化日期用于文件夹名称(格式:dd-MM-yyyy)
        DateTimeFormatter folderDateFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
        String folderName = now.format(folderDateFormatter);
        String folderPath = ".//ConvertedFiles//" + folderName;
        
        // 创建文件夹(不存在则自动创建,包含父目录)
        Files.createDirectories(Paths.get(folderPath));
        
        // 格式化时间戳用于文件名(精确到毫秒,避免同名覆盖)
        DateTimeFormatter fileNameTimeFormatter = DateTimeFormatter.ofPattern("HH-mm-ss-SSS");
        String timeStamp = now.format(fileNameTimeFormatter);
        String savePath = folderPath + "//output-" + timeStamp + ".xlsx";
        
        // JSON转Excel并保存
        Workbook workbook = new Workbook(".//Files//output.json");       
        workbook.save(savePath);            
        System.out.println("JSON文件转换成功,保存路径:" + savePath);
    }
}

关键说明

  • 日期文件夹自动创建:借助Files.createDirectories方法,无需手动判断文件夹是否存在,会自动创建所有缺失的父目录和当日日期文件夹。
  • 防重命名逻辑:文件名使用精确到毫秒的时间戳,确保同一秒内多次运行也不会出现文件覆盖的问题。
  • 跨平台路径兼容:使用//作为路径分隔符,可在Windows和Linux系统下正常运行,也可替换为File.separator进一步增强兼容性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 14:50:27