ExcelToJson转换器

public JsonNode excelToJson(File excel) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
            // hold the excel data sheet wise
            ObjectNode excelData = mapper.createObjectNode();
            FileInputStream fis = null;
            Workbook workbook = null;
            try {
                // Creating file input stream
                fis = new FileInputStream(excel);

                String filename = excel.getName().toLowerCase();
                if (filename.endsWith(".xls") || filename.endsWith(".xlsx")) {
                    // creating workbook object based on excel file format
                    if (filename.endsWith(".xls")) {
                        workbook = new HSSFWorkbook(fis);
                    } else {
                        workbook = new XSSFWorkbook(fis);
                    }

                    // Reading each sheet one by one
                    for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                        Sheet sheet = workbook.getSheetAt(i);
                        String sheetName = sheet.getSheetName();

                        List<String> headers = new ArrayList<String>();
                        ArrayNode sheetData = mapper.createArrayNode();
                        // Reading each row of the sheet
                        for (int j = 0; j <= sheet.getLastRowNum(); j++) {
                            Row row = sheet.getRow(j);
                            if (j == 0) {
                                // reading sheet header's name
                                for (int k = 0; k < row.getLastCellNum(); k++) {
                                    headers.add(row.getCell(k).getStringCellValue());
                                }
                            } else {
                                // reading work sheet data
                                ObjectNode rowData = mapper.createObjectNode();
                                for (int k = 0; k < headers.size(); k++) {
                                    Cell cell = row.getCell(k);
                                    String headerName = headers.get(k);
                                    if (cell != null) {
                                        switch (cell.getCellType()) {
                                            case FORMULA:
                                                rowData.put(headerName, cell.getCellFormula());
                                                break;
                                            case BOOLEAN:
                                                rowData.put(headerName, cell.getBooleanCellValue());
                                                break;
                                            case NUMERIC:
                                                rowData.put(headerName, cell.getNumericCellValue());
                                                break;
                                            case BLANK:
                                                rowData.put(headerName, "");
                                                break;
                                            default:
                                                rowData.put(headerName, cell.getStringCellValue());
                                                break;
                                        }
                                    } else {
                                        rowData.put(headerName, "");
                                    }
                                }
                                sheetData.add(rowData);
                            }
                        }
                        excelData.set(sheetName, sheetData);
                    }
                    return excelData;
                } else {
                    throw new IllegalArgumentException("File format not supported.");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (workbook != null) {
                    try {
                        workbook.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }
            return null;
    }

该方法工作正常,但在输出时会生成一个数组,然后需要将其写入数据库.此数组形成一个对象,数据无法写入数据库.

推荐答案

我认为您可以按照下面的代码片段将JSON数组转换为您需要的Java数组列表.

在导入中添加这些类,

import java.util.ArrayList;  
import org.json.JSONArray;  
import org.json.JSONObject; 

您可以使用下面的代码创建一个单独的方法,并在传递JSON数组以获取列表的位置调用它.在使用它时,请删除示例JSON数据和JSON对象创建部分,因为您已经拥有了JSONarray.将JSON数组作为参数传递,并开始将JSON数据添加到列表中.

public static void main(String[] args){  
        //Creating string of JSON data   
        String jsonData = "{\"languages\" : [{\"name\": \"Java\", \"description\":"  
                + " \" Java is a class-based high-level programming language that"  
                + " follows the OOPs concepts.\"},{\"name\": \"Javascript\","  
                + "\"description\": \"JavaScript is also a high-level, often "  
                + "just-in-time compiled, and multi-paradigm programming language."  
                + "\"},{\"name\": \"Python\",\"description\": \"Python is another "  
                + "high-level, interpreted and general-purpose programming language."  
                + "\"}]}";  
          
        //Converting jsonData string into JSON object  
        JSONObject jsnobject = new JSONObject(jsonData);  
        //Printing JSON object  
        System.out.println("JSON Object");  
        System.out.println(jsnobject);  
        //Getting languages JSON array from the JSON object  
        JSONArray jsonArray = jsnobject.getJSONArray("languages");  
        //Printing JSON array  
        System.out.println("JSON Array");  
        System.out.println(jsonArray);  
        //Creating an empty ArrayList of type Object  
        ArrayList<Object> listdata = new ArrayList<Object>();  
          
        //Checking whether the JSON array has some value or not  
        if (jsonArray != null) {   
              
            //Iterating JSON array  
            for (int i=0;i<jsonArray.length();i++){   
                  
                //Adding each element of JSON array into ArrayList  
                listdata.add(jsonArray.get(i));  
            }   
        }  
        //Iterating ArrayList to print each element  
  
        System.out.println("Each element of ArrayList");  
        for(int i=0; i<listdata.size(); i++) {  
            //Printing each element of ArrayList  
            System.out.println(listdata.get(i));  
        }  
    }  

输出:

JSON Object
{"languages":[{"name":"Java","description":"Java is a class-based high-level programming language that follows the OOPs concepts."},{"name":"Javascript","description":"JavaScript is also a high-level, often just-in-time compiled, and multi-paradigm programming language."},{"name":"Python","description":"Python is another high-level, interpreted and general-purpose programming language."}]}

JSON Array
[{"name":"Java","description":"Java is a class-based high-level programming language that follows the OOPs concepts."},{"name":"Javascript","description":"JavaScript is also a high-level, often just-in-time compiled, and multi-paradigm programming language."},{"name":"Python","description":"Python is another high-level, interpreted and general-purpose programming language."}]

Each element of ArrayList
{"name":"Java","description":"Java is a class-based high-level programming language that follows the OOPs concepts."}
{"name":"Javascript","description":"JavaScript is also a high-level, often just-in-time compiled, and multi-paradigm programming language."}
{"name":"Python","description":"Python is another high-level, interpreted and general-purpose programming language."}

如果您还有任何疑问,请参阅here

Java相关问答推荐

Spring安全实现多个SQL表身份验证

将Nimbus设置为计算机上运行的所有Java应用程序的默认外观

如何审查Java dtos中的自定义注释字段?

Javascript在边界中心调整ImageView大小

在AnyLogic中增加变量计数

Java 8中的多个字段和计数

如何创建一个2d自上而下的移动系统,其中移动,同时持有两个关键是可能的处理?

Kotlin内联互操作:强制装箱

无法使用Java&;TestContainers获取AWS SQS队列的属性

如何使用带有谓词参数的方法,而不使用lambda表达式

Mac上的全屏截图在使用JavaFX时不能正常工作吗?

JOOQ中的子查询使用的是默认方言,而不是配置的方言

Docker不支持弹性APM服务器

舰队运行配置Maven版本

try 在两个不同数组的数字之间求平均值

在Oracle db中,当我们提供字符串而不是数字时,比较是如何工作的?

记录是类的语法糖吗?

如何修复Spring Boot应用程序中的RestDocumentationGenerationException:java.io.FileNotFoundException:/curl-request.adoc(只读文件系统)?

如何从指定某些字段的父对象创建子对象

为什么Java编译器为没有参数的方法(getter方法)创建桥接方法