SpringMVC 生成Excel和PDF

要生成Excel和PDF,就要設置一個顯示自定義視圖的視圖解析器,就是BeanNameViewResolver,因此首先在SpringMVC配置文件中加入這個視圖解析器java

<!--自定義視圖解析器-->
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
       <property name="order" value="100"/>
</bean>

其中的order屬性爲視圖解析器的優先級,數字越小則優先級越高,而默認的InternalResourceViewResolver的order值爲Integer.MAX_VALUE,因此這裏設置的100確定比這個數小,優先級就大。
意味着在請求視圖的時候,SpringMVC先使用該視圖解析器解析,若是沒法解析,則繼續使用優先級較低的InternalResourceViewResolver進行解析。web

接下來寫Excel視圖。建立一個ExcelView類,讓它繼承自AbstractExcelView,而後實現其buildExcelDocument方法。具體類代碼以下spring

@Component
public class ExcelView extends AbstractExcelView{
    @Override
    protected void buildExcelDocument(Map<String, Object> map, org.apache.poi.hssf.usermodel.HSSFWorkbook hssfWorkbook, javax.servlet.http.HttpServletRequest httpServletRequest, javax.servlet.http.HttpServletResponse httpServletResponse) throws Exception {
// 新建一個工做簿
        HSSFSheet sheet = hssfWorkbook.createSheet("list");
        sheet.setDefaultColumnWidth(12);
        HSSFCell cell = getCell(sheet, 0, 0);
        setText(cell, "Spring Excel test");


// 獲得一個單元格
        cell = getCell(sheet, 1, 0);
// 設置單元格的值
        cell.setCellValue("日期:2008-10-23");

        getCell(sheet, 2, 0).setCellValue("測試1");
        getCell(sheet, 2, 1).setCellValue("測試2");

        HSSFRow sheetRow = sheet.createRow(3);
        for (int i = 0; i < 10; i++) {
            sheetRow.createCell(i).setCellValue(i * 10);
        }

    }
}

接下來建立PdfView類,繼承自AbstractPdfView,並實現其buildPdfDocument方法,具體代碼:apache

@Component
public class PdfView extends AbstractPdfView {
    @Override
    protected void buildPdfDocument(Map<String, Object> map, com.lowagie.text.Document document, com.lowagie.text.pdf.PdfWriter pdfWriter, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        List<String> list = new ArrayList<String>();
        list.add("<h1>Hello</h1>");
        list.add("World");

        for (int i = 0; i < list.size(); i++)
            document.add(new Paragraph(list.get(i)));

        document.addTitle("This is a PDF");
        document.addHeader("Header1","Header2");
        document.addAuthor("Elin");

    }
}

接下來,建立一個controller。建立一個名爲ExcelAndPDF的類,並添加兩個控制器方法,使其分別跳轉到對應的視圖tomcat

@Controller
@RequestMapping("/ExcelAndPdf")
public class ExcelAndPdf {

    @RequestMapping("/excel")
    public String excelView(){
        System.out.println("Excel View");
        return "excelView";
    }

    @RequestMapping("/pdf")
    public String pdfView(){
        System.out.println("PDF View");
        return "pdfView";
    }
}

切記,其中的返回字符串必須爲對應視圖的類名且第一個字母小寫。markdown

而後在index.jsp中添加入口app

<a href="ExcelAndPdf/excel">Excel</a><br>
<a href="ExcelAndPdf/pdf">PDF</a>

運行tomcat,就能夠正常獲得Excel和PDF文件了。jsp

相關文章
相關標籤/搜索