Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to export List of objects to .CSV in Java using OpenCSV?

I try to generate a .csv file in Java using OpenCSV. I want to generate results without hardcoding.

I have an entity with has fields like: Id, Title, Overview, etc.
In List movies I store all data from database.

I want to write this list in .csv without tell headers or other things.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Example.

…writeToCSV(Movie.class) not writeToCSV("ID", "Title’, etc)

In first step, I used Apache POI, but he don’t work properly.

@Slf4j
@Setter
@NoArgsConstructor
public class CSVHelper {
    private CSVFormat csvFormat;
    private PrintWriter printWriter;
    private CSVPrinter csvPrinter;


    public void writeHeader(Class<?> c) {
        List<String> headers = getHeaders(c);
        try {
            setCsvPrinter(new CSVPrinter(printWriter, csvFormat));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        headers.forEach(header -> {
            try {
                csvPrinter.print(header);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }

    public void writeToCsv(List<?> list, Class<?> c) {
        writeHeader(c);
        List<String> headers = getHeaders(c);
        try {
            setCsvPrinter(new CSVPrinter(printWriter, csvFormat));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        list.forEach(o -> {
            try {
                csvPrinter.println();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            headers.forEach(header -> {
                try {
                    Method method = c.getMethod("get" + header.substring(0, 1).toUpperCase() + header.substring(1));
                    String value = String.valueOf(method.invoke(o));
                    csvPrinter.print(value);

                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
        });
    }

    private static List<String> getHeaders(Class<?> c) {
        List<Field> fields = List.of(c.getDeclaredFields());
        return fields.stream().map(Field::getName).collect(Collectors.toList());
    }
}

I like to use direct object to method, without any code from me. This code is working but on any change to the entity it does’t work.

>Solution :

From the documentation:

The easiest way to write CSV files will in most cases be
StatefulBeanToCsv, which is simplest to create with
StatefulBeanToCsvBuilder, and which is thus named because there used
to be a BeanToCsv.Thankfully, no more.

 // List<MyBean> beans comes from somewhere earlier in your code.
 Writer writer = new FileWriter("yourfile.csv");
 StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer).build();
 beanToCsv.write(beans);
 writer.close();

Source: http://opencsv.sourceforge.net/#writing_from_a_list_of_beans

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading