excel转化为Json

时间:2023-03-09 16:01:34
excel转化为Json

Sheet sheet;
        Workbook book;
        Cell cell1,cell2,cell3,cell4;
        JSONArray jsonArray = new JSONArray();
        try {
            InputStream ins = new FileInputStream("C:/Users/Administrator/Downloads/123.xls");
            //读取Excel的文件
            WorkbookSettings setEncode = new WorkbookSettings();
            setEncode.setEncoding("UTF-8");
            book = Workbook.getWorkbook(ins, setEncode);
            //获取表中的对象(ecxel中sheet的编号从0开始,0,1,2,3,....)
            Sheet[] sheets = book.getSheets();
            // 获得表数
            int pages = sheets.length;
            for(int j=0;j<pages;j++){
                sheet = book.getSheet(j);
                int cols = sheet.getColumns();//列
                int rows = sheet.getRows(); // 行
                
                for(int i =0;i<rows;i++){
                    /*for(int k=0;k<cols;k++){*/
                        //获取每一行的单元格的数据
                        cell1 = sheet.getCell(0, i);//列 行                    
                        cell2 = sheet.getCell(1, i);
                        cell3 = sheet.getCell(2, i);
                        cell4 = sheet.getCell(3, i);
                        
                        if("".equals(cell1.getContents())){
                            break;
                        }
                        JSONObject object = new JSONObject();
                        object.put("ID", cell1.getContents());
                        object.put("红包ID", cell2.getContents());
                        object.put("红包金额", cell3.getContents());
                        object.put("用户名称", cell4.getContents());                        
                        jsonArray.add(object);
                    }                
                    
                                    
                    
                /*}*/
            }
            
            
            System.out.println(jsonArray.toString());
            ins.close();
            
        } catch (Exception e) {
            e.printStackTrace();
        }