PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 28, 2022

[FIXED] How to write csv file using common-csv lib

 August 28, 2022     apache-commons, csv, java     No comments   

Issue

I'm using common-csv to write a CSV file from a request body and I'm getting all the records in the same line and with double quotes:

Client Name,Value
"client 1,1.0","client 2,2.0","client 3,53.78","client 4,3.0","client 5555555,4.0","client 6,33.0","client 7,0.0","client 8,8.5"

What I need is:

Client Name, Value
"client 1", 1.0
"client 2", 2.0
"client 3", 53.78 (and so on)

this is the code (partial):

@PostMapping(value = "/v1/csv")
    public ResponseEntity<InputStreamResource> exportCSVV2(@RequestBody ClientDataObjectRequest clientDataObjectRequest){

        String[] csvHeader = {"Client Name","Value"};
        List<List<CompanyChartData>> csvBody = new ArrayList<>();
        csvBody.add(clientDataObjectRequest.getCompanyChartData());

        ByteArrayInputStream byteArrayOutputStream;

        try(
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                CSVPrinter csvPrinter = new CSVPrinter(
                        new PrintWriter(out),
                        CSVFormat.EXCEL.withHeader(csvHeader)
                );
        ) {

            for (List<CompanyChartData> record: csvBody) {
                csvPrinter.printRecord(record);

            }
            csvPrinter.flush();
            byteArrayOutputStream = new ByteArrayInputStream(out.toByteArray());
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }

        InputStreamResource fileInputStream = new InputStreamResource(byteArrayOutputStream);

        String dateFile = new SimpleDateFormat("MM-dd-yyyy").format(new java.util.Date());
        String timeFile = new SimpleDateFormat("HH-mm").format(new java.util.Date());
        String fileName = clientDataObjectRequest.getMetricName().replace(" ","_") + "_" + dateFile + "T" + timeFile;

        HttpHeaders headers = new HttpHeaders();
        headers.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName + ".csv");
        headers.set(HttpHeaders.CONTENT_TYPE, "text/csv");

        return new ResponseEntity<>(
                fileInputStream,
                headers,
                HttpStatus.OK
        );
    }

This code above is generating the response that I do not want. I've tried others stuff like changing the CSVFormat to another standard, also tried using the method "printRecords" instead of "printRecord". I did some research in the documentation but I'm struggling to understand it.


Solution

I found out how to change the outcome.
Instead of using this way:

try(
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                CSVPrinter csvPrinter = new CSVPrinter(
                        new PrintWriter(out),
                        CSVFormat.EXCEL.withHeader(csvHeader)
                );
        ) {

            for (List<CompanyChartData> record: csvBody) {
                csvPrinter.printRecord(record);

            }

I changed to this approach:

try(
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                CSVPrinter csvPrinter = new CSVPrinter(
                        new PrintWriter(out),
                        CSVFormat.DEFAULT.withHeader(csvHeader).withQuoteMode(QuoteMode.NON_NUMERIC)
                );
        ) {

            for (CompanyChartData record: csvBody) {
                csvPrinter.printRecord(record.getClientName(), record.getValue());

            }

And the response was

"Client Name","Value"
"client 1",1.0
"client 2",2.0
"client 3",53.78


Answered By - dcm50
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing