一個小需求

一個小需求

@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 朝明 閱讀(...) 評論(...) 編輯 收藏
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章