Apache POI - Error opening file generated in MS Excel

1

Hello,

I'm running some tests with Apache POI , version 3.15 , for .xlsx reporting using the sample code below, only to generate a file:

package exemplousoapachepoi;

import java.io.*;
import org.apache.poi.xssf.usermodel.*;
/**
 *
 * @author lpaiva
 */
public class ExemploUsoApachePOI {

    /**
     * @param args the command line arguments
     * @throws java.lang.Exception
     */
    public static void main(String[] args) throws Exception{
      //Cria planilha vazia
      XSSFWorkbook workbook = new XSSFWorkbook(); 
      //Cria arquivo com nome específico
      FileOutputStream out = new FileOutputStream(new File("pastadetrabalho.xlsx"));
      // Escreve planilha no arquivo 
      workbook.write(out);
      // Fecha arquivo
      out.close();
      System.out.println("pastadetrabalho.xlsx criado com sucesso!");
    } 
}

The file is generated correctly, but when you open this file in MS Excel 2016 the following error message is displayed:

Does anyone know how I can fix this problem?

Thank you in advance for your attention.

    
asked by anonymous 23.11.2016 / 17:11

2 answers

1

The solution seems a bit silly, I continued testing with spreadsheets yesterday and found that just instantiating XSSFWorkbook does not generate a complete Workbook, you need to at least insert a spreadsheet into the folder for it to be valid. In this case with a line of code:

XSSFSheet spreadsheet = workbook.createSheet("Planilha 01");

With this the Workbook opened without problems, here is a complete code for creating a Workbook with a Worksheet and inserting some information into this Worksheet:

package exemplousoapachepoi;

import java.io.*;
import java.util.*;
import org.apache.poi.xssf.usermodel.*;

public class ExemploUsoApachePOI {

    /**
     * @param args the command line arguments
     * @throws java.lang.Exception
     */
    public static void main(String[] args) throws Exception{
      // Cria planilha vazia
      XSSFWorkbook workbook = new XSSFWorkbook();
      // Cria planilha em branco
      XSSFSheet spreadsheet = workbook.createSheet("Planilha 01");

      // Cria objeto coluna
      XSSFRow row;

      // Construção das informações que irão preencher a planilha
      Map <String, Object[]> empinfo = new TreeMap <String, Object[]>();
      // Inserção de dados em empinfo
      empinfo.put("1", new Object[] {"ID", "NOME", "FUNÇÃO" });
      empinfo.put("2", new Object[] {"01", "Leandro", "Diretor" });
      empinfo.put("3", new Object[] {"02", "João Paulo", "Assessor" });
      empinfo.put("4", new Object[] {"03", "Daniel", "Gerente" });
      empinfo.put("5", new Object[] {"04", "Nilson", "Operador" });
      empinfo.put("6", new Object[] {"05", "Gabriel", "Assistente" });

      // Interação entre dados e escrita na planilha
      Set <String> keyid = empinfo.keySet();
      int rowid = 0;

      for(String key : keyid)
      {
          row = spreadsheet.createRow(rowid++);
          Object[] objectArr = empinfo.get(key);
          int cellid = 0;

          for(Object obj : objectArr)
          {
              XSSFCell cell = row.createCell(cellid++);
              cell.setCellValue((String)obj);
          }
      }

      //Cria arquivo com nome específico
      FileOutputStream out = new FileOutputStream(new File("pastadetrabalho.xlsx"));
      // Escreve planilha no arquivo 
      workbook.write(out);
      // Fecha arquivo
      out.close();
      System.out.println("pastadetrabalho.xlsx criado com sucesso!");
    } 
}

I found a tutorial , covering topics such as library configuration and usage, key functions, examples of reading and writing files. It helped me a lot.

If you have Netbeans IDE , simply download and unzip the library folder, go to Project Properties, in the Libraries Category add the JAR files that are in the library folder, as shown below:

I found the Apache POI library a good solution for generating MS Excel files using Java, anyone who has an interest can download it from the official Apache website, thanks to anyone who tried to help or was interested.

    
24.11.2016 / 12:47
0

Try to make a out.flush() before doing out.close() .

    
23.11.2016 / 21:18