我如何获得Excel数据并将其转换为JSON

时间:2017-06-28 06:28:30

标签: java json excel

我想阅读excel文件(.xls,.xlsx)并将其转换为JSON格式并保存。 这是一个代码,使我能够从excel文件中读取数据,但我无法获得如何以JSON格式放置数据。 任何人都可以帮助我。

public class ReadExcelFile {
private static XSSFWorkbook mybook;
static String fileLocation = "D://Traniee-SPG//Book1.xlsx";

public static void main(String[] args){
    try{
        File newFile = new File(fileLocation);
        FileInputStream fIO = new FileInputStream(newFile);
        mybook = new XSSFWorkbook(fIO);         //finds the Excelfile
        XSSFSheet mySheet = mybook.getSheetAt(0);// Return first sheet from the XLSX workbook
        Iterator<Row> rowIterator = mySheet.iterator(); //create a cursor called iterator to all rows in sheet
        Row r;
        Cell c;
        //to travel into the Excel spreadsheet
        while(rowIterator.hasNext())    {
             r = rowIterator.next();
            //Cursor points to row
            Iterator<Cell> cell_Iterator = r.cellIterator();
            while(cell_Iterator.hasNext())  {
                 c = cell_Iterator.next();
                //Cursor points to cell
                switch (c.getCellType())    {
                case Cell.CELL_TYPE_STRING:
                    System.out.print(c.getStringCellValue()+"\t");
                    //System.out.println("Case String");
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    System.out.print(c.getNumericCellValue()+"\t");
                    //System.out.println("Case number");
                    break;
                case Cell.CELL_TYPE_BOOLEAN:
                    System.out.print(c.getBooleanCellValue()+"\t");
                    System.out.println("Case boolean");
                    break;
                case Cell.CELL_TYPE_FORMULA:
                    System.out.print(c.getCellFormula()+"\t");
                    //System.out.println("Case formula");
                    break;
                default:
                }                   
            }
            System.out.println(" ");//next to display in table format
       }            
        mybook.close();
        fIO.close();
    }
    catch(FileNotFoundException ef){
        ef.printStackTrace();
    }
    catch(IOException ei){
        ei.printStackTrace();
    }
}

}

5 个答案:

答案 0 :(得分:2)

使用Gson给出的事实是每张纸的第一行是列名:

public static JsonObject getExcelDataAsJsonObject(File excelFile) {

    JsonObject sheetsJsonObject = new JsonObject();
    Workbook workbook = null;

    try {
        workbook = new XSSFWorkbook(excelFile);
    } catch (InvalidFormatException | IOException e) {
        TestLogUtils.logErrorMessage(
                "ExcelUtils -> getExcelDataAsJsonObject() :: Exception thrown constructing XSSFWorkbook from provided excel file.  InvalidFormatException | IOException => "
                        + TestLogUtils.convertStackTraceToString(e));
    }

    for (int i = 0; i < workbook.getNumberOfSheets(); i++) {

        JsonArray sheetArray = new JsonArray();
        ArrayList<String> columnNames = new ArrayList<String>();
        Sheet sheet = workbook.getSheetAt(i);
        Iterator<Row> sheetIterator = sheet.iterator();

        while (sheetIterator.hasNext()) {

            Row currentRow = sheetIterator.next();
            JsonObject jsonObject = new JsonObject();

            if (currentRow.getRowNum() != 0) {

                for (int j = 0; j < columnNames.size(); j++) {

                    if (currentRow.getCell(j) != null) {
                        if (currentRow.getCell(j).getCellTypeEnum() == CellType.STRING) {
                            jsonObject.addProperty(columnNames.get(j), currentRow.getCell(j).getStringCellValue());
                        } else if (currentRow.getCell(j).getCellTypeEnum() == CellType.NUMERIC) {
                            jsonObject.addProperty(columnNames.get(j), currentRow.getCell(j).getNumericCellValue());
                        } else if (currentRow.getCell(j).getCellTypeEnum() == CellType.BOOLEAN) {
                            jsonObject.addProperty(columnNames.get(j), currentRow.getCell(j).getBooleanCellValue());
                        } else if (currentRow.getCell(j).getCellTypeEnum() == CellType.BLANK) {
                            jsonObject.addProperty(columnNames.get(j), "");
                        }
                    } else {
                        jsonObject.addProperty(columnNames.get(j), "");
                    }

                }

                sheetArray.add(jsonObject);

            } else {
                // store column names
                for (int k = 0; k < currentRow.getPhysicalNumberOfCells(); k++) {
                    columnNames.add(currentRow.getCell(k).getStringCellValue());
                }
            }

        }

        sheetsJsonObject.add(workbook.getSheetName(i), sheetArray);

    }

    return sheetsJsonObject;

}

答案 1 :(得分:1)

如果要查找简单的在线转换工具,请使用以下命令: http://www.convertcsv.com/csv-to-json.htm

或者以编程方式执行此操作: https://github.com/nullpunkt/excel-to-json/blob/master/src/main/java/net/nullpunkt/exceljson/convert/ExcelToJsonConverter.java

答案 2 :(得分:0)

package com.core.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONcellValuesect;
import org.json.simple.JSONArray;

import com.PojoClassName;

public class ReadExcelUtil {
//create pojo class based on excel sheet columns 

