导出后,URL中不应包含Servlet名称

时间:2018-12-12 06:56:33

标签: java html servlets apache-poi

public class ExcelWriter extends HttpServlet{
    private void writeExcel(List<Book> listBook, String excelFilePath)
            throws IOException {
        Workbook workbook = getWorkbook(excelFilePath);
        Sheet sheet = workbook.createSheet();

        int rowCount = 0;

        for (Book aBook : listBook) {
            Row row = sheet.createRow(++rowCount);
            writeBook(aBook, row);
        }

        try (FileOutputStream outputStream = new FileOutputStream(new File(
                excelFilePath))) {
            workbook.write(outputStream);
        }
    }

    private void writeBook(Book aBook, Row row) {
        Cell cell = row.createCell(1);
        cell.setCellValue(aBook.getTitle());

        cell = row.createCell(2);
        cell.setCellValue(aBook.getAuthor());

        cell = row.createCell(3);
        cell.setCellValue(aBook.getPrice());
    }

    private List<Book> getListBook() {
        Book book1 = new Book("Head  Java", "Anot Serria", 79);
        Book book2 = new Book("Effective Java 1", "Bnot Bloch", 36);
        Book book3 = new Book("Clean Code 1", "Cnot Martin", 42);
        Book book4 = new Book("Thinking in Java 2", "D Eckel", 35);

        List<Book> listBook = Arrays.asList(book1, book2, book3, book4);

        return listBook;
    }

    private Workbook getWorkbook(String excelFilePath) throws IOException {
        Workbook workbook = null;

        if (excelFilePath.endsWith("xlsx")) {
            workbook = new XSSFWorkbook();
        } else if (excelFilePath.endsWith("xls")) {
            workbook = new HSSFWorkbook();
        } else {
            throw new IllegalArgumentException(
                    "The specified file is not Excel file");
        }

        return workbook;

    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            ExcelWriter excelWriter = new ExcelWriter();
            List<Book> listBook = excelWriter.getListBook();
            String excelFilePath = "C:\\ExcelTemp\\Temp.xls";
             excelWriter.writeExcel(listBook, excelFilePath);

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
  • 在下载excel文件后,Servlet应将我指向初始视图页面,即从中导出数据。我不想将其转发到正在使用的同一页面。

    功能应类似于我从索引中导出数据。html-->ExcelWriter Servlet。但是url不应显示Servlet部分。请帮我。我正在使用Apache POI和Servlet。我也有一本带有getter和setter方法的POJO手册。

1 个答案:

答案 0 :(得分:1)

您可以在Web描述符文件(xml文件)中进行servlet映射。