2014-11-12 1 views
0
public class ExcelSheetController extends HttpServlet implements ServletContextListener 
    { 

     static File appHome; 
     static File customerDataFile; 

     @Override 
     public void init(ServletConfig config) throws ServletException{ 
      // TODO Auto-generated method stub 
    /* I getting the Apache tomcat folder of web-app and also adding the context path which is written in web.xml folder{ <context-param> 
    <param-name>MyAppHome</param-name> 
    <param-value>com/excelsave/</param-value> 
</context-param>} */ 

String filePath = "C:/apache-tomcat-7.0.5/webapps"+getServletContext().getRealPath("MyAppHome") + File.separator+"udaanmasterdatabase.xls"; 
      System.out.println(filePath+" GGGGGGGGGG");  
      appHome = new File(filePath); 
      File customerDataFile = new File(appHome, "udaanmasterdatabase.xls"); 
     } 

      protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
       throws ServletException, IOException { 
      // TODO Auto-generated method stub 

      HttpSession session = req.getSession(false);  
       if(session!=null) 
       { 
     try { 
         int rownum = 0; 
          //Create a blank sheet 
          HSSFWorkbook workbook = new HSSFWorkbook(); 
          HSSFSheet sheet = workbook.createSheet("Sample sheet"); 
          shadeAlt(sheet); 
          HSSFCellStyle my_style = workbook.createCellStyle(); 
         /* We will now specify a background cell color */ 
          my_style.setFillPattern(HSSFCellStyle.FINE_DOTS); 
          my_style.setFillForegroundColor(new HSSFColor.BLACK().getIndex()); 
          my_style.setFillBackgroundColor(new HSSFColor.SKY_BLUE().getIndex()); 
           Row row = sheet.createRow(1); 
          for(int i=0;i<10;i++) 
          { 
          Cell cell = row.createCell(i); 
          cell.setCellStyle(my_style); 
         switch (i) { 
          case 3: 
           cell.setCellValue("Drive Detail"); 
           break; 

          default: 
           cell.setCellValue(""); 
          } 
          } 
         /* row.createCell(10).setCellValue("Selection of Student Detail");*/ 
          HSSFCellStyle my_style1 = workbook.createCellStyle(); 
          my_style1.setFillPattern(HSSFCellStyle.FINE_DOTS); 
          my_style1.setFillForegroundColor(new HSSFColor.BLACK().getIndex()); 
          my_style1.setFillBackgroundColor(new HSSFColor.GREEN().getIndex()); 
          Cell cell1 = null; 
          /* cell1 = row.createCell(10); 
          cell1.setCellValue("Selection of Student Detail");*/ 

            for(int i=10;i<85;i++) 
            { 
             cell1 = row.createCell(i); 
            cell1.setCellStyle(my_style1); 

            switch (i) { 
            case 10: 
             cell1.setCellValue("Selection of Student Detail"); 
             break; 

            default: 
             cell1.setCellValue(""); 
             break; 
            } 
            } 

            HSSFCellStyle my_style2 = workbook.createCellStyle(); 
            my_style2.setFillPattern(HSSFCellStyle.FINE_DOTS); 
           my_style2.setFillForegroundColor(new HSSFColor.BLACK().getIndex()); 
           my_style2.setFillBackgroundColor(new HSSFColor.BLUE_GREY().getIndex()); 
           Row row1 = sheet.createRow(2); 

           for(int i=0;i<86;i++) 
           { 
            Cell cell2 = row1.createCell(i); 
             cell2.setCellStyle(my_style2); 
            switch (i) { 
            case 0: 
             cell2.setCellValue("Sno");  
             break; 

            case 2: 
             cell2.setCellValue("Drive Location"); 
             break; 
            case 4 : 
             cell2.setCellValue("Date of Interview"); 
             break; 

            case 6: 
             cell2.setCellValue("Selected By"); 
             break; 

            case 8: 
             cell2.setCellValue("Mode of Selection"); 
             break; 

            case 10: 
             cell2.setCellValue("Student Id"); 
             break; 

            case 12: 
             cell2.setCellValue("Student first Name"); 
             break; 

            case 14: 
             cell2.setCellValue("Student Last Name"); 
             break; 


            case 16: 
             cell2.setCellValue("Qualification"); 
            break; 

            case 18: 
             cell2.setCellValue("Course Applied"); 
             break; 

            case 20: 
             cell2.setCellValue("Joining Course"); 
             break; 

            case 22: 
             cell2.setCellValue("Ending Course"); 
             break; 

            case 25: 
             cell2.setCellValue("Place of Training"); 
             break; 


            case 30: 
             cell2.setCellValue("Bank Account Number"); 
             break; 


            case 34: 
             cell2.setCellValue("Travel Expense"); 
             break; 


            case 38: 
             cell2.setCellValue("Medical Insurance Number"); 
             break; 


            case 42: 
             cell2.setCellValue("Medical Insurance Transfer from"); 
             break; 

            case 46: 
             cell2.setCellValue("Medical Insurance from"); 
             break; 

            case 50: 
             cell2.setCellValue("Medical Insurance to"); 
             break; 

            case 54: 
             cell2.setCellValue("Reason Leaving of Institue"); 
             break; 

            case 58: 
             cell2.setCellValue("Placement Status"); 
             break; 

            case 62: 
             cell2.setCellValue("Appointment Letter Received"); 
             break; 

            case 66: 
             cell2.setCellValue("First Month Salary Status"); 
             break; 

            case 70: 
             cell2.setCellValue("Second Month Salary Status"); 
             break; 

            case 74: 
             cell2.setCellValue("Third Month Salary Status"); 
             break; 

            case 78: 
             cell2.setCellValue("Book Returns Leaving Institute"); 
             break; 



            default: 
             cell2.setCellValue(""); 
             break; 
            } 

           } 



           Row row2 = sheet.createRow(3); 
           row2.createCell(0).setCellValue(1); 

           row2.createCell(2).setCellValue(lgbean.getDrivelocation()); 


           row2.createCell(4).setCellValue(datinter); 


           row2.createCell(6).setCellValue(lgbean.getSelectprocedure()); 


           row2.createCell(8).setCellValue(lgbean.getModeselection()); 


           row2.createCell(10).setCellValue(lgbean.getStudid()); 

           row2.createCell(12).setCellValue(lgbean.getFirstname()); 


           row2.createCell(14).setCellValue(lgbean.getLastname()); 


           row2.createCell(16).setCellValue(lgbean.getQualification()); 


           row2.createCell(18).setCellValue(lgbean.getCourseoffered()); 


           row2.createCell(20).setCellValue(join_date); 


           row2.createCell(22).setCellValue(end_date); 


           row2.createCell(25).setCellValue(lgbean.getPlacetraining()); 


           row2.createCell(30).setCellValue(lgbean.getBankaccntno()); 


           row2.createCell(34).setCellValue(lgbean.getTravelexpense()); 


           row2.createCell(38).setCellValue(lgbean.getMedicalinsuranceno()); 


           row2.createCell(42).setCellValue(lgbean.getTransferto()); 


           row2.createCell(46).setCellValue(medicaldatfrom); 


           row2.createCell(50).setCellValue(medicaldatto); 



           row2.createCell(54).setCellValue(lgbean.getLeavinghostel()); 


           row2.createCell(58).setCellValue(lgbean.getPlacementstatus()); 


           row2.createCell(62).setCellValue(lgbean.getAppoint_letter()); 


           row2.createCell(66).setCellValue(lgbean.getSelectmonth1()); 


           row2.createCell(70).setCellValue(lgbean.getSelectmonth2()); 


           row2.createCell(74).setCellValue(lgbean.getSelectmonth3()); 


           row2.createCell(78).setCellValue(lgbean.getBook_returns()); 



        try { 


    // file save in the com/excelsave folder in my web-app 


         File customerDataFile = new File(appHome, "udaanmasterdatabase.xls"); 
           FileOutputStream out = 
              new FileOutputStream(customerDataFile); 
            workbook.write(out); 
            out.close(); 
            System.out.println("Excel written successfully.."); 

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


         } catch (Exception e) { 
          // TODO Auto-generated catch block 
          e.printStackTrace(); 
         } 



        RequestDispatcher rd = req.getRequestDispatcher("index.do"); 
        rd.forward(req, resp); 
       } 
       else 
       { 
        resp.sendRedirect("logOut.do"); 
       } 


     } 


     private void shadeAlt(HSSFSheet sheet) { 
      // TODO Auto-generated method stub 
      SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); 
      // Condition 1: Formula Is =A2=A1 (White Font) 
      ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("MOD(ROW(),2)"); 
      PatternFormatting fill1 = rule1.createPatternFormatting(); 
      fill1.setFillBackgroundColor(IndexedColors.LIGHT_GREEN.index); 
      fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND); 
       CellRangeAddress[] regions = { 
        CellRangeAddress.valueOf("A1:GG1000") 
      }; 

      sheetCF.addConditionalFormatting(regions, rule1); 
     /* sheet.createRow(0).createCell(1).setCellValue("Shade Alternating Rows");*/ 
      sheet.createRow(1).createCell(1).setCellValue("Condition: Formula Is =MOD(ROW(),2) (Light Green Fill)"); 
      } 
     @Override 
     public void contextDestroyed(ServletContextEvent arg0) { 
      // TODO Auto-generated method stub 

     } 

     @Override 
     public void contextInitialized(ServletContextEvent arg0) { 
      // TODO Auto-generated method stub 


     } 

    } 

