简体   繁体   中英

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:

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:

<!-- 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. When I open this this file try to open browser and direct me on url. When I add to my PagetoExcelConverter class this:

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. 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():

#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.

A simple usage is demonstrated by Mark Serrano here - 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 .

Hope this helps.

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

In a method of your controller generates the xlsx as follows: 在您的控制器的一种方法中,生成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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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