JSON Question

Convert XLS to JSON with JAVA

I have an XLS file that you want to convert to json and write it to txt. I understand how to read the XLS file, but I have no idea how to convert it to json. Can you show how to implement it in my example.Please.

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.json.JSONObject;
import org.json.simple.JSONArray;
import java.io.*;
import java.util.Iterator;

public class App {
public static void main(String[] args) throws IOException {
try {
FileInputStream file = new FileInputStream(new File("C:/Users/MyName/Desktop/book.xls"));

Workbook wb = new HSSFWorkbook(file);
Sheet sheet = wb.getSheetAt(0);

Iterator<Row> iterator = sheet.iterator();
while (iterator.hasNext()) {
Row row = iterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println("");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Answer

Use some of existing JSON libraries, let's say GSON.

Exact JSON form is depending on how you want information to be encoded.

You can have one list for XLS column names and then lists of values. Other way would be to represent each XLS row as embed JSON object (where key will be column name and value actual column value).

GSON API is really simple.