java - 使用当前日期和时间重命名现有 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;
}
}
先感谢您。
解决方案
我认为您也应该在其他部分添加工作簿代码。由于您只是使用 File 对象重命名文件,因此您的 excel 损坏可能是原因。在其他部分添加工作簿代码,并在所有操作完成后关闭您的工作簿实例。
推荐阅读
- javascript - Access-Control-Allow-Origin axios 请求错误 - CORS
- angular - Angular 12 数据表在我使用模态之前不显示数据
- r - 如何将我在 r 中的 excel 数据集的性别因子值更改为 0 和 1 而不是 1 和 2
- c++ - 如何将文本文件分解成更小的块(在 Unix 上使用 C++)?
- c++ - 从向量中擦除 shared_ptr 时某些隐藏的 == 操作数出现问题
- java - 在 Windows 上使用 Gradle axion 发布失败,但在 Linux 上有效
- c++ - 如果布局兼容的派生类成员处于活动状态,是否定义了访问联合中的基类的行为?
- javascript - 将子组件中单击的元素的值传递到父组件中的按钮中,以通过状态提升做出反应不起作用
- r - 如何从该特定网页中抓取数据并将输出保存在数据框中?
- json - 在 Go 中编组多维数组