gpt4 book ai didi

java - 将java对象列表转换为CSV

转载 作者:行者123 更新时间:2023-12-02 10:22:47 25 4
gpt4 key购买 nike

我有一个对象列表,其中包含来自 XML 源的对象中的许多值:

iit.getHomeCurrency().getPrice().toString()

如果我把 System.out.println(iit.getHomeCurrency().getPrice().toString());我成功获得了完整的对象列表。

但是,当我想将此对象转换为 CSV 时,使用

CSVWriter csvWriter = new CSVWriter(new FileWriter("example.csv"));
csvWriter.writeNext(new String[]{iit.getHomeCurrency().getPrice().toString(),"/n"}
csvWriter.close();

我在 csv 文件中只有一行:(

代码:

for(int i=0;i<contentElement.size();i++){
JAXBElement<ListInvoiceType> invoiceTypeElement = (JAXBElement<ListInvoiceType>) contentElement.get(i);
ListInvoiceType listInvoiceType = invoiceTypeElement.getValue();
List<InvoiceType> invoiceTypeList = listInvoiceType.getInvoice();
for(InvoiceType invoiceType:invoiceTypeList ){
InvoiceHeaderType invoiceHeaderType = invoiceType.getInvoiceHead
er();
InvoiceDetailType invoiceDetailType = invoiceType.getInvoiceDetail();

InvoiceItemType iit = null;
InvoiceAdvancePaymentItemType iapit = null;
for(Serializable s:invoiceDetailType.getContent()){
if(s instanceof JAXBElement) {
JAXBElement<?> element = (JAXBElement)s;
if(element.getValue() instanceof InvoiceItemType){
iit = (InvoiceItemType)element.getValue();
}
else if(element.getValue() instanceof InvoiceAdvancePaymentItemType){
iapit = (InvoiceAdvancePaymentItemType)element.getValue();
}
else{
throw new Exception("xx");
}
}

else if(s instanceof String){

}
else{
throw new Exception("xx");
}


if(iit!=null){
CSVWriter csvWriter = new CSVWriter(new FileWriter("example.csv"));

csvWriter.writeNext(new String[]{iit.getHomeCurrency().getPrice().toString(), iit.getCentre().getIds() ,invoiceHeaderType.getDate().toString(),invoiceHeaderType.getInvoiceType().value(),"\r\n"});

csvWriter.close();

我应该改变什么才能让java将每个对象写入csv文件的新行?

谢谢

最佳答案

主要问题似乎是您为循环的每次迭代打开一个新文件,移动

CSVWriter csvWriter = new CSVWriter(new FileWriter("example.csv"));

for 循环之前

CSVWriter csvWriter = new CSVWriter(new FileWriter("example.csv"));
for(Serializable s:invoiceDetailType.getContent()){
if(s instanceof JAXBElement) {
//...
}

if( iit !=n ull){
csvWriter.writeNext(new String[]{iit.getHomeCurrency().getPrice().toString(), iit.getCentre().getIds() ,invoiceHeaderType.getDate().toString(),invoiceHeaderType.getInvoiceType().value(),"\r\n"});
}

并在for循环后关闭文件

} //end for loop

csvWriter.close();

关于java - 将java对象列表转换为CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54204671/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com