Martin Jones
Martin Jones

Reputation: 51

What is wrong with my JAVA Swing code when I try to access Excel file?

I'm trying to make "Life Scheduler" with JAVA Swing, and I am trying to use Excel for database. (I can't use SQL for database cause I don't really know about it)

But it seems that my program corrupts excel file that I tried to use.

When I press "addSchedulebutton", I intended to add String "This is a test Data" at cell (0, 0). But it seems my program corrupts excel file while adding the string. After I press the button, I cannot open excel file with error message "It seems this excel file is corrupted..."

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(); 
            }
        }
    });

Above is the code that I made. Can someone find problem in my code?

Upvotes: 0

Views: 49

Answers (1)

Dragos Secara
Dragos Secara

Reputation: 36

HSSF is designed to work with the Excel '97(-2007) file format (.xls). You are trying to save a .xlsx file(Excel 2007 OOXML). You can try saving as ".xls" or change the program to use the XSSF classes.

I suggest changing the output to .xls. It is a quick way to see if the implementation is really the problem.

Upvotes: 2

Related Questions