1
votes

I am working with apache poi and I create a HSSF workbook and try to open a xlsx file. But when I open with excel, it says the file is corrupted. Here is my code.

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.FileOutputStream;

public class Excel {

    public static void main(String[] args) {

        Workbook workbook = new HSSFWorkbook();

        try {
            FileOutputStream output = new FileOutputStream("Test1.xls");
            workbook.write(output);
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
1
HSSF might not work with the newer .xslx file format. It's pretty old. I'm not sure it's kept up. You might do better with Andy Khan's JExcel.duffymo
It is happening same thing, when I try .xlsEmin Çiftçi
Looks like the latest release was 16-Apr-2017; newer than I thought. What version are you using? poi.apache.org/download.html#POI-3.16duffymo
I am using 3.16 which is latest stable version.Emin Çiftçi
I try to open .xls file wtih notepad++ and there are some strange characters in thereEmin Çiftçi

1 Answers

5
votes

You have to use XSSFWorkbook for XLSX.

And try creating at least one sheet and see if it is opening correctly.

HSSFWorkbook workbook = new HSSFWorkbook();
try {
    FileOutputStream output = new FileOutputStream("Test1.xls");
    workbook.createSheet("sheet1")
    workbook.write(output);
    output.close();
} catch (Exception e) {
    e.printStackTrace();
}