pluralton pluralton - 7 months ago 86
Java Question

Apache poi XSSF Creating Excel Files - Create returns empty file with format or file extension not valid?

The relevant part of the Controller class:

@RequestMapping(value = "/DBCompare/download", method = RequestMethod.GET)
public void handleDownloadDBCompareReportGet(HttpServletResponse response, Model model){
try{
reportService.downloadResultsDto(reportDto);
}
finally{
}
}


The ReportService in this case only fetches some information from the database, and calls newTableCompare() from the CreateTable class.

The following class should create a new Excel table, workbook, ect.

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.AreaReference;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFTable;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTable;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableColumn;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableColumns;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableStyleInfo;


public class CreateTable {

public void newTableCompare(Class1 c1, Class1 c2) throws FileNotFoundException,
IOException {
String tableName = "DB compare report for " + c1.getName() + "and" +c2.getName();
Workbook wb = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet) wb.createSheet();

XSSFTable table = sheet.createTable();
table.setDisplayName("Test");
CTTable cttable = table.getCTTable();

CTTableStyleInfo style = cttable.addNewTableStyleInfo();
style.setName("TableStyle1");
style.setShowColumnStripes(true);
style.setShowRowStripes(true);

AreaReference reference = new AreaReference(new CellReference(0, 0),
new CellReference(2,2));
cttable.setRef(reference.formatAsString());
cttable.setId(1);
cttable.setName("Test");
cttable.setTotalsRowCount(1);

CTTableColumns columns = cttable.addNewTableColumns();
columns.setCount(3);
CTTableColumn column;
XSSFRow row;
XSSFCell cell;
for(int i=0; i<3; i++) {
column = columns.addNewTableColumn();
column.setName("Column");
column.setId(i+1);
row = sheet.createRow(i);
for(int j=0; j<3; j++) {

cell = row.createCell(j);
if(i == 0) {
cell.setCellValue("Column"+j);
} else {
cell.setCellValue("0");
}
}
}
//this correctly creates a table in workbook
FileOutputStream fos = new FileOutputStream("workbook.xlsx");
wb.write(fos);
fos.close();
wb.close();

}
}


But in the end, when download is triggered, the result is only an empty file and if I try to open it with Excel, format or file extension not valid error is shown. Does anybody know how to fix this or what I am doing wrong?




In the end I did find out what I have been doing wrong.

Answer

Here is my own sollution, I forgot to add it when I solved the issue:

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import address.Class1;
import address.Class2;

public class CreateTable {

public void newTableCompare(Class1 class1, Class1 class2,
        ReportDcResultViewDto resultDto, OutputStream outputStream)
        throws FileNotFoundException, IOException {

    Workbook wb = new XSSFWorkbook();

    XSSFSheet sheet = (XSSFSheet) wb.createSheet();
    int rowCount = 1;
    int columnCount = 7;
    ArrayList<String> columnNames = new ArrayList<String>();

    columnNames.add("filename");
    columnNames.add("type");
    columnNames.add("created by");
    columnNames.add("modified by");
    columnNames.add("modification date");
    columnNames.add(class1.getName());
    columnNames.add(class2.getName());

    CreationHelper creationHelper = wb.getCreationHelper();
    // Create
    XSSFRow rowHeader = sheet.createRow(0);
    for (int j = 0; j < columnCount; j++) {
        // create first row
        XSSFCell cell = rowHeader.createCell(j);
        RichTextString richString = creationHelper
                .createRichTextString(columnNames.get(j));
        Font font = wb.createFont();
        font.setBold(true);
        richString.applyFont(font);

        cell.setCellValue(richString);
        CellStyle style = wb.createCellStyle();
        style.setFont(font);

        cell.setCellStyle(style);
    }

    if (CollectionUtils.isNotEmpty(resultDto
            .getClass1ExclusiveViewDtos())) {
        for (ReportDcResultViewExclusiveDto dto : resultDto
                .getClass1ExclusiveViewDtos()) {

            XSSFRow row = sheet.createRow(rowCount);
            for (int j = 0; j < columnCount; j++) {
                XSSFCell cell = row.createCell(j);

                    switch (j) {
                    case 0:
                        cell.setCellValue(dto.getFile().getFilename());
                        break;
                    case 1:
                        cell.setCellValue(dto.getFile().getType()
                                .toString());
                        break;
                    case 2:
                        cell.setCellValue(dto.getFile().getCreatedBy()
                                .getUsername());
                        break;
                    case 3:
                        cell.setCellValue(dto.getModification().getUser()
                                .getUsername());
                        break;
                    case 4:
                        cell.setCellValue(dto.getModification().getDate().toString());
                        break;
                    case 5:
                        cell.setCellValue("yes");
                        break;
                    case 6:
                        cell.setCellValue(" ");
                        break;
                    default:
                        cell.setCellValue("Missing");
                        break;
                    }
                }
                rowCount++;
            }
        }
        for (int k = 0; k < columnCount; k++) {
            sheet.autoSizeColumn(k);
    }
    System.out.println("check rowCount: current="+rowCount);
    wb.write(outputStream);
    outputStream.close();
    wb.close(); 
}
}

I hope this will be of use to somebody.