Home » excel » export mysql data to excel from Java using Apache POI

export mysql data to excel from Java using Apache POI

Posted by: admin April 23, 2020 Leave a comment


I have the class MysqlToXls copied from here:

I edited the class making a constructor that doesn’t need any parameter in this way:

public MysqlToXls()
throws ClassNotFoundException, SQLException {

    // Create MySQL database connection

    String url = "jdbc:mysql://localhost/Spinning?user=root&useUnicode=true&characterEncoding=utf8";
    connection = DriverManager.getConnection(url);

While there is not any guide I try to do myself and I’m not able.

  MysqlToXls m=new MysqlToXls();
  m.generateXls("utente", "utenti.xls");

But there are no errors and the file utenti.xls remains blank.
Does someone know where is the problem?

How to&Answers:

It is possible that you have to explicitly close the outputStream, so insted of doing this:

xlsWorkbook.write(new FileOutputStream(filename));

you should try to do something like this:

FileOutputStream fos = new FileOutputStream(filename);


the only problem was the path of the file. I was trying to save the file in one folder of the project (with a relative path), while if I give the absolute path (f.e. on the desktop) it works perfectly!