Home > Enterprise >  Need to save the excel file for every run with the current timestamp
Need to save the excel file for every run with the current timestamp

Time:12-20

I am using the below code to convert the json file to excel using aspose. I am able to convert the json file but i need to save the converted file for every run with the current timestamp and i need to run it daily so that it should create a folder daily with the date.

public class converter1 {
public static void main(String[] args) throws Exception {   
    LocalDateTime date = LocalDateTime.now();
    DateTimeFormatter dateformat = DateTimeFormatter.ofPattern("dd-MM-yyyy HH-mm-ss");
    String formatedate =date.format(dateformat);
    Workbook workbook = new Workbook(".//Files//output.json");       
    workbook.save(".//output-" formatedate ".xlsx");            
    System.out.println("json file converted successfully");
}

}

CodePudding user response:

To save the file with the current timestamp, you can use the LocalDateTime class to get the current date and time, and then use a DateTimeFormatter to format it into a string in the desired format. You can then use this formatted string as part of the file name when you save the file.

To create a folder with the current date, you can use the Files class from the java.nio.file package to create a directory with the desired name.

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class converter1 {
    public static void main(String[] args) throws Exception {   
        LocalDate date = LocalDate.now();
        DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("dd-MM-yyyy");
        String formattedDate = date.format(dateFormat);

        // Create a directory with the current date
        Path dir = Paths.get(".//"   formattedDate);
        Files.createDirectories(dir);

        Workbook workbook = new Workbook(".//Files//output.json");       

        // Save the file in the new directory with the current timestamp
        LocalDateTime dateTime = LocalDateTime.now();
        DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern("dd-MM-yyyy HH-mm-ss");
        String formattedDateTime = dateTime.format(dateTimeFormat);
        workbook.save(dir   "//output-"   formattedDateTime   ".xlsx");            

        System.out.println("json file converted successfully");
    }
}

This code will create a new directory with the current date (e.g. "20-12-2022") if it doesn't already exist, and save the converted file inside it with a file name that includes the current timestamp (e.g. "output-20-12-2022 12-34-56.xlsx"). If you want to run this code daily to create a new folder with the current date each day, you can set it up as a daily cron job or use some other scheduling mechanism to run it automatically at the desired interval.

  • Related