    public static List<PojoClassName> readAssetExcel(
            final InputStream inputStream) {
        List<PojoClassName> cellValues = new ArrayList<PojoClassName>();

        XSSFWorkbook workbook;
        try {

            workbook = new XSSFWorkbook(inputStream);
            XSSFSheet sheet = workbook.getSheetAt(0);
            cellValues = damcellValues(sheet, cellValues);
            return cellValues;

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return cellValues;

    }

    private static List<PojoClassName> damcellValues(XSSFSheet sheet,
            List<PojoClassName> cellValues) {

        int num = sheet.getPhysicalNumberOfRows();

        for (int i = 1; i <= num; i++) {

            Row column = sheet.getRow(i);

            if (column.getCell(0) == null) {
                break;
            }

            PojoClassName object = new PojoClassName();

            String str1 = column.getCell(0).getStringCellValue();
            object.setDamPath(str1);

            String str2 = column.getCell(1).getStringCellValue();
            object.setServerUrl(str2);

            String str3 = column.getCell(2).getStringCellValue();
            object.setAssetTitle(str3);

            String str4 = column.getCell(3).getStringCellValue();
            object.setAssetDescription(str4);

            String str5 = column.getCell(4).getStringCellValue();
            object.setSourceId(str5);

            cellValues.add(object);
        }

        return cellValues;

    }

    //you can use below method to convert the List into Json

    public static String getJsonFromMyFormObject(List<DamAssetDetails> obj) throws JSONException{

        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < obj.size(); i++)`enter code here`
        {
          JSONObject formDetailsJson = new JSONObject();
          formDetailsJson.put("key1", obj.get(i).getDamPath());
          formDetailsJson.put("key2", obj.get(i).getServerUrl());
          formDetailsJson.put("key3", obj.get(i).getAssetTitle());
          formDetailsJson.put("key4", obj.get(i).getAssetDescription());
          formDetailsJson.put("key5", obj.get(i).getSourceId());
          jsonArray.add(formDetailsJson);
        }
        //responseDetailsJson.put("obj", jsonArray);
        return jsonArray.toJSONString();
      }

}

答案 3 :(得分:0)

public static String ExcelReader(String filePath, int index) throws IOException {
    List<String> list = new ArrayList<String>();

    try {

        FileInputStream excelFile = new FileInputStream(filePath);
        Workbook workbook = new XSSFWorkbook(excelFile);
        Sheet datatypeSheet = workbook.getSheetAt(index);
        XSSFRow row = (XSSFRow) datatypeSheet.getRow(0);
        String TC_ID = String.valueOf(row.getCell(0));
        String TS_ID = String.valueOf(row.getCell(1));
        String Test_Steps = String.valueOf(row.getCell(2));
        String Execution_Flag = String.valueOf(row.getCell(3));
        String IdentifierType = String.valueOf(row.getCell(4));
        String IdentifierValue = String.valueOf(row.getCell(5));
        String Action_Keyword = String.valueOf(row.getCell(6));
        String Dataset = String.valueOf(row.getCell(7));


        for (int rowNumber = 1; rowNumber <= datatypeSheet.getLastRowNum(); rowNumber++) {

            list.add(jsonObject.toString());
            XSSFRow row1 = (XSSFRow) datatypeSheet.getRow(rowNumber);

            for (int columnNumber = 0; columnNumber < row.getLastCellNum(); columnNumber++) {
                String cell = String.valueOf(row1.getCell(columnNumber));
                if (cell != null) {
                    switch (columnNumber) {
                        case 0:
                            jsonObject.addProperty(*** cell);
                            break;

                        case 1:
                            jsonObject.addProperty(**, cell);
                            break;

                        case 2:
                            jsonObject.addProperty(**, cell);
                            break;






                }
            }
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
          json = gson.toJson(jsonObject);
          System.out.print(json);




        }


    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return jsonObject.toString();
}

}

答案 4 :(得分:-1)

请参考以下代码,将Excel转换为Json- 还处理了多张工作表,并逐行读取excel工作表值(第一行被视为键,其余行是json格式的值)示例输入和输出在此处inputFile-Sheet1附加 inputFile-Sheet2 output jsonobject

公共类ExcelToJsonConvertor {

    private JSONObject readExcelFileAsJsonObject_RowWise(String filePath) {
        DataFormatter dataFormatter = new DataFormatter();
        JSONObject workbookJson = new JSONObject();
        JSONArray sheetJson = new JSONArray();
        JSONObject rowJson = new JSONObject();
        try {

            FileInputStream excelFile = new FileInputStream(new File(filePath));
            Workbook workbook = new XSSFWorkbook(excelFile);
            FormulaEvaluator formulaEvaluator = new XSSFFormulaEvaluator((XSSFWorkbook) workbook);

            for (Sheet sheet : workbook) {
                sheetJson = new JSONArray();
                int lastRowNum = sheet.getLastRowNum();
                int lastColumnNum = sheet.getRow(0).getLastCellNum();
                Row firstRowAsKeys = sheet.getRow(0); // first row as a json keys

                for (int i = 1; i <= lastRowNum; i++) {
                    rowJson = new JSONObject();
                    Row row = sheet.getRow(i);

                    if (row != null) {
                        for (int j = 0; j < lastColumnNum; j++) {
                            formulaEvaluator.evaluate(row.getCell(j));
                            rowJson.put(firstRowAsKeys.getCell(j).getStringCellValue(),
                                    dataFormatter.formatCellValue(row.getCell(j), formulaEvaluator));
                        }
                        sheetJson.add(rowJson);
                    }
                }
                workbookJson.put(sheet.getSheetName(), sheetJson);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return workbookJson;
    }

    public static void main(String arg[]) {
        ExcelToJsonConvertor excelConvertor = new ExcelToJsonConvertor();
        String filePath = "C:\\Users\\username\\Documents\\WorkInputFiles\\InputSheet.xlsx";
        JSONObject data = excelConvertor.readExcelFileAsJsonObject_RowWise(filePath);
        System.out.println(data);
    }

}

需要Maven依赖项- json-simple,apache.poi,poi-ooxml