Home » excel » Is there an elegant way to Generate Excel spreadsheet from List<POJO>? (JAVA)

Is there an elegant way to Generate Excel spreadsheet from List<POJO>? (JAVA)

Posted by: admin May 14, 2020 Leave a comment

Questions:

In java, Is there a elegant way to Generate Excel spreadsheet from List?

How to&Answers:

There are two possible and radically different approaches:

  • Write a CSV file. That’s comma-separated, you just write out your fields, separated by commas, into a file with a .csv extension. Excel can read that just fine and it’s dramatically simple.

  • Use Apache/Jakarta POI, a library, to write perfectly formatted, Office-compatible Excel files (Excel 95, 2003, … various standards). This takes a bit more work.

Answer:

As a previous answer suggests, CSV is an easy way to do this, but Excel has a habit of inferring data types – for example, if a string looks like a number, it will be formatted as a number, even if you have double-quoted it. If you want more control, you can try generating Excel XML, which in your case may be using a template, and generating a table that looks a little bit like an HTML table. See an example of a simple Excel XML document.

Answer:

Yes. With sep4j you can do it in one line after defining the header with a HashMap.

    Collection<User> users = Arrays.asList(user1, user2);
    LinkedHashMap<String, String> headerMap = new LinkedHashMap<String, String>();
    headerMap.put("userId", "User Id");  //"userId" is a property of User class.
                        // "User Id" will be the column header in the excel.
    headerMap.put("firstName", "First Name");
    headerMap.put("lastName", "Last Name");

    ExcelUtils.save(headerMap, users, outputStream);