I am exporting a list of user records to csv file in my sprig boot REST application. I am using supercsv maven dependency for this. My entity class for User & Address is like below.
User
Class User{
private String userId;
private String name;
private int age;
private double salary;
private List<Address> addresses;
}
Address
class Address{
private String id;
private String city;
private String street;
private String country;
}
enter code here
And my main controller class is like below.
@GetMapping("/exportCsv")
public ResponseEntity<?> exportCsv(HttpServletResponse response) {
try {
List<User> userList = getUserList();
String csvFileName = "users.csv";
response.setContentType("text/csv");
// creates mock data
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"",
csvFileName);
response.setHeader(headerKey, headerValue);
// write to csv file //
ICsvBeanWriter csvWriter = new CsvBeanWriter(response.getWriter(),
CsvPreference.STANDARD_PREFERENCE);
String[] user_headings = { "Name", "Age", "Salary" };
String[] pojoclassPropertyName = { "name", "age", "salary"
};
csvWriter.writeHeader(account_headings);
if(null!=userList && !userList.isEmpty()){
for (User user : userList) {
csvWriter.write(user, pojoclassPropertyName);
}
}
csvWriter.close();
}catch(Exception e) {
e.printStackTrace();
}
return new ResponseEntity<>("successfully export to csv ",HttpStatus.OK);
with this data i can able to export the user name age salary data to csv file. but how could I pass the header for address in user_headings array and corresponding pojoclassPropertyName array mentioned above so that i can able to export all user and user address data to my csv file. kindly suggest me with any working example.