简体   繁体   中英

How to write to csv using CSVWriter from a comma separated key:value list of strings

I have a list of strings in k:v format as follows:

List<String> data = new ArrayList();

data[0] = "acctHolderName:null,auctEndDt:2021-04-23,auctTitle:2 X BUCKLE RACING SEAT BELT HARNESS,bankName:null,buyerId:22494074,byrCntryId:1,cardlastFourDigits:1234,checkoutStatus:2,cityShipAddr:null,ckCompleteDate:2021-04-04 08:06:27,cnvstnIdList:null,countryShipAddr:null,createdTime:2021-04-04 08:06:27,firstTrackingDtlId:17824011,gmvBuyerLcAmt:59.990000000,gmvSellerLcAmt:59.9900000000000000,gmvUsdAmt:59.9900000000000000,instrumentType:null,itemId:4966893,itemPrice:59.99,itemSiteId:100,nonPciAccountId:null,omsExternalRfrncId:17-06848-86625,omsOrderId:170000684886625,orderStsId:0,paidDate:2021-04-04 08:06:27,paymentMethod:[34],"


data[1] = "acctHolderName:null,auctEndDt:2021-04-22,auctTitle:2 X BELT,bankName:null,buyerId:22491011,byrCntryId:2,cardlastFourDigits:5678,checkoutStatus:2,cityShipAddr:null,ckCompleteDate:2020-05-04 08:06:26,cnvstnIdList:null,countryShipAddr:null,createdTime:2020-05-04 08:06:27,firstTrackingDtlId:17834022,gmvBuyerLcAmt:59.990000000,gmvSellerLcAmt:59.9900000000000000,gmvUsdAmt:59.9900000000000000,instrumentType:null,itemId:4955893,itemPrice:59.99,itemSiteId:101,nonPciAccountId:null,omsExternalRfrncId:17-06848-86625,omsOrderId:170000684886625,orderStsId:0,paidDate:2021-03-04 08:06:27,paymentMethod:[34],"

How can I write to csv using opencsv CSVWriter where before colon is a column name and after it a value.

So for example in above case: acctHolderName:null , acctHolderName is a column name and null is its value.

You can use the method CSVWriter.writeAll(List<String[]> list) to write your whole list. In order to get the apropriate data from your List in the desired format List<String[]> you just need to extract the headers, for example from the first element of the list and all the values you need from all elements of the list. To do so, just split each string at , , stream over the resulting array, split once again at : map to first elemnt for column names and to second element for values.

Example, assuming you data is well formated and all lines have the same number of "columns", here is a first approach without exception handling:

public static void writeListToFile(List<String> list, String fileName) throws IOException {
    
    List<String[]> out = new ArrayList<>();
    
    //extract headers
    String[] columns = Arrays.stream(list.get(0).split(","))
                             .map(str -> str.split(":")[0])
                             .toArray(String[]::new);
    
    //extract values
    List<String[]> rows = list.stream()
                              .map(line -> Arrays.stream(line.split(","))
                                                 .map(str -> str.split(":")[1])
                                                 .toArray(String[]::new))
                              .collect(Collectors.toList());
    
    out.add(columns);
    out.addAll(rows);
    
    try (CSVWriter writer = new CSVWriter(new FileWriter(fileName))) {
        writer.writeAll(out);
    }
}

and call above method like

public static void main(String[] args) throws IOException {
    List<String> data = List.of("acctHolderName:null,auctEndDt:2021-04-23,auctTitle:2 X BUCKLE RACING SEAT BELT HARNESS,bankName:null,buyerId:22494074,byrCntryId:1,cardlastFourDigits:1234,checkoutStatus:2,cityShipAddr:null,ckCompleteDate:2021-04-04 08:06:27,cnvstnIdList:null,countryShipAddr:null,createdTime:2021-04-04 08:06:27,firstTrackingDtlId:17824011,gmvBuyerLcAmt:59.990000000,gmvSellerLcAmt:59.9900000000000000,gmvUsdAmt:59.9900000000000000,instrumentType:null,itemId:4966893,itemPrice:59.99,itemSiteId:100,nonPciAccountId:null,omsExternalRfrncId:17-06848-86625,omsOrderId:170000684886625,orderStsId:0,paidDate:2021-04-04 08:06:27,paymentMethod:[34],",
                                "acctHolderName:null,auctEndDt:2021-04-22,auctTitle:2 X BELT,bankName:null,buyerId:22491011,byrCntryId:2,cardlastFourDigits:5678,checkoutStatus:2,cityShipAddr:null,ckCompleteDate:2020-05-04 08:06:26,cnvstnIdList:null,countryShipAddr:null,createdTime:2020-05-04 08:06:27,firstTrackingDtlId:17834022,gmvBuyerLcAmt:59.990000000,gmvSellerLcAmt:59.9900000000000000,gmvUsdAmt:59.9900000000000000,instrumentType:null,itemId:4955893,itemPrice:59.99,itemSiteId:101,nonPciAccountId:null,omsExternalRfrncId:17-06848-86625,omsOrderId:170000684886625,orderStsId:0,paidDate:2021-03-04 08:06:27,paymentMethod:[34],");

    writeListToFile(data, "C:\\Users\\Atihska\\Downloads\\mydata.csv");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM