Exporting an .xlsx with Java

0

I'm trying to export a spreadsheet with Java, specifically a .xlsx file, but I'm not getting it.

I'm doing it this way and it's working, but it only works by putting the extension .xls :

HSSFWorkbook workbook = new HSSFWorkbook();
String PathTillProject = System.getProperty("user.dir");
FileOutputStream fileOut = null;

fileOut = new FileOutputStream(PathTillProject + "/src/Export.xls");
workbook.write(fileOut);

If I put in fileOut the extension .xlsx , at the time of opening the file, it says that the extension of the file is not valid.

I'm importing the following file:

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

What should I do to be able to export with another extension?

    
asked by anonymous 10.10.2018 / 17:36

2 answers

1

To create an Excel worksheet in .xlsx format, you must use it with the Apache POI-XSSF/SXSSF import. HSSF only works with .xls worksheets.

You can convert the code already made to this code:

//criar uma planilha
XSSFWorkbook wb = new XSSFWorkbook();

//pegar o diretório do usuário e criar um arquivo com o determinado nome
String PathTillProject = System.getProperty("user.dir");
FileOutputStream fileOut = new FileOutputStream(PathTillProject + "/src/Export.xls");

//criar várias abas
XSSFSheet abaPrimaria = wb.createSheet("ABA 1");
XSSFSheet abaSecundaria = wb.createSheet("ABA 2");

//criar linhas (passar o nome da aba onde deseja criar)
XSSFRow primeiraLinha = abaPrimaria.createRow(0);
XSSFRow segundaLinha = abaPrimaria.createRow(0);

//criar uma célula em uma linha (passar o nome da linha onde deseja criar)
XSSFCell primeiraCelulaColuna = primeiraLinha.createCell(0);
XSSFCell segundaCelulaColuna = primeiraLinha.createCell(1);

//escrever tudo o que foi feito no arquivo
wb.write(fileOut);

//fecha a escrita de dados nessa planilha
wb.close();

Basically, it follows the same parameters as HSSF , it only changes the call and the .jar import.

    
18.10.2018 / 05:02
0

For xlsx you should use XSSFWorkbook instead of HSSFWorkbook. example:

    InputStream ExcelFileToRead = new FileInputStream("C:/Test.xlsx");
    XSSFWorkbook  wb = new XSSFWorkbook(ExcelFileToRead);

    XSSFWorkbook teste = new XSSFWorkbook(); 
    
10.10.2018 / 17:44