簡體   English   中英

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

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

大家好。 我是春季的新人,也是這里的新人。

我有問題。 我有使用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;

    }                       
}   

在我的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。 當我打開此文件時,請嘗試打開瀏覽器並在url上定向我。 當我將其添加到我的PagetoExcelConverter類中時:

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

它正確地保存了所有文件,我的意思是將文件保存為不需要的TXT/HTML ,並按指向的位置保存了xls。 我需要從用戶的瀏覽器中彈出一個小窗口,以使用戶有機會保存在特定位置。 請問你能幫幫我嗎?

添加了對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

關於Spring MVC使用POI有一些教程。

Mark Serrano在這里演示了一種簡單用法-http: //krams915.blogspot.in/2011/02/spring-3-apache-poi-hibernate-creating.html

在我的博客中使用BO和DAO演示了如何使用Excel MVC生成excel模板並將填充到excel文件的數據導入到您自己的數據庫中的一個稍微復雜的版本-http: //avik-ganguly.blogspot.in/ 2013/06 / import-bulk-data-tutorial-apache-poi.html

希望這可以幫助。

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();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM