2013-07-27 37 views
1

新创建的文件好日子的人。我在春天以及新在这里都是新手。Spring MVC和Apache POI创建xls文档。无法保存从模型

我有问题。我有类创建XLS文件与Apache POI:

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; 

    }      
} 

在我的servlet上下文,我有:

<!-- 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。当我打开这个文件时,尝试打开浏览器并指向我的网址。当我加入我PagetoExcelConverter类这样的:

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

这一切都正确保存,我的意思是保存与TXT/HTML的文件,我不需要和我点它的地方保存XLS。我需要从他的浏览器弹出一个小窗口给用户,让用户有机会保存在特定的位置。请问你能帮帮我吗?

新增呼叫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方法()?我上周刚刚使用了POI,可能会提供帮助。 – JBuenoJr

+0

是的。当我调用xlspage.jsp页面时触发这个方法。 – UDS

+0

啊,对于混乱感到抱歉。我会删除我的答案,因为我误解了你的问题。对不起,我不熟悉Spring,无法回答这个问题。 – JBuenoJr

回答

0

有一对夫妇使用POI与Spring MVC的教程。

一个简单的用法由Mark Serrano在这里演示 - http://krams915.blogspot.in/2011/02/spring-3-apache-poi-hibernate-creating.html

如何生成excel模板并使用Spring MVC将填充到excel文件中的数据导入到您自己的数据库中的稍微复杂一些的版本在我的博客中使用BO和DAO - http://avik-ganguly.blogspot.in/2013/06/import-bulk-data-tutorial-apache-poi.html进行了演示。

希望这会有所帮助。

+0

这是有用的,但我找到了最简单的方法。这是在我的帖子中使用ResourceBundleViewResolver,只是不明白为什么我没有从浏览器弹出窗口。 – UDS

-1

1º.-将jar包中的apache.poi库添加到您的项目中。

2º.-在你的控制器的方法生成XLSX如下:

@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

我希望现在,如果你喜欢它,并发现它有用。 –

相关问题