2

美好的一天人们。我是新来的春天,也是新来的。

我有问题。我有课用 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/HTMLxls。当我打开这个文件时,尝试打开浏览器并引导我访问 url。当我添加到我的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
4

2 回答 2

0

有一些关于在 Spring MVC 中使用 POI 的教程。

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

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

希望这可以帮助。

于 2013-07-28T13:51:46.783 回答
-1

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

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();
    }
}
于 2014-08-26T17:32:30.337 回答