【问题标题】:Converting excel to JSON in JAVA using poi and jackson使用 poi 和 jackson 在 JAVA 中将 excel 转换为 JSON
【发布时间】:2016-03-03 18:53:39
【问题描述】:

我正在尝试将 excel 转换为 Json,它应该保存在某个本地目录中。我能够保存 Json 文件,但所有都得到 Null 值。它正在逐行读取 Excel,它本身正在将其更改为 JSON 格式并再次保存,它将转到下一行并用当前行数据替换以前的 Json 文件。它在 while 循环中,因此它正在迭代和替换文件。如果我将转换器代码从 while 中移出,则只有一个行数据会到达具有列名(json 数据)的空值,而不是 34 行数据(完整数据)。

这里是代码。请建议我如何实现要转换的整个excel数据并将文件保存在本地目录中。

public static void uploadXLS(MultipartFile file, Document doc)
        throws IOException {

    Products products = new Products();

    List<Products> productsList = new ArrayList<Products>();

    logger.info("uploadExcel method");
    HSSFWorkbook wb = null;
    try {

         wb= new HSSFWorkbook(file.getInputStream());
            System.out.println("workbook: "+wb);
            HSSFSheet sheet = wb.getSheetAt(0);
            System.out.println("worksheet: "+sheet);
            HSSFRow row;

            Iterator<Row> iterator = sheet.iterator();

            while (iterator.hasNext()) {
            products = new Products();
                Row nextRow = iterator.next();
                Iterator<Cell> cellIterator = nextRow.cellIterator();


                    Cell cell = cellIterator.next();

                    Iterator cells = nextRow.cellIterator();

                        cell=(HSSFCell) cells.next();

                        if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING)
                        {
                            System.out.print(cell.getStringCellValue()+" ");
                        }
                        else if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
                        {
                            System.out.print(cell.getNumericCellValue()+" ");
                        }
                        else if(HSSFDateUtil.isCellDateFormatted(cell)){
                            Date date = HSSFDateUtil.getJavaDate(cell.getNumericCellValue());
                        } else
                        {
                            //U Can Handel Boolean, Formula, Errors
                        }

                        products.setId(new DataFormatter().formatCellValue(nextRow.getCell(0)));
                        products.setProductId(new DataFormatter().formatCellValue(nextRow.getCell(1)));
                        products.setPopularity((new DataFormatter().formatCellValue(nextRow.getCell(12))));
                        products.setRelevance((new DataFormatter().formatCellValue(nextRow.getCell(13))));
                        products.setShortlisted((new DataFormatter().formatCellValue(nextRow.getCell(14))));
                        products.setLikes((new DataFormatter().formatCellValue(nextRow.getCell(15))));
                        products.setCreateDt((new DataFormatter().formatCellValue(nextRow.getCell(16))));
                        products.setPageId((new DataFormatter().formatCellValue(nextRow.getCell(17))));
                        products.setStyleName(nextRow.getCell(18).getStringCellValue());
                        products.setStyleId(nextRow.getCell(19).getStringCellValue());
                        products.setPriceRange(nextRow.getCell(20).getStringCellValue());
                        products.setPriceId(nextRow.getCell(21).getStringCellValue());
//                          products.setDefaultPrice(nextRow.getCell(22).getStringCellValue());
                             products.setDefaultMaterial(nextRow.getCell(23).getStringCellValue());
                        products.setDefaultFinish((new DataFormatter().formatCellValue(nextRow.getCell(24))));


                    productsList.add(products);
                    System.out.println(productsList.add(products));



           // JSON CONVERTER
    ObjectMapper mapper = new ObjectMapper();

    System.out.println("productsList: "+products);
    DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
      Date date = new Date();
      String location = dateFormat.format(date);
      System.out.println("productsList final: "+products);



        // Convert object to JSON string
        String jsonInString = mapper.writeValueAsString(products);
        System.out.println("JsonInString " +jsonInString);

        // Convert object to JSON string and pretty print
        jsonInString = mapper.writerWithDefaultPrettyPrinter()
                .writeValueAsString(products);

       mapper.writeValue(new File("D:\\"+location+"products.json"), productsList);

            }
            } catch (JsonGenerationException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    finally {


    }
}

我附上屏幕截图,在这里你可以看到,excel 中有 34 行。它做得很好并显示了值,但最后一个 Json 生成的文件有空值。所有 34 行数据都具有空值 :(

非常感谢提前:)。希望任何人都可以让我摆脱这个问题。

【问题讨论】:

    标签: java json jackson apache-poi


    【解决方案1】:

    首先你必须每次重新实例化 Product 对象,否则列表中只有一个对象。

           .....
            Iterator<Row> iterator = sheet.iterator();
            while (iterator.hasNext()) {
                products = new Products(); // re-instantiation.
                Row nextRow = iterator.next();
                Iterator<Cell> cellIterator = nextRow.cellIterator();
           .....
    

    Products 包含单个产品信息。如果可能,请将其重命名为 Product。

    【讨论】:

    • 嗨,Gurpeet,谢谢。我已经按照你的建议做了。但仍然有相同的输出:(。我正在更新问题中的变化
    • 我添加了有问题的控制台屏幕截图
    • 好的,看看你的代码。这可能会添加 2 个对象.. productsList.add(products); System.out.println(productsList.add(products));删除此 sysout 行。此外,您没有使用 jsonInString,最后您只是将 productList 值添加到文件中。你能在最后一次得到一个产品列表的系统输出吗?或者调试和检查!!!
    • 我们必须确保最后一次 productList 包含所有具有精细值的对象,或者它们具有 null !!!验证这个..
    • 好的,那我应该保留 System.out.println("productsList: "+products);或 System.out.println("productsList: "+productsList); .最后一次的意思是,我没有得到你。 ek ek loop hote waqt uske values relpace hote ja rahe hai。帕塔纳希昆。 Aap ek bar teamviewer me dekh liye to apku pata chalega.. 如果您不开采 Gurpeet,Teamviewer 将是不错的选择。请
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    • 2012-08-21
    • 2017-12-18
    • 1970-01-01
    • 2015-03-20
    • 2018-07-19
    • 2014-08-21
    相关资源
    最近更新 更多