I have object list with many values in object which comes from XML source:
iit.getHomeCurrency().getPrice().toString()
If I put System.out.println(iit.getHomeCurrency().getPrice().toString()); I get succesfully complete list of objects.
But, when I want to convert this object into CSV, using
CSVWriter csvWriter = new CSVWriter(new FileWriter("example.csv"));
csvWriter.writeNext(new String[]{iit.getHomeCurrency().getPrice().toString(),"/n"}
csvWriter.close();
I got only one line in csv file :(
Code:
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();
What shall I change to make java write every object into new row of csv file?
Thank you
答案 0 :(得分:1)
主要问题似乎是您为循环的每次迭代打开一个新文件,移动
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();