I get a JSON response as one single string like below. This string should be extracted into a 2-dimensional array.
\t
appears in the response
it has to be in a new cell in the current row\n
appears it has to increment a row number and write in a new rowResponse:
"type": "TABLE",
"data": "Col_1\tCol_2\tCol_3\nName_1\tPlace_1\tAnimal_1\nName_2\tPlace_2\tAnimal_2\nName_3\tPlace_3\tAnimal_3\n"
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_1\tCol_2\tCol_3\nName_1\tPlace_1\tAnimal_1\nName_2\tPlace_2\tAnimal_2\nName_3\tPlace_3\tAnimal_3\n";
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: