我正在将用户记录列表导出到我的sprig boot REST应用程序中的csv文件中。我为此使用supercsv maven依赖项。我的“用户和地址”实体类如下所示。
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
我的主控制器类如下。
@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);
使用此数据,我可以将用户名年龄工资数据导出到csv文件中。但是我怎样才能在上面提到的user_headings数组和相应的pojoclassPropertyName数组中传递地址的头,以便我能够将所有用户和用户地址数据导出到我的csv文件中。请给我一个可行的例子。