Export. xlsx with Java

Asked

Viewed 2,460 times

0

I am trying to export a spreadsheet with Java, specifically a file .xlsx, 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 the fileOut the extent .xlsx, at the time of opening the file, says that the file extension 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?

2 answers

1


To create an Excel spreadsheet in the format .xlsx, it is necessary to use with import of Apache POI-XSSF/SXSSF. the HSSF only works with spreadsheets .xls.

You can convert the code already made to that 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 the HSSF, only changes the call and import of that .jar.

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(); 
  • but in this case, it is not to pick up a file .xlsx to read? tested here and did not work, I want to generate a file .xlsx.

Browser other questions tagged

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