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.