Is there an elegant way to Generate Excel spreadsheet from List<POJO>? (JAVA)
In java, Is there a elegant way to Generate Excel spre开发者_高级运维adsheet from List?
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. 
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.
You can try ssio
public class Player {
    @SsColumn(index = 0, name = "Id")
    private long id;
    @SsColumn(index = 1) // the column name will be decided as "Birth Country"
    private String birthCountry;
    @SsColumn(index = 2, typeHandler = FullNameTypeHandler.class) //complex prop type
    private FullName fullName;
    @SsColumn(index = 3) //The enum's name() will be saved. Otherwise, use a typeHandler
    private SportType sportType;
    @SsColumn(index = 4, format = "yyyy/MM/dd") //date format
    private LocalDate birthDate;
    @SsColumn(index = 5, typeHandler = TimestampAsMillisHandler.class)
    //if you prefer saving timestamp as number
    private LocalDateTime createdWhen; 
...
}
  SaveParam<Player> saveParam =
            //Excel-like file. For CSV,  use "new CsvSaveParamBuilder()"
            new OfficeSaveParamBuilder<Player>()  
                    .setBeanClass(Player.class)
                    .setBeans(players)
                    .setOutputTarget(outputStream)
                    .build();
    
    SsioManager ssioManager = SsioManagerFactory.newInstance();
    SaveResult saveResult = ssioManager.save(saveParam);
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论