1

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.

5
  • How is this related to apache-poi? Commented Aug 22, 2022 at 13:34
  • I did not find anything specific in Apache POI to automatically select the fields from a certain class. I resorted to writing the code and just sending the fields. It was a headache until I selected all the fields, the methods for the getters. After I got all the names I wrote them with apache poi Commented Aug 22, 2022 at 13:40
  • I didn't want to have hradcoded headers, the fields will differ over time, I can't rely on that Commented Aug 22, 2022 at 13:41
  • This question is not about apache-poi. So it also should not tagged as such. Please remove that tag. Commented Aug 22, 2022 at 13:44
  • Related: StatefulBeanToCsv with Column headers Commented Aug 22, 2022 at 13:52

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.