如何使用univocity writer

时间:2015-05-29 10:49:18

标签: java csv export-to-csv

我有一个Java bean A如下

String name;
List<Address> address;

Address再次是一个bean,如下所示

String city;
int pinCode;

当使用@Parsed注释的univocity bean writer处理器时,地址字段被写为csv文件中的对象。如何打印城市和密码值?

这是我生成CSV文件的代码

File csvFile = File.createTempFile("NEW" + ".csv", "");
Writer out = new FileWriter(csvFile);

FixedWidthFieldLengths lengths = new FixedWidthFieldLengths(30, 20);
FixedWidthWriterSettings settings = new FixedWidthWriterSettings(lengths);

// Creates a BeanWriterProcessor that handles annotated fields in the UserVo class.
settings.setRowWriterProcessor(new BeanWriterProcessor<UserVO>(UserVO.class));

// Sets the file headers
settings.setHeaders("Username", "listOfAddresses");

// Creates a writer with the above settings;
FixedWidthWriter writer = new FixedWidthWriter(out, settings);

// Writes the headers specified in the settings
writer.writeHeaders();

// writes a fixed width row with empty values (new UserVO instance).
writer.processRecord(new UserVO());

// writes values of UserVO
writer.processRecords(userVOs);

writer.close();

response().setContentType("text/csv");
response().setHeader("Content-disposition", "attachment;filename=" + csvFile.getName());
return ok(csvFile);

UserVO映射到带有@Parsed注释的输出文件,如下所示

public class UserVO {
    @NullString(nulls = { "?", "-" })
    @LowerCase
    @Parsed
    private String username;

    @Parsed
    private List<Address> listOfAddresses;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public List<Address> getListOfAddresses() {
        return listOfAddresses;
    }

    public void setListOfAddresses(List<Address> listOfAddresses) {
        this.listOfAddresses = listOfAddresses;
    }
}

2 个答案:

答案 0 :(得分:0)

对于您的情况,您可以创建自定义转换类来处理Bean中的任意元素。请查看tutorial的以下部分:在注释中使用您自己的转化

使用您自己的示例,我创建了以下自定义转换来打印集合中的对象:

public class CollectionConversion implements Conversion<String, Collection<?>> {

private String separator = "|";

public CollectionConversion(String[] args) {
    if (args.length > 0) {
        separator = args[0];
    }
}

@Override
public Collection<?> execute(String input) {
    return null;
}

//You only need to implement this one when writing.
@Override
public String revert(Collection<?> input) {
    if (input == null) {
        return "";
    }
    StringBuilder out = new StringBuilder();
    for (Object element : input) {
        if (out.length() > 0) {
            out.append(this.separator);
        }
        out.append(element.toString());
    }
    return out.toString();
}
}

此实现依赖于集合中元素的 toString(),因此我的Address类如下所示:

public class Address {
    String city;
    int pinCode;

    public String toString() {
        return city + " (" + pinCode + ")";
    }
}

现在,在您的UserVO类中,您可以指定地址列表,如下所示:

@Convert(conversionClass = CollectionConversion.class, args = { ";" })
@Parsed
private List<Address> listOfAddresses;

在我的测试中,我创建了一些地址:         ...         writer.processRecord(new UserVO());

    List<Address> addresses = new ArrayList<Address>();
    Address a = new Address();
    a.city = "New York";
    a.pinCode = 14;

    Address b = new Address();
    b.city = "Sydney";
    b.pinCode = 345;

    addresses.add(a);
    addresses.add(b);

    UserVO vo1 = new UserVO();
    vo1.setUsername("User1");
    vo1.setListOfAddresses(addresses);

    List<UserVO> userVOs = new ArrayList<UserVO>();
    userVOs.add(vo1);

    writer.processRecords(userVOs);
    ...

我将第二个字段的长度从20改为50(否则将输出输出)。这将产生:

Username                      listOfAddresses                                   
?                                                                               
user1                         New York (14);Sydney (345)                        

答案 1 :(得分:0)

我正在使用相同的univocity writer将对象写入csv文件。一些数据写为null。在写之前。我正在记录它,我能够看到数据。但是在完成的写作中,它在csv文件中反映为null。

settings.setRowWriterProcessor(new BeanWriterProcessor<Employee>(Employee.class));

writers.writeHeaders("added headers here");

List<Employee> employeeList = service.generatereport(start,enddate);

for(employeel:employeeList) {

//here when i print the values of employeel.getSomethings - i'm getting the value

writer.processRecord(employeel);

//in csv it is null.
}