자바 필요 에 따라 엑셀 내 보 내기 및 자동 계약 셀

자바 엑셀 내 보 내기 및 셀 자동 병합
최근 회사 의 한 가지 수요 가 있 는데 그것 이 바로 모델 에 따라 데이터 보고 서 를 내 보 내 고 내용 이 같은 단원 격 으로 자동 합병 을 실현 하 는 것 이다. 구체 적 인 업무 설계 도 는 다음 과 같다.
수요 분석
  • 머리 가 고정 되 어 있 기 때문에 먼저 엑셀 을 사용 하여 데이터 모델 을 만 듭 니 다
  • 단원 격 합병, 앞의 3 열 은 내용 에 따라 단원 격
  • 을 자동 으로 합병 해 야 한다.
  • 상태 에 따라 상태 가 이상 한 빨간색 글씨 체 를 판단 하고 빨간색 × 표지
  • * 상황 은 모두 하 나 를 더 선택 한 것 입 니 다. 데이터 베 이 스 는 한 가지 상태 만 기록 할 수 있 습 니 다. 배경 은 판단 하고 지정 한 셀 에 식별 자
  • 를 추가 해 야 합 니 다.
    코드 개발
  • 생 성 * 상황 에 대응 하 는 마법 치 대비 색인
  • /**
     * @ClassName PatrolExportEnum
     * @Description            
     * @Author xiongchao
     * @Date 2020/10/20 10:02
     **/
    public class  PatrolExportEnum {
    
        //     
        private static Map waterInCondition;
        //     
        private static Map waterOutCondition;
        //     
        private static Map electryCondition;
        //        
        private static Map liveCondition;
        //     
        private static Map pipeCondition;
        //     
        private static Map waterCondition;
    
        static {
    
            waterInCondition = new HashMap<>();
            waterOutCondition = new HashMap<>();
            electryCondition = new HashMap<>();
            liveCondition = new HashMap<>();
            pipeCondition = new HashMap<>();
            waterCondition = new HashMap<>();
    
            waterInCondition.put(" ",0);
            waterInCondition.put(" ",1);
            waterInCondition.put("  ",2);
            waterInCondition.put("   ",3);
    
            waterOutCondition.put("  ",0);
            waterOutCondition.put("  ",1);
    
            electryCondition.put("  ",0);
            electryCondition.put("  ",1);
    
            liveCondition.put("  ",0);
            liveCondition.put("   ",1);
    
            pipeCondition.put("  ",0);
            pipeCondition.put("  ",1);
            pipeCondition.put("   ",2);
    
            waterCondition.put("  ",0);
            waterCondition.put("  ",1);
        }
    
        public static Integer getWaterInCondition(String waterIn) {
            return waterInCondition.get(waterIn);
        }
    
        public static Integer getWaterOutCondition(String waiterOut) {
            return waterOutCondition.get(waiterOut);
        }
    
        public static Integer getElectryCondition(String electry) {
            return electryCondition.get(electry);
        }
    
        public static Integer getLiveCondition(String live) {
            return liveCondition.get(live);
        }
    
        public static Integer getPipeCondition(String pipe) {
            return pipeCondition.get(pipe);
        }
    
        public static Integer getWaterCondition(String water) {
            return waterCondition.get(water);
        }
    
    }
    
    
  • 데이터 실체 클래스 내 보 내기
  • public class PatrolTaskExport {
    
        private String street;
    
        private String xVillage;
    
        private String zVlillage;
    
        private String  patrolTime;
    
        private String patrolPerson;
    
        private String content;
    
        private String waterInCondition;
    
        private String waterOutCondition;
    
        private String electryCondition;
    
       private List equConditionList;
    
        private String isSame;
    
        private List pipeCondition;
    
        private String waterSupport;
    
        private String afforestCondition;
    
        public String getStreet() {
            return street;
        }
    
        public void setStreet(String street) {
            this.street = street;
        }
    
        public String getxVillage() {
            return xVillage;
        }
    
        public void setxVillage(String xVillage) {
            this.xVillage = xVillage;
        }
    
        public String getzVlillage() {
            return zVlillage;
        }
    
        public void setzVlillage(String zVlillage) {
            this.zVlillage = zVlillage;
        }
    
        public String getPatrolTime() {
            return patrolTime;
        }
    
        public void setPatrolTime(String patrolTime) {
            this.patrolTime = patrolTime;
        }
    
        public String getPatrolPerson() {
            return patrolPerson;
        }
    
        public void setPatrolPerson(String patrolPerson) {
            this.patrolPerson = patrolPerson;
        }
    
        public String getContent() {
            return content;
        }
    
        public void setContent(String content) {
            this.content = content;
        }
    
        public String getWaterInCondition() {
            return waterInCondition;
        }
    
        public void setWaterInCondition(String waterInCondition) {
            this.waterInCondition = waterInCondition;
        }
    
        public String getWaterOutCondition() {
            return waterOutCondition;
        }
    
        public void setWaterOutCondition(String waterOutCondition) {
            this.waterOutCondition = waterOutCondition;
        }
    
        public String getElectryCondition() {
            return electryCondition;
        }
    
        public void setElectryCondition(String electryCondition) {
            this.electryCondition = electryCondition;
        }
    
        public String getIsSame() {
            return isSame;
        }
    
        public void setIsSame(String isSame) {
            this.isSame = isSame;
        }
    
        public List getPipeCondition() {
            return pipeCondition;
        }
    
        public void setPipeCondition(List pipeCondition) {
            this.pipeCondition = pipeCondition;
        }
    
        public String getWaterSupport() {
            return waterSupport;
        }
    
        public void setWaterSupport(String waterSupport) {
            this.waterSupport = waterSupport;
        }
    
        public String getAfforestCondition() {
            return afforestCondition;
        }
    
        public void setAfforestCondition(String afforestCondition) {
            this.afforestCondition = afforestCondition;
        }
    
        public static class equCondition {
    
            public equCondition (String name,String value){
                this.name = name;
                this.value = value;
            }
    
            private String name;
    
            private String value;
    
            public String getName() {
                return name;
            }
    
            public void setName(String name) {
                this.name = name;
            }
    
            public String getValue() {
                return value;
            }
    
            public void setValue(String value) {
                this.value = value;
            }
        }
    
        public List getEquConditionList() {
            return equConditionList;
        }
    
        public void setEquConditionList(List equConditionList) {
            this.equConditionList = equConditionList;
        }
    }
    
  • 대응 하 는 서비스 유형
  • 
    /**
     * @ClassName ExcelExportService
     * @Description TODO
     * @Author xiongchao
     * @Date 2020/10/20 10:42
     **/
    public interface ExcelExportService {
    
        /**
         *     ,    
         * @param fileName
         * @param rootPath
         * @param list
         * @return
         */
        FileData exportFile(String fileName, String rootPath, List list);
    
    
        /**
         *       
         * @param param
         * @return
         */
        List getExportData(Map param);
    }
    
    
    
  • 인터페이스 실현 류
  • 
    @Service
    public class ExcelExportServiceImpl implements ExcelExportService {
    
        private static final String yes ="√";
        private static final String no ="×";
    
        private Logger log = LoggerFactory.getLogger(ExcelExportServiceImpl.class);
    
        private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        @Override
        public FileData exportFile(String fileName, String rootPath, List list) {
            if (CollectionUtils.isEmpty(list)) {
                log.error("        !");
                return null;
            }
            FileData fileData = null;
            Sheet sheet = null;
            Workbook workbook = null;
            Row row = null;
            try {
                workbook= ExcelUtil.readExcel(rootPath);
                CellStyle cellStyle =  workbook.createCellStyle();
                cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
                cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
                Font font = workbook.createFont();
                font.setColor(HSSFColor.RED.index);
    
                //      
                String month = getMonth();
                if(workbook != null) {
                    sheet = workbook.getSheetAt(0);
                }
                if(sheet != null){
                    //    
                    row= sheet.getRow(1);
                    row.getCell(0).setCellValue(month);
    
                    //          
                    int rowNum = 4;
                    int index = 1;
                    //     2,3,4           
                    //       
                    String perPurpose = "";
                    String perxVillage = "";
                    String perzVliiage= "";
                    //       
                    int startMergeCol = 4;
                    int xStartMergeCol = 4;
                    int zStartMergeCol = 4;
                    int xendMergeCol = 3;
                    int zendMergeCol = 3;
                    //       
                    int endMergeCol = 3;
                    //     
                    Integer selectIndex = null;
                    //            
                    boolean flag = true;
    
                    int cellNum = sheet.getRow(3).getLastCellNum();
                    //     
                    for(PatrolTaskExport vo :list){
                        row = sheet.createRow(rowNum);
                        for(int i=0;i4;
                    for(PatrolTaskExport vo :list){
                        row = sheet.getRow(rowNum);
                        //      
                        createCell(row,cellStyle,0,String.valueOf(index));
                        createCell(row,cellStyle,1,vo.getStreet());
                        if(flag){
                            perPurpose = vo.getStreet();
                            perzVliiage = vo.getzVlillage();
                            perxVillage =vo.getxVillage();
                            flag = false;
                        }
    
                        if(perzVliiage.equalsIgnoreCase(vo.getzVlillage())){
                            zendMergeCol ++;
                        } else {
                            if(zendMergeCol > zStartMergeCol){
                                sheet.addMergedRegion(new CellRangeAddress(zStartMergeCol,zendMergeCol,3,3));
                            }
                            zStartMergeCol = rowNum;
                            zendMergeCol = zStartMergeCol;
                            perzVliiage = vo.getzVlillage();
                        }
    
                        if(perxVillage.equalsIgnoreCase(vo.getxVillage())){
                            xendMergeCol ++;
                        } else {
                            if(xendMergeCol > xStartMergeCol){
                                sheet.addMergedRegion(new CellRangeAddress(xStartMergeCol,xendMergeCol,2,2));
                            }
                            xStartMergeCol = rowNum;
                            xendMergeCol = xStartMergeCol;
                            perxVillage = vo.getxVillage();
                        }
    
                        if(perPurpose.equals(vo.getStreet())){
                            endMergeCol ++;
                        } else {
                            //          
                            if(startMergeCol < endMergeCol){
                                sheet.addMergedRegion(new CellRangeAddress(startMergeCol,endMergeCol,1,1));
                            }
                            startMergeCol = rowNum;
                            endMergeCol = startMergeCol;
                            perPurpose = vo.getStreet();
                        }
                        createCell(row,cellStyle,2,vo.getxVillage());
                        createCell(row,cellStyle,3,vo.getzVlillage());
                        createCell(row,cellStyle,4,vo.getPatrolTime());
    
                        selectIndex = PatrolExportEnum.getWaterInCondition(vo.getWaterInCondition());
                        if(selectIndex != null) {
                            if(selectIndex.equals(3)){
                                CellStyle style = colorRed(workbook,font);
                                createCell(row,style,5 + selectIndex,no);
                            }else{
                                createCell(row,cellStyle,5 + selectIndex,yes);
                            }
                            selectIndex = null;
                        }
                        selectIndex = PatrolExportEnum.getWaterOutCondition(vo.getWaterOutCondition());
                        if(selectIndex != null){
                            if(selectIndex.equals(1)){
                                CellStyle style = colorRed(workbook,font);
                                createCell(row,style,9 + selectIndex,no);
                            }else {
                                createCell(row,cellStyle,9 + selectIndex,yes);
                            }
                            selectIndex  = null;
                        }
    
                        selectIndex = PatrolExportEnum.getElectryCondition(vo.getElectryCondition());
                        if(selectIndex != null) {
                            if(selectIndex.equals(1)){
                                CellStyle style = colorRed(workbook,font);
                                createCell(row,style,11 + selectIndex,no);
                            }else{
                                createCell(row,cellStyle,11 + selectIndex,yes);
                            }
                            selectIndex  = null;
                        }
                        List conditions = vo.getEquConditionList();
                        if(!CollectionUtils.isEmpty(conditions)){
                            for(PatrolTaskExport.equCondition e : conditions){
                                String value = e.getValue();
                                String name = e.getName();
                                if ("  ".equalsIgnoreCase(name)) {
                                    CellStyle style = setColor(value,workbook,font);
                                    createCell(row,style,13,value);
                                }
                                if ("  ".equalsIgnoreCase(name)) {
                                    CellStyle style = setColor(value,workbook,font);
                                    createCell(row,style,14 ,value);
                                }
                                if ("  ".equalsIgnoreCase(name)) {
                                    CellStyle style = setColor(value,workbook,font);
                                    createCell(row,style,15 ,value);
                                }
                                if ("   ".equalsIgnoreCase(name)) {
                                    CellStyle style = setColor(value,workbook,font);
                                    createCell(row,style,16 ,value);
                                }
                            }
                        }
                        selectIndex = PatrolExportEnum.getLiveCondition(vo.getIsSame());
                        if(selectIndex != null) {
                            if (selectIndex.equals(1)) {
                                CellStyle style = colorRed(workbook,font);
                                createCell(row,style,17 + selectIndex,no);
                            }else {
                                createCell(row,cellStyle,17 + selectIndex,yes);
                            }
                           selectIndex = null;
                        }
    
                        List pipeCodintion = vo.getPipeCondition();
                        if(!CollectionUtils.isEmpty(pipeCodintion)){
                            for(PatrolTaskExport.equCondition e : pipeCodintion){
                                String value = e.getValue();
                                String name = e.getName();
                                if ("  ".equalsIgnoreCase(name)) {
                                    CellStyle style = setColor(value,workbook,font);
                                    createCell(row,style,19,value);
                                }
                                if ("  ".equalsIgnoreCase(name)) {
                                    CellStyle style = setColor(value,workbook,font);
                                    createCell(row,style,20 ,value);
                                }
                                if ("   ".equalsIgnoreCase(name)) {
                                    CellStyle style = setColor(value,workbook,font);
                                    createCell(row,style,21 ,value);
                                }
                            }
                        }
    
    
                        selectIndex = PatrolExportEnum.getWaterCondition(vo.getWaterSupport());
                        if(selectIndex != null){
                            if (selectIndex.equals(1)) {
                                CellStyle style = colorRed(workbook,font);
                                createCell(row,style,22 + selectIndex,no);
                            }else {
                                createCell(row,cellStyle,22 + selectIndex,yes);
                            }
                            selectIndex = null;
                        }
    
                        createCell(row,cellStyle,24 ,vo.getAfforestCondition());
                        createCell(row,cellStyle,25 ,vo.getPatrolPerson());
                        createCell(row,cellStyle,26 ,vo.getContent());
                        rowNum++;
                        index ++;
    
                    }
                    if(startMergeCol < endMergeCol){
                        sheet.addMergedRegion(new CellRangeAddress(startMergeCol,endMergeCol,1,1));
                    }
                    if(xendMergeCol > xStartMergeCol){
                        sheet.addMergedRegion(new CellRangeAddress(xStartMergeCol,xendMergeCol,2,2));
                    }
                    if(zendMergeCol > zStartMergeCol){
                        sheet.addMergedRegion(new CellRangeAddress(zStartMergeCol,zendMergeCol,3,3));
                    }
                }
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                fileData  = new FileData();
                workbook.write(os);
                os.flush();
                fileData.setBytes(os.toByteArray());
                fileData.setFileName(fileName);
    
            } catch (IOException e) {
                log.error("partrol_report_export_error");
                e.printStackTrace();
            }
            return fileData;
        }
    
    
        @Override
        public List getExportData(Map param) {
    
            List list = new ArrayList<>();
            for (int i = 0; i < 100 ; i++) {
                PatrolTaskExport pa = new PatrolTaskExport();
                if(i == 6) {
                    pa.setStreet("    ");
                }else{
                    pa.setStreet("    ");
                }
    
                pa.setzVlillage("    "+i);
                pa.setPatrolTime("2020-12-" + i);
                if(i%2 == 0){
                    pa.setWaterInCondition("  ");
                    pa.setWaterOutCondition("  ");
                    pa.setIsSame("  ");
                    pa.setPatrolPerson("  " + i);
                    pa.setxVillage("     ");
                }else{
                    pa.setWaterInCondition(" ");
                    pa.setWaterOutCondition("  ");
                    pa.setIsSame("   ");
                    pa.setPatrolPerson("  " + i);
                    pa.setxVillage("      ");
                }
                pa.setElectryCondition("  ");
                List conditions = new ArrayList<>();
                conditions.add(new PatrolTaskExport.equCondition("  ","  "));
                conditions.add(new PatrolTaskExport.equCondition("  ","  "));
                conditions.add(new PatrolTaskExport.equCondition("  ","  "));
                conditions.add(new PatrolTaskExport.equCondition("   ","  "));
                pa.setEquConditionList(conditions);
    
                List pipeconditions = new ArrayList<>();
                pipeconditions.add(new PatrolTaskExport.equCondition("  ","  "));
                pipeconditions.add(new PatrolTaskExport.equCondition("  ","  "));
                pipeconditions.add(new PatrolTaskExport.equCondition("   ","  "));
    
                pa.setPipeCondition(pipeconditions);
                pa.setWaterSupport("  ");
                pa.setAfforestCondition("   ");
                pa.setContent("      ");
                list.add(pa);
            }
            return list;
        }
    
        private  String getMonth(){
            Calendar date = Calendar.getInstance();
            String year = String.valueOf(date.get(Calendar.YEAR));
            String month = String.valueOf(date.get(Calendar.MONTH) + 1);
            return year + " " + month + " ";
        }
    
        private void createCell(Row row,CellStyle cellStyle ,int rowNum,String value){
            Cell cell = row.getCell(rowNum);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(value);
        }
    
        private CellStyle setColor(String  value ,Workbook workbook,Font font){
            CellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            if(value.equalsIgnoreCase("  ")){
                cellStyle.setFont(font);
                return cellStyle;
            }
            return  cellStyle;
        }
    
        private CellStyle colorRed(Workbook workbook,Font font){
            CellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            cellStyle.setFont(font);
            return cellStyle;
        }
    }
    
    
  • 인터페이스 노출 및 테스트 controller
  • @Api(tags = "        ")
    @RequestMapping("/api")
    @RestController
    public class PatrolTaskResource {
    
        @Autowired
        private ExcelExportService exportService;
    
        @ApiOperation(value = "        ")
        @GetMapping("/partorl-task/export")
        public void patrolReportExport(
            @ApiParam(value = "    ") @RequestParam(value = "param",required = false) String param,
            HttpServletRequest request, HttpServletResponse response
        ){
            long start =System.currentTimeMillis();
            Map map = new HashMap<>();
            if(StringUtils.isNotEmpty(param)){
                map.put("param",param);
            }
            List list = exportService.getExportData(map);
            String rootPath = ImportTypeEnum.REPORT.getFilePath();
            String fileName = ImportTypeEnum.REPORT.getFileName();
    
    
            FileData file = exportService.exportFile(fileName,rootPath,list);
            try {
                ExcelUtil.setResponse(request, response,file);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    최종 전시 결과

    좋은 웹페이지 즐겨찾기