如何将数据从struts2导出到Excel

时间:2016-11-30 09:29:19

标签: struts2 apache-poi

我希望数据以Excel格式导出。我在将数据写入Excel文件时遇到问题,当我下载时,它不是Excel格式。

在下面的第一个方法中,我从数据库获取数据并将其作为列表发送到需要文件名的第二个方法。在第二种方法中,我试图将数据库数据写入Excel文件。

我已经完成了导出为PDF的编码。它被正确下载,但在URL栏downloadTeacherListINExcel.action中。我给出了这样的文件路径:String fileName = "f:\\teachersList.pdf"。当它在浏览器中下载时,文件名就像f-teachersList一样。

public String exportInExcel() {

        // getting data from data base 
        listOfTeachers = reportService.getlistOfTeachers();
        for (TeacherDTO teacherDTO : listOfTeachers) {
            System.out.println(teacherDTO.getTeacherEmailID());
        }

        // sending a list data export in excel
        String excelFileName = reportService.exportInExcel(listOfTeachers);
        System.out.println(excelFileName);
        try {
            fileInputStream = new FileInputStream(excelFileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("Execl Download Method");
        return SUCCESS;
    }

为Excel编写的代码

@Override
    public String exportInExcel(List<TeacherDTO> listOfTeachers) {
        String fileName = "f:\\test\\teachersList.xls";
        try {

            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("Products List");

            // create heading
            Row rowHeading = sheet.createRow(0);

            rowHeading.createCell(0).setCellValue("Id");
            rowHeading.createCell(1).setCellValue("Name");

            for (int i = 0; i < 6; i++) {

                CellStyle stylerowHeading = workbook.createCellStyle();

                Font font = workbook.createFont();
                font.setBoldweight(Font.BOLDWEIGHT_BOLD);
                font.setFontName(HSSFFont.FONT_ARIAL);
                font.setFontHeightInPoints((short) 11);

                stylerowHeading.setFont(font);
                stylerowHeading.setVerticalAlignment(CellStyle.ALIGN_CENTER);

                rowHeading.getCell(i).setCellStyle(stylerowHeading);
            }

            int r = 1;
            for (TeacherDTO teacher : listOfTeachers) {
                Row row = sheet.createRow(r);

                // Id column
                Cell cellID = row.createCell(0);
                cellID.setCellValue(teacher.getTeacherFirstName());// (run after
                                                                    // this line
                                                                    // once)

                // name column
                Cell cellName = row.createCell(1);
                cellName.setCellValue(teacher.getTeacherEmailID());// (run after
                                                                    // this line
                                                                    // once)

                r++;
            }

            // Auto fit
            for (int i = 0; i < 6; i++) {
                sheet.autoSizeColumn(i);
            }

            FileOutputStream fout = new FileOutputStream(new File(fileName));
            workbook.write(fout);
            fout.close();

            System.out.println("Excel Written Success");

        } catch (Exception e) {
        System.out.println("%%%%%%%%%%%%%%%%%%"+e.getMessage());
        }
        return fileName;
    }

Struts config

<action name="downloadTeacherListINExcel" class="com.pradeep.sms.controller.report.StaffReportAction" method="exportInExcel">
            <result  name="success"  type="stream">

                <param name="contentType">application/vnd.ms-excel</param>
                <param name="inputName">fileInputStream</param>
                 <param name="contentDisposition">attachment;filename=${fileName}</param>
                <param name="bufferSize">1024</param>
        </result>
    </action>   

错误

Hibernate: select 
pradeepkumarhe1989@gmail.com
%%%%%%%%%%%%%%%%%%null
f:\test\teachersList.xls
java.io.FileNotFoundException: f:\test\teachersList.xls (The system cannot find the file specified)

1 个答案:

答案 0 :(得分:1)

在行动课

 public String exportInExcel() {

                //getting List of teachers
                listOfTeachers = reportServiceExcel.getlistOfTeachers();

                // sending list data to write in excel sheet
                HSSFWorkbook workbook = reportServiceExcel.exportInExcel(listOfTeachers);

                // code to download
                try {
                    ByteArrayOutputStream boas = new ByteArrayOutputStream();
                    workbook.write(boas);
                    setInputStream(new ByteArrayInputStream(boas.toByteArray()));
                } catch (IOException e) {
                    e.printStackTrace();
                }

                return SUCCESS;
            }

Excel类

 public HSSFWorkbook exportInExcel(List<TeacherDTO> listOfTeachers) {

            HSSFWorkbook workbook = null;
            try {
                workbook = new HSSFWorkbook();
                HSSFSheet sheet = workbook.createSheet("Products List");

                // create heading
                Row rowHeading = sheet.createRow(0);

                rowHeading.createCell(0).setCellValue("Name");
                rowHeading.createCell(1).setCellValue("Mobile Number");
                rowHeading.createCell(2).setCellValue("Email ID");
                rowHeading.createCell(3).setCellValue("Designation");

                for (int i = 0; i < 4; i++) {
                    CellStyle stylerowHeading = workbook.createCellStyle();
                    Font font = workbook.createFont();
                    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
                    font.setFontName(HSSFFont.FONT_ARIAL);
                    font.setFontHeightInPoints((short) 11);
                    stylerowHeading.setFont(font);
                    stylerowHeading.setVerticalAlignment(CellStyle.ALIGN_CENTER);
                    rowHeading.getCell(i).setCellStyle(stylerowHeading);
                }

                int r = 1;
                for (TeacherDTO t : listOfTeachers) {

                    String teacherName = t.getTeacherFirstName() + "" + t.getTeacherMiddleName() + ""
                            + t.getTeacherLastName();
                    Row row = sheet.createRow(r);

                    // Name column
                    Cell cellName = row.createCell(0);
                    cellName.setCellValue(teacherName);// (run after this line once)

                    // Mobile Number column
                    Cell cellMobileNumber = row.createCell(1);
                    cellMobileNumber.setCellValue(t.getTeacherMobileNumber());

                    // Email column
                    Cell cellEmail = row.createCell(2);
                    cellEmail.setCellValue(t.getTeacherEmailID());

                    // Designation column
                    Cell cellDesignation = row.createCell(3);
                    cellDesignation.setCellValue(t.getTeacherDesignation());

                    r++;
                }

                // Auto fit columns in excel sheet
                for (int i = 0; i < 4; i++) {
                    sheet.autoSizeColumn(i);
                }


                System.out.println("Excel Written Success");

            } catch (Exception e) {
                e.printStackTrace();
            }
            return workbook;
        }

Struts配置

<action name="downloadTeacherListExcel" class="com.pradeep.sms.controller.report.StaffReportAction" method="exportInExcel">
    <result  name="success"  type="stream">           
        <param name="contentType">application/vnd.ms-excel</param>
        <param name="inputName">inputStream</param>
        <param name="contentDisposition">attachment;filename="teachersList.xls"</param>
        <param name="bufferSize">4096</param>
    </result>
</action>