【问题标题】:How to convert an excel/CSV table to JSON object in JAVA?如何在 JAVA 中将 excel/CSV 表转换为 JSON 对象?
【发布时间】:2021-05-05 09:22:08
【问题描述】:

我想将 Excel 表(或 CSV 表)转换为键值对形式的 JSON 对象。由于文件非常大,我无法使用任何在线服务。

例如,我的表格如下所示:

name place animal
Himanshu India Cat
Kamal London Dog
John Turkey Lion

我希望我的回复与此类似:

{
  {"name":"Himanshu",
    "place":"India",
    "animal":"Cat"
  },
  {
    "name":"Kamal",
    "place":"London",
    "animal":"Dog"
  },
  {
    "name":"John",
    "place":"Turkey",
    "animal":"Lion"
  }
}

由于我必须将此作为响应发布,因此我尝试使用以下代码将其转换为数组列表:

public static List<String[]> get(String file) {

    String delimiter = ",";
    String line;
    List lines = new ArrayList<>();

    try (Scanner s = new Scanner(new File(file))) {
        while (s.hasNext()) {
            line = s.next();
            List values = Arrays.asList(line.split(delimiter));
            lines.add(values);
        }
        
    } catch (Exception e) {
        System.out.println(e);
    }
    return lines;

}

现在这样的代码的问题在于,它不仅不会将输出作为数组列表返回,而且它也不是很通用,无法处理任何现实生活中的异常。循环使用具有数十万条目的 excel 文件需要大量时间和资源。而且我们必须处理许多这样的文件。

我使用的语言是 JAVA(Springboot 作为框架)。如果您能建议一个高效的库来处理此类情况,那就太好了。欢迎对其他语言的库提出建议,但优先考虑使用 JAVA。

谢谢。

【问题讨论】:

  • 请添加您迄今为止尝试过的内容(以及缺少的逗号)!
  • @KlausD。我已经更新了它。看看吧。
  • @HimanshuSuthar 发布了答案看看。

标签: java json excel csv


【解决方案1】:

使用Apache POI将excel数据转换为Java Objects(可以使用类来保存数据)然后使用JSONObject将其转换为JSON

public static void main(String[] args) throws IOException, JSONException {
    //Out put JSONArray
    JSONArray data = new JSONArray();

    //Read the File 
    FileInputStream fileInputStream = new FileInputStream("D:\\test.xls");

    //Load the file into workbook using Apache POI 
    Workbook workbook = new XSSFWorkbook(fileInputStream);
    Sheet sheet = workbook.getSheetAt(0);
    Iterator<Row> rows = sheet.iterator();
    int index = 0;
    while(rows.hasNext()) {
        Row row = rows.next();
        if(index!=0) {
            //Add to JSON Array
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("Name", row.getCell(0).getStringCellValue());
            jsonObject.put("Place", row.getCell(1).getStringCellValue());
            jsonObject.put("Animal", row.getCell(2).getStringCellValue());
            data.put(jsonObject);
        }
        index++;
    }

    //print JsonArray
    System.out.println(data.toString());
}

输出

[
   {
      "Animal":"Cat",
      "Place":"India",
      "Name":"Himanshu"
   },
   {
      "Animal":"Dog",
      "Place":"London",
      "Name":"Kamal"
   },
   {
      "Animal":"Lion",
      "Place":"Turkey",
      "Name":"John"
   }
]

【讨论】:

    猜你喜欢
    • 2013-03-12
    • 1970-01-01
    • 2019-06-09
    • 2020-07-23
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多