Turgut Tak
Turgut Tak

Reputation: 43

XSSFSheet cannot be cast to java.io.File

I am reading some values from a spesific sheet of excel workbook. I am adding these values to my database. There isnt any problem for this

But I also want to store the sheet of the workbook to my database BLOB cell.

I am trying to convert the sheet to Byte[]. I use below code.

I am trying to cast the sheet to java.io.File. But I am getting the below exception

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: org.apache.poi.xssf.usermodel.XSSFSheet cannot be cast to java.io.File

public  byte[] convertPDFToByteArray() {

    InputStream inputStream = null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    File file = (File) oku.wb.getSheet("İN");

    try {

        inputStream = new FileInputStream(file);

        byte[] buffer = new byte[1024];
        baos = new ByteArrayOutputStream();

        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            baos.write(buffer, 0, bytesRead);
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return baos.toByteArray();
    }

Is there a way to cast the "wb.getSheet("İN");" to java.io.File or any better way ?

Upvotes: 0

Views: 2034

Answers (1)

mvreijn
mvreijn

Reputation: 2942

You cannot just cast between two unrelated classes. In your case, I think you should use getBytes() of the sheet's workbook since the sheet object does not have this:

byte[] buffer = sheet.getWorkbook().getBytes();

It looks as though your oku.wb already contains the workbook, in that case you can call getBytes() directly on oku.wb:

byte[] buffer = oku.wb.getBytes();

EDIT Blast, I picked this code from one of my own projects, but that used HSSFSheet instead of XSSFSheet. So, your best best is to use the workbook's write() method as outlined in the comments:

public byte[] convert(XSSFSheet sheet) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        sheet.getWorkbook().write(baos);
    } catch (IOException e) {
        // blah
    }
    return baos.toByteArray();
}

Upvotes: 2

Related Questions