Apache POI导出到Web浏览器中的Excel

时间:2016-09-28 06:22:01

标签: java excel apache-poi

我想在浏览器中导出excel文件并在浏览器下载位置下载文件(与浏览器中发生的任何下载相同)。我正在使用以下servlet导出文件,它没有显示下载或它没有下载到浏览器默认下载位置。但文件已导出到项目位置。

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    // PrintWriter out = response.getWriter();

    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-Disposition",
            "attachment; filename=filename.xls");
    try {
        // ExportClass export = new ExportClass();
        // export.export();

        XSSFWorkbook workbook = new XSSFWorkbook();
        // Create a blank sheet
        XSSFSheet spreadsheet = workbook.createSheet(" Employee Info ");
        // Create row object
        XSSFRow row = spreadsheet.createRow(1);
        XSSFCell cell;
        cell = row.createCell(1);
        cell.setCellValue("AGE");
        cell = row.createCell(2);
        cell.setCellValue("ID");
        cell = row.createCell(3);
        cell.setCellValue("NAME");

        int i = 2;
        DbCon db = new DbCon();
        ArrayList<Student> students = db.getStudentList();

        for (int x = 0; x < students.size(); x++) {

            row = spreadsheet.createRow(i);
            cell = row.createCell(1);
            cell.setCellValue(students.get(x).studentAge);
            cell = row.createCell(2);
            cell.setCellValue(students.get(x).studentID);
            cell = row.createCell(3);
            cell.setCellValue(students.get(x).stuntName);
            i++;
        }

        // Write the workbook in file system

        OutputStream out = response.getOutputStream();
        System.out.println("going to export");
        workbook.write(out);
        out.close();
        System.out.println("exceldatabase.xlsx written successfully");

    }

请帮我弄清问题。感谢。

0 个答案:

没有答案