首页 > 解决方案 > 使用当前日期和时间重命名现有 excel 文件时 Excel 文件损坏?

问题描述

当我使用下面的代码重命名现有的 Excel 文件时,将使用当前时间戳生成 Excel 文件,但是当我尝试打开重命名的 Excel 文件时,我无法打开它。它显示工作簿已损坏。

请找出以下代码中的错误在哪里。为什么 Excel 文件会损坏?

package BrokenLink;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


    public class CreateExcelFile {


        public static void main(String[] args)
        {
       
        
            //new File("C:\\Users\\skumari1\\eclipse-workspace\\AlarmTest\\Generics").mkdir();
                CreateFileRenameExisting("NewBook.xlsx");


            }
        
        


        //Rename an existing file and create a new file
        public static void CreateFileRenameExisting(String filename)
        {
            //get current project path
            String filePath=System.getProperty("user.dir");
            //create a new file
            File file=new File(filePath+"\\"+filename);
            try {
                if(!file.exists()) {
                
                    Workbook wb1 = new XSSFWorkbook();


                    FileOutputStream fileOut1 = new FileOutputStream(filename);


                    wb1.write(fileOut1);


                    fileOut1.close();
                    //file.createNewFile();
                    System.out.println("File is created");
                   
                }
                else
                {
                    File backupFile=new File(filePath+"\\"+ Validatedate()  +  file.getName());
                    System.out.println("File already exist and backup file is created");
                    file.renameTo(backupFile);
                }
                
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        public static String Validatedate() {
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH_mm_ss");
            Date date = new Date();
            String date1= dateFormat.format(date);
            // System.out.println("Current date and time is " +date1);
             return date1;
        }
        


        }

先感谢您。

标签: javaselenium-webdriver

解决方案


我认为您也应该在其他部分添加工作簿代码。由于您只是使用 File 对象重命名文件,因此您的 excel 损坏可能是原因。在其他部分添加工作簿代码,并在所有操作完成后关闭您的工作簿实例。


推荐阅读