0

Here I have a excel file named Merged.xlsx. The figure of this is as:- enter image description here

and I want this data to be displayed in a JSON format as:-

{
  "Cars":[
    {"SellerName":"govinda lamgade","Seller Address":"-Dallu,Kathmandu",...},

  ],
  "Motorcycle":[
    {Same as above},
  ]
}

So far I have got the result as

{"rows":[{"cell":["Skoda Rapid On Sale And Exchange"," govinda lamgade ","- Dallu, Kathmandu","19-06-2020",1450000.0,"https://cdn.hamrobazaar.com/21...

which is not the one that I wanted. The code is as:-

    String excelFilePath = "E:\\Merged.xlsx";
    FileInputStream fileInputStream = new FileInputStream(excelFilePath);
    Workbook workbook = new XSSFWorkbook(fileInputStream);

    Sheet sheet = workbook.getSheetAt(0);
    JsonObject jsonObject = new JsonObject();
    JsonArray rows = new JsonArray();
    Iterator<Row> rowIterator = sheet.iterator();
    while(rowIterator.hasNext()){
        Row row = rowIterator.next();

        if(row.getRowNum() == 0) {
            continue;
        }
        else{
            JsonObject jRow = new JsonObject();
            JsonArray cells = new JsonArray();
            Iterator<Cell> cellIterator = row.cellIterator();
            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
               
                switch (cell.getCellType()) {
                    case Cell.CELL_TYPE_NUMERIC:
                        cells.add(cell.getNumericCellValue());
                        break;
                    case Cell.CELL_TYPE_STRING:
                        cells.add(cell.getStringCellValue());
                        break;
                }
                jRow.add("cell",cells);
                rows.add(jRow);
            }
            jsonObject.add("rows", rows);
        }
        System.out.println(jsonObject.toString());
        fileInputStream.close();
    }
}

}

Thank You

1 Answer 1

1

You can do this as follows;

Assumptions:

  • This sheet only contains Car related data
  • No empty rows in the sheet
  • All rows have data value for each column

Important:

You have to give the expected json key for each json value as the column name in the excel sheet (eg:- put sellerName as column name instead of Seller Name in the excel file)

Required imports;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import java.util.*;

You should get Cell data and put to a HashMap and then convert the HashMap to a JsonElement;

String excelFilePath = "E:\\Merged.xlsx";
FileInputStream fileInputStream = new FileInputStream(excelFilePath);
Workbook workbook = new XSSFWorkbook(fileInputStream);

Sheet sheet = workbook.getSheetAt(0);

JsonArray carArray = new JsonArray();
List<String> columnNames = new ArrayList<>();

Gson gson = new Gson();

// Get column names
Row row = sheet.getRow(0);
for (Iterator<Cell> it = row.cellIterator(); it.hasNext(); ) {
    Cell cell = it.next();
    columnNames.add(cell.getStringCellValue());
}

Iterator<Row> rowIterator = sheet.iterator();    
while (rowIterator.hasNext()) {
    row = rowIterator.next();
    if (row.getRowNum()==0) {
        continue;
    }
    Iterator<String> columnNameIterator = columnNames.iterator();
    Iterator<Cell> cellIterator = row.cellIterator();

    // Create a new map for the row
    Map<String, Object> newCarMap = new HashMap<>();
    while (cellIterator.hasNext()) {
        Cell cell = cellIterator.next();
        String columnName = columnNameIterator.next();

        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC:
                newCarMap.put(columnName, cell.getNumericCellValue());
                break;
            case Cell.CELL_TYPE_STRING:
                newCarMap.put(columnName, cell.getStringCellValue());
                break;
        }
    }
    // Convert the map to `JsonElement`
    JsonElement carJson = gson.toJsonTree(newCarMap);
    // Add the `JsonElement` to `JsonArray`
    carArray.add(carJson);
}
// Add the `JsonArray` to `completeJson` object with the key as `Cars`
JsonObject completeJson = new JsonObject();

completeJson.add("Cars", carArray);

If you print the completeJson;

{
  "Cars": [
    {
      "price": 111111,
      "imageUrl": "https://example_url_1",
      "sellerAddress": "address_1",
      "sellerName": "name_1",
      "date": "12-07-2020"
    },
    {
      "price": 222222,
      "imageUrl": "https://example_url_2",
      "sellerAddress": "address_2",
      "sellerName": "name_2",
      "date": "19-06-2020"
    }
    // rest of the car json objects will come here
  ]
}

Like wise you can create the Motorcycle json array. When adding MotorCycle JsonArray to completeJson, put the key as Motorcycle (or the key you prefer)

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.