简体   繁体   中英

Converting Excel file (xlsx) into Json

I will be reading an excel file and convert it into json and create json file.

Code: (I have tried)

public static void main(String[] args) throws IOException, InvalidFormatException {

    // Creating a Workbook from an Excel file (.xls or .xlsx)
    Workbook workbook = WorkbookFactory.create(new File(
            "C:\\Users\\SomeExcel.xlsx"));

    Sheet sheet = workbook.getSheetAt(0);

    // Create a DataFormatter to format and get each cell's value as String
    DataFormatter dataFormatter = new DataFormatter();
    System.out.println("\n\nIterating over Rows and Columns using for-each loop\n");
    for (Row row : sheet) {
        for (Cell cell : row) {
            String cellValue = dataFormatter.formatCellValue(cell);
            System.out.print(cellValue + "\t");
        }
        System.out.println();
    }

    // Closing the workbook
    workbook.close();
}

I am kinda stuck with converting cell content into json key-value pair.

Please check and let me know.

You can read the excel with Apache POI and generate Json using JsonGenerator:

JsonFactory factory = new JsonFactory();

JsonGenerator generator = factory.createGenerator(
    new File("data/output.json"), JsonEncoding.UTF8);

generator.writeStartObject();
generator.writeStringField("stringField", "stringValue");
generator.writeNumberField("numericField", 25);
generator.writeEndObject();

generator.close();

See: Oracle Java JSonGenerator

From the question it isn't quite clear where you stuck at, I assuming you figured out the reading from excel part, when reading you just need to insert the cell's values to a Map and than dump it to json, I used Jackson lib as follows

public static void main(String[] args)  {
    Map<String, String> map = new HashMap<>();

    // this should happen in a for loop (reading from the excel file)
    map.put("ABCD", "hello");
    map.put("key1", "value1");

    try {
        String json = new ObjectMapper().writeValueAsString(map);
        System.out.println(json);
    } catch (JsonProcessingException e) {
        e.printStackTrace();

    }
}

Thanks for the other answers, with that information i have tried and found the solution.

Code:

FileInputStream file = new FileInputStream(new File("C:\\Users\\SomeExcel.xlsx"));

// Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);

// Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);

SomePojo somePojo = new SomePojo();

Map<Object, Object> x = new LinkedHashMap<>();
// ignoring header for that I've +1 in loop
for(int i = sheet.getFirstRowNum() + 1; i<=sheet.getLastRowNum(); i++)
{

    Row row = sheet.getRow(i);
    for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
        Cell ce = row.getCell(j);
        if (j == 0) {
            // If you have Header in text It'll throw exception because it won't get
            // NumericValue
            somePojo.setName(ce.getStringCellValue());
        }
        if (j == 1) {
            somePojo.setValue(ce.getStringCellValue());
        }
        // Same for third column
    }
    x.put(somePojo.getName(), somePojo.getValue());
}

// Object to JSON in String
ObjectMapper mapper = new ObjectMapper();
// Object to JSON in file
mapper.writeValue(new File("C:\\some.json"),x);
// Print in console
String jsonFromMap = mapper.writeValueAsString(x);
file.close();

SomePojo.java

public String name;
public String value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM