2013-07-27 1 views
1

좋은 하루 사람. 저는 봄에 새로 왔을뿐만 아니라 새로 왔습니다.스프링 MVC와 Apache POI를 사용하여 xls doc을 만듭니다. 모델에서 새로 만든 파일을 저장할 수 없습니다.

문제가 있습니다. 제가 아파치 POI로 XLS 문서를 만들 수있는 클래스가 : 내 서블릿 컨텍스트에서

public class PagetoExcelConverter extends AbstractExcelView{ 

    List<FormDate> attributesList = null; 

    //Create massive of constants for making table header 
    private final String[] HEADER_NAMES_MASSIVE = {"HEADER1", "HEADER2", "HEADER3"}; 


    @SuppressWarnings("unchecked") 
    @Override 
    protected void buildExcelDocument(Map<String, Object> model, 
      HSSFWorkbook workbook, HttpServletRequest request, 
      HttpServletResponse response) throws Exception { 

       //Creating new instance of ArrayList for add model attributes to 
      attributesList = new ArrayList<FormDate>(); 

       //Adding model attributes to ArrayList 
       attributesList.addAll((List<FormDate>)model.get("findAttributes")); 

     //Creating sheet inside of book with given name 
     Sheet sheet = workbook.createSheet("Result"); 
      sheet.autoSizeColumn(0); 

     //Making first row as a header 
     Row headerRow = sheet.createRow(0); 


     for(int i=0; i<HEADER_NAMES_MASSIVE.length; i++) {  

      Cell headCell = headerRow.createCell(i); 
      headCell.setCellValue(HEADER_NAMES_MASSIVE[i]); 
      headCell.setCellStyle(headCellstyle);    
      } 


      int rowNumber=1; 

     for(int i=0; i<attributesList.size(); i++) { 

      Row dataRow = sheet.createRow(rowNumber); 
      Cell dataCell; 

      int cellNumber=0; 

       dataCell = dataRow.createCell(cellNumber); 
       dataCell.setCellValue(attributesList.get(i).getFormDescriptionList().get(i).getInstitutions().getNameOfInstitution()); 

       cellNumber++; 

       dataCell = dataRow.createCell(cellNumber); 
       dataCell.setCellValue(attributesList.get(i).getFormDescriptionList().get(i).getInstitutionType().getTypeOfInstitution()); 

       cellNumber++; 

       dataCell = dataRow.createCell(cellNumber); 
       dataCell.setCellValue(attributesList.get(i).getParticularDate().toString()); 

       cellNumber++; 


       rowNumber++; 

       FileOutputStream fos = new FileOutputStream("/home/vadim/Desktop/mybook.xls"); 
       workbook.write(fos); 

     } 

     attributesList = null; 

    }      
} 

을 나는이 내 컨트롤러 클래스에서

<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/classes directory. Goes first --> 
    <beans:bean id="xlsviewResolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver"> 
    <beans:property name="order" value="1" /> 
    <beans:property name="basename" value="views"/> 
    </beans:bean> 

내가 가진 방법 :

@RequestMapping(value="/result", method=RequestMethod.POST, params="asexcel") 
    public String resultXLS(@RequestParam String particularDate, 
          @RequestParam String institutionName, 
          @RequestParam String institutionType, Model model) throws Exception { 

     if((!particularDate.equals("")) && !institutionName.equals("") && institutionType.equals("")) { 

      model.addAttribute("findAttributes", educationWebService.fetchByDateAndNameService(dateConvertation(particularDate), institutionName)); 

     } else if((!particularDate.equals("")) && (institutionName.equals("")) && (!institutionType.equals(""))) { 

      model.addAttribute("findAttributes", educationWebService.fetchByDateAndTypeService(dateConvertation(particularDate), institutionType));     

     } else if((!particularDate.equals("")) && institutionName.equals("") && institutionType.equals("")) { 

      model.addAttribute("findAttributes", educationWebService.fetchByDateService(dateConvertation(particularDate))); 

     } else {   
      throw new Exception("Exception occurs because it's not correspond to any case in controller"); 
     }  

     return "xlspage"; 
    } 

문제 모델 데이터에서 가져온 새로 생성 된 파일을 저장하지 않는다는 것입니다. 이 대신에 뭔가 완전히 다른 파일을 저장합니다. TEXT/HTML xls가 아닙니다. 이 파일을 열면 브라우저를 열고 URL을 직접 입력 해보십시오. 내 PagetoExcelConverter 수업이에 추가 할 때 : 모든 올바르게 저장

FileOutputStream fos = new FileOutputStream("/home/vadim/Desktop/mybook.xls"); 
       workbook.write(fos); 

, 내 말은 내가 필요하고 내가 그것을 가리 곳으로 XLS를 저장하지 않는 TXT/HTML으로 파일을 저장합니다. 나는 그의 브라우저에서 사용자를위한 작은 창 팝업이 필요하여 사용자가 특정 장소에서 저장할 수있는 기회를 제공합니다. 제발 도와 주실 수 있나요?

추가 호출 buildExelDocument():

#This view property triggered from org.springframework.web.servlet.view.ResourceBundleViewResolver for xls converting 
#Here is xlspage is name of the jsp page, is tied in with (class) with do converting model to xls 
xlspage.(class)=edu.demidov.service.PagetoExcelConverter 
+0

당신이() 우리에게 buildExcelDocument에 대한 호출을 표시 할 수 있습니다 : 다음과 같이 제어하는 ​​방법에

2º.-는 XLSX를 생성? 지난 주에 POI를 사용했고 도움을 줄 수 있습니다. – JBuenoJr

+0

예. 이 메소드는 xlspage.jsp 페이지를 호출 할 때 트리거됩니다. – UDS

+0

아, 혼란에 대 한 미안 해요. 나는 당신의 문제를 오해 한 것처럼 내 대답을 제거 할 것입니다. 죄송합니다. 저는 스프링에 익숙하지 않고 질문에 대답 할 수 없습니다. – JBuenoJr

답변

0

에 스프링 MVC와 POI를 사용하는 방법에 대한 자습서의 몇 가지가 있습니다.

Mark Serrano의 간단한 사용법은 여기에서 - http://krams915.blogspot.in/2011/02/spring-3-apache-poi-hibernate-creating.html입니다.

봄 MVC를 사용하여 엑셀 템플릿을 생성하고 엑셀 파일에 채워진 데이터를 자신의 데이터베이스로 가져 오는 방법이 약간 더 복잡한 버전이 내 블로그에서 BO 및 DAO - http://avik-ganguly.blogspot.in/2013/06/import-bulk-data-tutorial-apache-poi.html을 사용하여 시연되었습니다.

희망이 도움이됩니다.

+0

이것은 유용하지만 가장 쉽게 만들 수있는 방법을 찾았습니다. 이것은 내 게시물 ResourceBundleViewResolver를 사용하여, 그냥 왜 팝업 창이 브라우저에서 팝업 이해가되지 않습니다. – UDS

-1

1º- apache.poi 라이브러리의 jar를 프로젝트에 추가하십시오.

@RequestMapping 
public void descargar_archivo(String dato, HttpServletRequest hsr, HttpServletResponse response) { 
    // Initialize your book and sheet 
    Workbook wb = new XSSFWorkbook(); 
    String safeName = WorkbookUtil.createSafeSheetName("Datos"); 
    Sheet sheet = wb.createSheet(safeName); 
    sheet.getPrintSetup().setLandscape(true); 
    sheet.getPrintSetup().setPaperSize(XSSFPrintSetup.LETTER_PAPERSIZE); 
    // 
    Row row; 
    Cell cell; 
    // We put the data we want 
    String titulo = dato + "Generated Data"; 
    row = sheet.createRow(0); 
    cell = row.createCell(0); 
    cell.setCellValue(titulo); 

    // We set the column width auto 
    sheet.autoSizeColumn((short) 0); 

    // We modify the return flow 
    // to return our file xlsx 
    try { 
     // We place the necessary headers 
     response.reset(); 
     response.setStatus(HttpServletResponse.SC_OK); 
     response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); 
     response.setHeader("Expires:", "0"); // eliminates browser caching 
     // We assign the name of our file 
     response.setHeader("Content-Disposition", "inline; attachment; filename=MisDatos.xlsx"); 
     // Captured backflow 
     OutputStream out = response.getOutputStream(); 
     wb.write(out);  // We write in that flow 
     out.flush();  // We emptied the flow 
     out.close();  // We close the flow 
    } catch (Exception ex) { 
     ex.printStackTrace(); 
    } 
} 
+2

에 오신 것을 환영합니다. 영어로 써주십시오. – mpromonet

+0

나는 당신이 그것을 즐기고 유용하다고 여기기를 바랍니다. –