一个小需求

@Slf4j
public class ExcelUtil {
    public static void main(String[] args) {
        ArrayList<Map<String,String>> list = readCsv("D:\\kedacom\\项目\\昆明\\f_kunming_area.xls");
        log.info("list======{}",list.size());
    }

    // 读取csv文件的内容
    public static ArrayList<Map<String,String>> readCsv(String filepath) {
        int ignoreRows = 1;
        File file = new File(filepath); // CSV文件路径
        file.setReadable(true);//设置可读
        file.setWritable(true);//设置可写
        Map<Integer, String> headerMapper = new HashedMap() {{
            put(0, "id");
            put(1, "code");
            put(2, "name");
            put(3, "parent_code");
        }};
        ArrayList<Map<String,String>> arrayList = new ArrayList<>();
        BufferedReader br = null;
        try {
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(

                    file));
            // 打开HSSFWorkbook

            POIFSFileSystem fs = new POIFSFileSystem(in);

            HSSFWorkbook wb = new HSSFWorkbook(fs);
            HSSFCell cell = null;
            int rowSize = 0;
            for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {

                HSSFSheet st = wb.getSheetAt(sheetIndex);

                // 第一行为标题,不取

                for (int rowIndex = ignoreRows; rowIndex <= st.getLastRowNum(); rowIndex++) {
                    TreeMap<String, String> treeMap = new TreeMap();
                    HSSFRow row = st.getRow(rowIndex);

                    if (row == null) {

                        continue;

                    }

                    for (int columnIndex = 0; columnIndex < row.getLastCellNum(); columnIndex++) {

                        cell = row.getCell(columnIndex);
                        String value="";
                        if (cell != null) {
                            switch (cell.getCellType()) {

                                case HSSFCell.CELL_TYPE_STRING:

                                    value = cell.getStringCellValue();

                                    break;

                                case HSSFCell.CELL_TYPE_NUMERIC:

                                    if (HSSFDateUtil.isCellDateFormatted(cell)) {

                                        Date date = cell.getDateCellValue();

                                        if (date != null) {

                                            value = new SimpleDateFormat("yyyy-MM-dd").format(date);

                                        } else {

                                            value = "";

                                        }

                                    } else {

                                        value = new DecimalFormat("0").format(cell.getNumericCellValue());

                                    }

                                    break;

                                case HSSFCell.CELL_TYPE_FORMULA:

                                    // 导入时如果为公式生成的数据则无值

                                    if (!cell.getStringCellValue().equals("")) {

                                        value = cell.getStringCellValue();

                                    } else {

                                        value = cell.getNumericCellValue() + "";

                                    }

                                    break;

                                case HSSFCell.CELL_TYPE_BLANK:

                                    break;

                                case HSSFCell.CELL_TYPE_ERROR:

                                    value = "";

                                    break;

                                case HSSFCell.CELL_TYPE_BOOLEAN:

                                    value = (cell.getBooleanCellValue() == true ? "Y" : "N");

                                    break;

                                default:

                                    value = "";

                            }
                            treeMap.put(headerMapper.get(columnIndex),value);
                         //   log.info("headerMapper======{},value======{}", headerMapper.get(columnIndex),value);


                        }

                    }
                    arrayList.add(treeMap);
                }

            }

            in.close();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return arrayList;

    }
}

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = OAuth2ServerApplication.class)
@Transactional
@Rollback(false)
//@ActiveProfiles("offline")
public class AreaServiceImplTest {
    @Autowired
    private AreaService areaService;
    @Before
    public void setUp() throws Exception {
        log.info("====={}","up");
    }
    @After
    public void tearDown() throws Exception {
        log.info("====={}","Down");
    }
        @Test
    public void testInsertArea() throws Exception {
            ArrayList<Map<String,String>> list = readCsv("D:\\kedacom\\项目\\昆明\\f_kunming_area.xls");
            log.info("list======{}",list.size());
         List<Area> list1=   buildTree(list,"code","parent_code","100000");
            list1.forEach(area -> {
                updateARea(area);
            });
            log.info("====={}", list1.size());
    }

    private void updateARea(Area area) {
        Area oldArea = areaService.selectByCode(area.getCode());
        if (oldArea == null) {
            //log.info("area>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>{}", JSON.toJSONString(areaService));
            areaService.insert(area);
        }
        if (CollectionUtil.isNotEmpty(area.getChildren())) {
            List<Area> list = area.getChildren();
            list.forEach(dept -> {
                updateARea(dept);
            });
        }
    }
    /**
     * 生成部门树
     *
     * @param list
     * @param idProperty
     * @param parentIdProperty
     * @param parentValue
     * @return
     */
    private List<Area> buildTree(List<Map<String,String>> list, String idProperty, String parentIdProperty, String parentValue) {
        List<Area> lists = Lists.newArrayList();
        list.forEach(obj -> {
            try {
                String parentId;

                parentId = BeanUtils.getProperty(obj, parentIdProperty);

                if (parentId == parentValue || (parentId != null && parentId.equals(parentValue))) {
                    Area area=new SimpleArea();
                    Area oldArea = areaService.selectByCode(obj.get("code").toString());
                    if (oldArea != null) {
                        area.setId(oldArea.getId());
                    } else {
                        String id = BeanUtils.getProperty(obj, idProperty);
                        area.setId(id);
                    }
                    area.setName(obj.get("name"));
                    if (StringUtils.isNotBlank(obj.get("parent_code"))) {
                        Area parentArea = areaService.selectByCode(obj.get("parent_code").toString());
                        if(parentArea!=null){
                            area.setParentId(parentArea.getId());
                        }else{
                            area.setParentId("100000");
                            area.setCityCode(obj.get("parent_code").toString());
                        }

                    }
                    area.setCode(obj.get("code").toString());
                    area.setStatus(1);
                    List<Area> subarray = buildTree(list, idProperty, parentIdProperty, area.getCode());
                    if (subarray.size() > 0)
                        area.setChildren(subarray);
                    lists.add(area);
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        });
        return lists;
    }

}

posted @ 2019-06-04 10:24  朝明  阅读(195)  评论(0编辑  收藏  举报