Apache POI - Error opening file generated in MS Excel

Asked

Viewed 899 times

1

Hello,

I’m running some tests with Apache POI, version 3.15, for reporting purposes .xlsx, using the example 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, however while opening this file in MS Excel 2016 the following error message is displayed:

Erro ao abrir pastadetrabalho.xlsx

Does anyone know how I can be fixing this problem?

Thank you in advance for your attention.

2 answers

1


The solution seems kind of silly, I continued to perform tests yesterday with the generation of spreadsheets and found that just instantiate Xssfworkbook does not generate a complete workbook, it is necessary to at least insert a worksheet into the workbook for it to be valid. In this case with a code line:

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

With this the Workbook opened without problems, below follows a complete code of the creation of a Workbook with a Worksheet and the insertion of some information within 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 (in English), addresses topics such as: library configuration and use, main functions, reading and writing examples in archives. It has helped me a lot.

If using the Netbeans IDE, just download and unzip the library folder, go to Project Properties, in Libraries Category add the JAR files that are in the library folder, as image below:

inserir a descrição da imagem aqui

I found the Apache POI library a good solution for generating MS Excel files using Java, who is interested can download on the official Apache website, thank those who tried to help or had interest.

0

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.