Storing a Json response containing n and t in a 2 dimentional array in Java and write to Excel using POI

I get a JSON response as one single string like below. This string should be extracted into a 2-dimensional array.

  1. Wherever the t appears in the response it has to be in a new cell in the current row
  2. Wherever the n appears it has to increment a row number and write in a new row
  3. Write the array list in excel using Apache POI.

Response:

"type": "TABLE",
"data": "Col_1tCol_2tCol_3nName_1tPlace_1tAnimal_1nName_2tPlace_2tAnimal_2nName_3tPlace_3tAnimal_3n"

Answer

You need to split your response using n which becomes the rows in the excel and then from the row split using t which becomes the column values.

import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ApachePOIExcelWrite {

  public static void main(String[] args) throws IOException {
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("Java Books");

    String response =
        "Col_1tCol_2tCol_3nName_1tPlace_1tAnimal_1nName_2tPlace_2tAnimal_2nName_3tPlace_3tAnimal_3n";

    int rowCount = 0;

    String rows[] = response.split("n");
    for (String rowInfo : rows) {
      Row row = sheet.createRow(++rowCount);

      int columnCount = 0;
      String[] colInfo = rowInfo.split("t");
      for (String column : colInfo) {
        Cell cell = row.createCell(++columnCount);
        cell.setCellValue(column);
      }

    }

    try (FileOutputStream outputStream = new FileOutputStream("JavaBooks.xlsx")) {
      workbook.write(outputStream);
    }
  }
}

Output:

Output