/* 나는 내 웹 응용 프로그램 com/excelsave 폴더에 내 excelile을 저장하고 싶지만 거기에는 장신구가 없습니다. 그래서 다른 접근 방식을 제안 해주세요.이 부분에서 NPE를 얻었습니다. {String filePath = "C : /apache-tomcat-7.0.54/webapps"+ getServletContext(). getRealPath ("MyAppHome") + File.separator + "udaanmasterdatabase.xls"} */웹 애플 리케이션 프로젝트 폴더에 엑셀 파일을 만드는 방법,하지만 NullpointerException지고있어?

+1

스택 추적과 함께 널 포인터 예외가 발생하는 코드의 관련 부분을 붙여주십시오. – SMA

+0

NPE에 관해서 : _ 어디서 구할 수 있습니까? 나는 어떤 라인을 의미합니까? 그리고 라인 번호를 알려주지 마십시오. – Thomas

+0

문자열 \t filePath = "C : /apache-tomcat-7.0.54/webapps"+ getServletContext(). getRealPath ("MyAppHome") + File.separator + "udaanmasterdatabase.xls" –

답변

0

다음 링크를 방문하십시오. http://viralpatel.net/blogs/java-read-write-excel-file-apache-poi/

전체 절차를 설명하고 귀하의 문제도 해결 될 것이라고 생각합니다.

+0

네, 절대 로컬 호스트 서버를 실행합니다. 내 로컬 시스템에서 내 파일을하지만이 웹 애플 리케이션 프로젝트 서버에서 자동으로 웹 응용 프로그램 폴더에 생성하고 Excel 파일을 읽고 난 다음 파일을 읽고 wrute 자동으로 다운로드 폴더에 저장 –

관련 문제