e代剑客——温柔一刀

生活就像海洋,只有意志坚强的人,才能到达彼岸

   :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  76 随笔 :: 7 文章 :: 215 评论 :: 0 Trackbacks
HTML页面并不总是向用户显示数据输出的最好方式,有时候需要生成不可改变的文件打印,PDF可能是种不错的选择。

Spring支持从数据动态生成PDF或Excel文件

下面这个简单实现的例子实现了spring输出PDF和Excel文件,为了使用Excel电子表格,你需要在你的classpath中加入poi-2.5.1.jar库文件,而对PDF文件,则需要iText.jar文件。它们都包含在Spring的主发布包中。

下面是测试项目代码:


1、控制器配置代码
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
    
<bean id="beanNameViewResolver"
        class
="org.springframework.web.servlet.view.BeanNameViewResolver" />

    
<bean id="viewController" class="com.zhupan.spring.ViewController" />
    
<bean id="urlMapping"
        class
="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        
<property name="mappings">
            
<props>
                
<prop key="/view*.shtml">viewController</prop>
            
</props>
        
</property>
    
</bean>
</beans>

 3、用于Excel视图的视图子类化
为了在生成输出文档的过程中实现定制的行为,我们将继承合适的抽象类。对于Excel,这包括提供一个 org.springframework.web.servlet.view.document.AbstractExcelView的子类,并实现 buildExcelDocument方法。
package com.zhupan.view;

import java.util.Date;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.servlet.view.document.AbstractExcelView;


public class ViewExcel extends AbstractExcelView {

  
public void buildExcelDocument(
             Map model, HSSFWorkbook workbook,
             HttpServletRequest request, HttpServletResponse response)
    
throws Exception {
  
       HSSFSheet sheet 
= workbook.createSheet("list");
       sheet.setDefaultColumnWidth((
short12);
       
       
       HSSFCell cell 
= getCell(sheet, 00);
       setText(cell, 
"Spring Excel test");
  
       HSSFCellStyle dateStyle 
= workbook.createCellStyle();
       dateStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat(
"m/d/yy"));
       cell 
= getCell(sheet, 10);
       cell.setCellValue(
new Date());
       cell.setCellStyle(dateStyle);
       getCell(sheet, 
20).setCellValue(458);
  
       HSSFRow sheetRow 
= sheet.createRow(3);
       
for (short i = 0; i < 10; i++{
             sheetRow.createCell(i).setCellValue(i 
* 10);
       }


  }

  
}


4、用于PDF视图的视图子类化
需要象下面一样继承org.springframework.web.servlet.view.document.AbstractPdfView,并实现buildPdfDocument()方法。
package com.zhupan.view;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.view.document.AbstractPdfView;

import com.lowagie.text.Document;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;

public class ViewPDF extends AbstractPdfView {
    
public void buildPdfDocument(Map model, Document document,
            PdfWriter writer, HttpServletRequest request,
            HttpServletResponse response) 
throws Exception {

        List list 
= (List) model.get("list");

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


}

5、其他文件
1)控制器ViewController
package com.zhupan.spring;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.zhupan.view.ViewExcel;
import com.zhupan.view.ViewPDF;


public class ViewController extends MultiActionController{
     
     
public ModelAndView viewPDF(HttpServletRequest request, HttpServletResponse response) throws Exception {
       List list 
= new ArrayList();
       Map model
=new HashMap();
       list.add(
"test1");
       list.add(
"test2");
       model.put(
"list",list);
       ViewPDF viewPDF
=new ViewPDF();
       
return new ModelAndView(viewPDF,model);
  }

     
      
public ModelAndView viewExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
            List list 
= new ArrayList();
        Map model
=new HashMap();
        list.add(
"test1");
        list.add(
"test2");
        model.put(
"list",list);
        ViewExcel viewExcel
=new ViewExcel();
        
return new ModelAndView(viewExcel,model);
      }

}
2)web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation
="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
>

    
<display-name>springPDFTest</display-name>
    
<servlet>
        
<servlet-name>springPDFTest</servlet-name>
        
<servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        
</servlet-class>
        
<load-on-startup>1</load-on-startup>
    
</servlet>

    
<servlet-mapping>
        
<servlet-name>springPDFTest</servlet-name>
        
<url-pattern>*.shtml</url-pattern>
    
</servlet-mapping>

    
<welcome-file-list>
        
<welcome-file>index.jsp</welcome-file>
    
</welcome-file-list>

</web-app>

3)index.jsp
<%@ page contentType="text/html; charset=gb2312"%>

<href="viewPDF.shtml">PDF视图打开 </a>
<br>
<href="viewExcel.shtml">Excel视图打开</a>
posted on 2006-10-04 12:11 温柔一刀 阅读(7274) 评论(7)  编辑  收藏 所属分类: 开源框架

评论

# re: spring 生成Excel和PDF文件 2006-10-15 17:06 曲静波
有个问题,如果不用spring的controller或改成struts的action或servlet可以使用viewPdf 和 viewExcel吗?  回复  更多评论
  

# re: spring 生成Excel和PDF文件 2006-10-16 08:52 温柔一刀
@曲静波
直接是不可以的
因为它们都extends AbstractPdfView
而AbstractPdfView是spring提供的
org.springframework.web.servlet.view.document.AbstractExcelView
如果要用的话就得把spring的包导入项目  回复  更多评论
  

# re: spring 生成Excel和PDF文件 2007-04-04 15:12 yangaries
我把它部署在Eclipse中,为什么单击“Excel视图打开”后提示“Servlet springPDFTest is not available”呢?
  回复  更多评论
  

# re: spring 生成Excel和PDF文件 2007-04-04 16:40 yangaries
解决了,jar包放错地方了,呵呵。
能解释一下在位置文件中控制是怎样传递的么?  回复  更多评论
  

# re: spring 生成Excel和PDF文件[未登录] 2008-10-21 17:55 michael
请问楼上的,我也遇到同样的问题了,你能不能告诉我详细点的解决方案呢  回复  更多评论
  

# re: spring 生成Excel和PDF文件[未登录] 2008-10-21 17:59 michael
17:05:32,125 INFO [STDOUT] 2008-10-21 17:05:32,109 [main] ERROR org.springframe
work.web.servlet.DispatcherServlet - Context initialization failed
org.springframework.beans.factory.BeanDefinitionStoreException: IOException pars
ing XML document from ServletContext resource [/WEB-INF/springPDFTest-servlet.xm
l]; nested exception is java.io.FileNotFoundException: Could not open ServletCon
text resource [/WEB-INF/springPDFTest-servlet.xml]
Caused by:
java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/
springPDFTest-servlet.xml]
------------------------------
这个是JBOSS的错误信息  回复  更多评论
  

# re: spring 生成Excel和PDF文件 2010-03-10 16:07 XT
在 使用 Excel视图打开 的时候有中文乱码问题,
搞了半天都没解决 ,楼主,再麻烦一下  回复  更多评论
  


只有注册用户登录后才能发表评论。


网站导航:
 
联系偶 zhupanjava@gmail.com 温柔一刀