O
O
Orkhan Hasanli2019-01-16 23:34:45
Java
Orkhan Hasanli, 2019-01-16 23:34:45

What is the best way to implement data export using Apache POI?

Hello!
I thought about writing a simple wrapper for the convenience of exporting data using Apache POI.
It is often necessary to export a List to an xlsx document. How can this be theoretically implemented in order to preserve "universality"?
Thought about using reflection and generics.
Method to be modified:

private void exportData(List<Article> articles) {

    List<Article> articleList = articles;
    Workbook workbook = new XSSFWorkbook();
    CreationHelper creationHelper = workbook.getCreationHelper();
    Sheet sheet = workbook.createSheet("newSheet");

    int rowNum = 0;
    for (Article article : articleList) {

      Row row = sheet.createRow(rowNum++);

      row.createCell(0).setCellValue(article.getArticleTitle());
      row.createCell(1).setCellValue(article.getArticleContent());
    }

    FileOutputStream fileOutputStream = null;
    try {
      fileOutputStream = new FileOutputStream("doc.xlsx");

    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
    try {
      workbook.write(fileOutputStream);
    } catch (IOException e) {
      e.printStackTrace();
    }
    try {
      assert fileOutputStream != null;
      fileOutputStream.close();
    } catch (IOException e) {
      e.printStackTrace();
    }

    try {
      workbook.close();
    } catch (IOException e) {
      e.printStackTrace();
    }

  }

How best to implement the idea?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Cheremisin, 2019-01-17
@azerphoenix

I would look at the visitor pattern. It just suits different features for exporting to different formats - https://refactoring.guru/en/design-patterns/visito...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question