Reputation: 450
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.
Class User{
private String userId;
private String name;
private int age;
private double salary;
private List<Address> addresses;
}
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.
Upvotes: 2
Views: 2333
Reputation: 26
As you added other properties (name, age, salary) of User class in the string array pojoclassPropertyName, you have to add the addresses property.
So the declaration should be like below:
String[] pojoclassPropertyName = { "name", "age", "salary", "addresses"};
Then you have to override toString() method in the Address class to return the data of the class address. This can be something like below:
class Address{
private String id;
private String city;
private String street;
private String country;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
@Override
public String toString() {
return getId() + " " + getStreet() + " " + getCity() + " " + getCountry();
}
}
This will write the addresses in csv file as you return in toString() method and if there is more than one address then it will be written with comma separated.
Upvotes: 0