简体   繁体   English

Spring MVC和Apache POI创建xls doc。 无法保存模型中新创建的文件

[英]Spring MVC and Apache POI to create xls doc. Can't save newly created file from model

Good day people. 大家好。 I'm new in Spring as well as new here. 我是春季的新人,也是这里的新人。

I have problem. 我有问题。 I have class to create xls document with Apache POI: 我有使用Apache 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;

    }                       
}   

In my servlet-context I have: 在我的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>

In my controller class I have method: 在我的控制器类中,我有方法:

@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";
    }

The problem is that it doesn't save newly created file fetched from model data. 问题在于它不会保存从模型数据中获取的新创建的文件。 Instead of this it saves something completely different file looks like TEXT/HTML not xls. 取而代之的是,它可以保存一些完全不同的文件,例如TEXT/HTML而不是xls。 When I open this this file try to open browser and direct me on url. 当我打开此文件时,请尝试打开浏览器并在url上定向我。 When I add to my PagetoExcelConverter class this: 当我将其添加到我的PagetoExcelConverter类中时:

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

It saves all correctly, I mean it saves the file with TXT/HTML which I don't need and saves xls by where I point it to. 它正确地保存了所有文件,我的意思是将文件保存为不需要的TXT/HTML ,并按指向的位置保存了xls。 I need a little window pop up for user from his browser to give a user chance to save in particular place. 我需要从用户的浏览器中弹出一个小窗口,以使用户有机会保存在特定位置。 Could you help me please? 请问你能帮帮我吗?

Added call to buildExelDocument(): 添加了对buildExelDocument():调用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

There are a couple of tutorials on using POI with Spring MVC. 关于Spring MVC使用POI有一些教程。

A simple usage is demonstrated by Mark Serrano here - http://krams915.blogspot.in/2011/02/spring-3-apache-poi-hibernate-creating.html . Mark Serrano在这里演示了一种简单用法-http: //krams915.blogspot.in/2011/02/spring-3-apache-poi-hibernate-creating.html

A slightly more complex version of how to generate the excel template and import the data filled into the excel file to your own database using Spring MVC is demonstrated in my blog using BO and DAO - http://avik-ganguly.blogspot.in/2013/06/import-bulk-data-tutorial-apache-poi.html . 在我的博客中使用BO和DAO演示了如何使用Excel MVC生成excel模板并将填充到excel文件的数据导入到您自己的数据库中的一个稍微复杂的版本-http: //avik-ganguly.blogspot.in/ 2013/06 / import-bulk-data-tutorial-apache-poi.html

Hope this helps. 希望这可以帮助。

1º.- Add the jar of apache.poi libraries to your project. 1º。-将jar apache.poi库添加到您的项目中。

2º.- In a method of your controller generates the xlsx as follows: 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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM