Home > Back-end >  Is there a way to export List of objects to .CSV in Java using OpenCSV?
Is there a way to export List of objects to .CSV in Java using OpenCSV?

Time:08-24

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.

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.

CodePudding user response:

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

  • Related