【问题标题】:What is wrong with my JAVA Swing code when I try to access Excel file?当我尝试访问 Excel 文件时,我的 JAVA Swing 代码有什么问题?
【发布时间】:2020-09-19 01:04:18
【问题描述】:

我正在尝试使用 JAVA Swing 制作“Life Scheduler”,并且我正在尝试将 Excel 用于数据库。 (我不能将 SQL 用于数据库,因为我真的不知道)

但似乎我的程序损坏了我尝试使用的 excel 文件。

当我按下“addSchedulebutton”时,我打算在单元格 (0, 0) 处添加字符串“This is a test Data”。但似乎我的程序在添加字符串时损坏了 excel 文件。按下按钮后,我无法打开 excel 文件并显示错误消息“似乎此 excel 文件已损坏...”

addSchedulebutton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            HSSFWorkbook workbook = new HSSFWorkbook(); 
            HSSFSheet sheet = workbook.createSheet("Sheet1"); 
            HSSFRow row = sheet.createRow(0); 
            HSSFCell cell = row.createCell(0); 
            cell.setCellValue("This is a test Data"); 

            try {
                FileOutputStream fileoutputstream = new FileOutputStream("C:/Users/jihlo/Desktop/ScheduleData.xlsx");
                workbook.write(fileoutputstream);
                fileoutputstream.close();
            } catch (IOException ex) {
                ex.printStackTrace(); 
            }
        }
    });

以上是我编写的代码。有人能在我的代码中找到问题吗?

【问题讨论】:

  • fileoutputstream.close(); 更改为 fileoutputstream.flush(); fileoutputstream.close();

标签: java excel swing user-interface actionlistener


【解决方案1】:

HSSF 旨在使用 Excel '97(-2007) 文件格式 (.xls)。您正在尝试保存 .xlsx 文件(Excel 2007 OOXML)。您可以尝试另存为“.xls”或更改程序以使用 XSSF 类。

我建议将输出更改为 .xls。这是一种快速查看实施是否真的存在问题的方法。

【讨论】:

    猜你喜欢
    • 2019-06-06
    • 1970-01-01
    • 2022-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 2011-07-28
    相关资源
    最近更新 更多