JAvaはexcelファイルを取得し、データを書き込む

15227 ワード

public void templateToExcel(ServletOutputStream output, HttpSession session) throws Exception {

        InputStream is=null;
        FileInputStream fis=null;
        Workbook wb=null;
        try {
            String classpath = this.getClass().getResource("/").getPath().replaceFirst("/", "");
            String filePath = classpath+"META-INF/resources/uploadFiles/          .xlsx";
            File excel = new File(filePath);
            if (excel.isFile() && excel.exists()) {   //        
                String[] split = excel.getName().split("\\.");  //.     ,    !!!!!
                //      (xls/xlsx)    
                if ( "xls".equals(split[1])){
                    fis = new FileInputStream(excel);   //     
                    wb = new HSSFWorkbook(fis);
                }else if ("xlsx".equals(split[1])){
                    is = new FileInputStream(excel);
                    XSSFWorkbook xssfWorkbook= new XSSFWorkbook(is);
                    wb = xssfWorkbook;
                }
                //      
                Sheet sheet = wb.getSheetAt(0);

                List<ControlClerk> list =controlClerkMapper.getClerkList2();
                if(list != null && list.size() > 0) {
                    Cell cell = null; //   
                    Row nRow = null; //    
                    for(int i = 0; i < list.size(); i++) {
                        nRow = sheet.createRow(i + 2);
//                        nRow.setRowStyle(style);
                        ControlClerk item = list.get(i);

                        int j = 1;

                        cell = nRow.createCell(j++);
                        cell.setCellValue(item.getUserId());

                        cell = nRow.createCell(j++);
                        cell.setCellValue(item.getUserName());
                    }
                }
            } else {
                _log.info("===========     !=============");
            }
        } catch (Exception e) {
            e.printStackTrace();
            _log.error("===========      !==========="+e.getMessage(),e);
        }finally{
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fis!=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        wb.write(output);
        output.close();
    }