转载:点击打开链接

现在的项目需要把用户反馈的信息表中的数据导出到excel的需求。之前做过类似的事情,但是时间已经久远,只能网上搜了一下,对于struts2,基本使用poi的方法,但是感觉网上的方法比较乱及不靠谱(没有开v*n 去google),就把之前的老项目用到的方法拿出来,整理如下,希望对大家有用。确实很简单(对于使用,里面的原理没有深入了解,可能我这边使用的是基本功能,如果需要细致研究,去apache下载jar包的时候,顺便把源码下载下来,这样就可以一目了然了。)

       不多说,先从架构(使用步骤,从前端到后端,方式和action走的路径一致,只是多了对excel流的处理):

  •   前端jsp页面,加个点击的按钮或者超链接;
    [html] view plain copy
    1. <a href="feedBackReportAction_exportExcel.action">导出</a>  

  •   struts.xml中加个action:
[html] view plain copy
  1.             <action name="feedBackReportAction_exportExcel" class="feedBackReportAction" method="exportExcel">  
  2.     <result name="excel" type="stream">  
  3.         <param name="contentType">  
  4.             application/vnd.ms-excel  
  5.         </param>  
  6.         <param name="inputName">excelStream</param>  
  7.         <param name="contentDisposition">  
  8.             attachment;filename="${fileName}"  
  9.         </param>  
  10.         <param name="bufferSize">1024</param>  
  11.     </result>  
  12.     <result name="input" type="redirect">feedBackWebAction_queryAll.action</result>  
  13. </action>  

             从action可以看出,result中 name为excel的类型为stream,并且有几个参数,对于自己的项目,其他的不需要动,只是需要注意"${fileName}",这个是后面action中定义的一个String名称,作为下载时显示的xls的文件名。当然名称为input的result跳转的地址需要自己定义的。
  •    action只是很简单的类:
    其中的exportExcel方法如下:
    [java] view plain copy
    1. public String exportExcel() throws IOException{  
    2.         HttpServletRequest request = ServletActionContext.getRequest();  
    3.   
    4.         List<FeedBack> listFeedBack = feedBackService.getAll();  
    5.         if ( listFeedBack == null )  
    6.             return ERROR;  
    7.           
    8.         Map beans = new HashMap();  
    9.         beans.put("feedback", listFeedBack);  
    10.         SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");  
    11.         // 填充报表  
    12.         filePath += "feedBackTemplet.xls";  
    13.         fileName = "用户反馈信息报表.xls";  
    14.           
    15.         beans.put("createDate", df.format(new Date()));  
    16.           
    17.         excelStream = new ExcelReport().makeReportFromTemplet(request  
    18.                 .getRealPath("/WEB-INF")  
    19.                 + filePath, beans);  
    20.           
    21.         if (excelStream == null) {  
    22.             return INPUT;  
    23.         }  
    24.         return "excel";  
    25.     }  
    很简单吧,我需要显示的bean就是数据库中的表,不需要作其他的操作,如果有需要,自己填充到Map中,上文提到的fileName也在这赋值了。其中
    [java] view plain copy
    1. excelStream = new ExcelReport().makeReportFromTemplet(request  
    2.                 .getRealPath("/WEB-INF")  
    3.                 + filePath, beans);  
    这句是核心,把beans的内容,写到excel模板中。用的类----ExcelReport。就是所谓的poi。这个类的代码,会贴到此文章的最后。
  • poi帮助类   (直接贴代码)      
         Report.java接口
         
[java] view plain copy
  1. import java.io.InputStream;  
  2. import java.util.Collection;  
  3. import java.util.Map;  
  4.   
  5. public interface Report {  
  6.     @SuppressWarnings("rawtypes")  
  7.     public void makeReport(Collection collection, String filePath);  
  8.       
  9.     public void makeReport(String[] dataStr, String filePath);  
  10.       
  11.     @SuppressWarnings("rawtypes")  
  12.     public void makeReport(Collection collection, String[] collumHead, String filePath);  
  13.     /** 
  14.      * 按模板生成报表,使用jxls设置报表模板,用于通过浏览器下载报表 
  15.      * @param templetFileName 模板文件绝对路径+模板文件名 
  16.      * @param beans 模板参数对象集合 
  17.      * @return InputStream   
  18.      */  
  19.     @SuppressWarnings("rawtypes")  
  20.     public InputStream makeReportFromTemplet(String templetFileName, Map beans);  
  21.     /** 
  22.      * 按模板生成报表,使用jxls设置报表模板,直接生成本地文件 
  23.      * @param templetFileName 
  24.      * @param beans 
  25.      * @param targetFileName 
  26.      */  
  27.     @SuppressWarnings("rawtypes")  
  28.     public void makeReportFromTemplet(String templetFileName, Map beans, String targetFileName);  
  29.       
  30. }  
        继承类,即action调用的类
        ExcelReport.java
        
[java] view plain copy
  1. import java.io.ByteArrayInputStream;  
  2. import java.io.ByteArrayOutputStream;  
  3. import java.io.FileInputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.util.Collection;  
  7. import java.util.Map;  
  8.   
  9. import net.sf.jxls.exception.ParsePropertyException;  
  10. import net.sf.jxls.transformer.Configuration;  
  11. import net.sf.jxls.transformer.XLSTransformer;  
  12.   
  13. import org.apache.poi.hssf.usermodel.HSSFSheet;  
  14. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  15. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;  
  16. import org.apache.poi.ss.usermodel.Sheet;  
  17. import org.apache.poi.ss.usermodel.Workbook;  
  18. /** 
  19.  * Excel报表类 
  20.  * 
  21.  */  
  22. public class ExcelReport implements Report {  
  23.     public static final String POSTIFIX = ".xls";  
  24.   
  25.     protected String reportName;  
  26.     protected Workbook workBook = new HSSFWorkbook();  
  27.     protected Sheet sheet;  
  28.     protected String sheetName;  
  29.     protected InputStream excelStream;  
  30.   
  31.     public ExcelReport(String reportName, String sheetName) {  
  32.         super();  
  33.         this.reportName = reportName;  
  34.         this.sheetName = sheetName;  
  35.         sheet = workBook.createSheet(sheetName);  
  36.     }  
  37.   
  38.     public ExcelReport() {  
  39.         super();  
  40.     }  
  41.   
  42.     @SuppressWarnings({ "rawtypes" })  
  43.     @Override  
  44.     public void makeReport(Collection collection, String filePath) {  
  45.   
  46.     }  
  47.   
  48.     @Override  
  49.     public void makeReport(String[] dataStr, String filePath) {  
  50.   
  51.     }  
  52.       
  53.     @SuppressWarnings("rawtypes")  
  54.     @Override  
  55.     public void makeReport(Collection collection, String[] collumHead,  
  56.             String filePath) {  
  57.   
  58.     }  
  59.       
  60.     @SuppressWarnings("rawtypes")  
  61.     @Override  
  62.     public InputStream makeReportFromTemplet(String templetFileName, Map beans) {  
  63.         Configuration config = new Configuration();  
  64.         XLSTransformer transformer = new XLSTransformer(config);  
  65.         InputStream is = null;  
  66.         try {  
  67.             is = new FileInputStream(templetFileName);  
  68.             try {  
  69.                 workBook = transformer.transformXLS(is, beans);  
  70.             } catch (ParsePropertyException e) {  
  71.                 e.printStackTrace();  
  72.             } catch (InvalidFormatException e) {  
  73.                 e.printStackTrace();  
  74.             }     
  75.             // 产生POI输出流  
  76.             ByteArrayOutputStream os = new ByteArrayOutputStream();  
  77.             workBook.write(os);  
  78.             excelStream = new ByteArrayInputStream(os.toByteArray());  
  79.             is.close();  
  80.         } catch (IOException ie) {  
  81.             ie.printStackTrace();  
  82.         }  
  83.         return excelStream;  
  84.     }  
  85.   
  86.     @SuppressWarnings("rawtypes")  
  87.     @Override  
  88.     public void makeReportFromTemplet(String templetFileName, Map beans,  
  89.             String targetFileName) {  
  90.         Configuration config = new Configuration();  
  91.         XLSTransformer transformer = new XLSTransformer(config);  
  92.         try{  
  93.             try {  
  94.                 transformer.transformXLS(templetFileName, beans, targetFileName);  
  95.             } catch (ParsePropertyException e) {  
  96.                 e.printStackTrace();  
  97.             } catch (InvalidFormatException e) {  
  98.                 e.printStackTrace();  
  99.             }         
  100.         }catch(IOException ie){  
  101.             ie.printStackTrace();  
  102.         }  
  103.     }  
  104.   
  105.     public String getReportName() {  
  106.         return reportName;  
  107.     }  
  108.   
  109.     public void setReportName(String reportName) {  
  110.         this.reportName = reportName;  
  111.     }  
  112.   
  113.     public Workbook getWorkBook() {  
  114.         return workBook;  
  115.     }  
  116.   
  117.     public void setWorkBook(HSSFWorkbook workBook) {  
  118.         this.workBook = workBook;  
  119.     }  
  120.   
  121.     public Sheet getSheet() {  
  122.         return sheet;  
  123.     }  
  124.   
  125.     public void setSheet(HSSFSheet sheet) {  
  126.         this.sheet = sheet;  
  127.     }  
  128.   
  129.     public String getSheetName() {  
  130.         return sheetName;  
  131.     }  
  132.   
  133.     public void setSheetName(String sheetName) {  
  134.         this.sheetName = sheetName;  
  135.     }  
  136.       
  137.     public InputStream getExcelStream() {  
  138.         return excelStream;  
  139.     }  
  140.   
  141.     public void setExcelStream(InputStream excelStream) {  
  142.         this.excelStream = excelStream;  
  143.     }  
  144.   
  145. }  

        注意,这里需要说明添加的jar包(这是我加的jar包):poi-3.10-FINAL-20140208.jar,jxls-core-1.0.5.jar,poi-ooxml-3.10-FINAL-20140208.jar,commons-digester-2.1.jar,commons-jexl-2.1.1.jar;稍后打个包,可以去免费去下载,不用单独去下载,有的包必须翻墙才能下载。
        打包地址:点击这额

  •    最后,就差excel模板了
    在action中的exportExcel中,模板存放路径:工程/WEB-INF/excelTemplet/feedBackTemplet.xls,内容为:由于ubuntu系统,只能屏幕截图了:
           struts2导出数据到excel中方法(模板方法)
            
                        
       这个平铺的就是excel,这里面的布局,都是自己调整好的,和平常操作excel一样,想如何显示,就如何设计。
       其中以$开头的,就是上文beans传过来的值,还有下面jx:forEach循环,如果传过来的是对象的list,就可以在此循环打印出来。

      ok,想要说的就这些!
      一切准备好,就可以下载了。

    
     资料:
     1、commons-jexl
     2、http://jxls.sourceforge.net/reference/simplebeans.html

     
     
    附录:
   1、 action 代码:
    
[java] view plain copy
  1. import java.io.File;  
  2. import java.io.IOException;  
  3. import java.io.InputStream;  
  4. import java.io.UnsupportedEncodingException;  
  5. import java.text.SimpleDateFormat;  
  6. import java.util.Date;  
  7. import java.util.HashMap;  
  8. import java.util.List;  
  9. import java.util.Map;  
  10.   
  11. import javax.servlet.http.HttpServletRequest;  
  12.   
  13. import org.apache.struts2.ServletActionContext;  
  14. import org.springframework.beans.factory.annotation.Autowired;  
  15. import org.springframework.context.annotation.Scope;  
  16. import org.springframework.stereotype.Component;  
  17.   
  18. import com.opensymphony.xwork2.ActionSupport;  
  19. import com.wshouyou.bean.FeedBack;  
  20. import com.wshouyou.service.FeedBackService;  
  21. import com.wshouyou.util.ExcelReport;  
  22.   
  23. @Component("feedBackReportAction")  
  24. @Scope("prototype")  
  25. public class FeedBackReportAction extends ActionSupport {  
  26.   
  27.     private static final long serialVersionUID = 1L;  
  28.       
  29.     @Autowired  
  30.     private FeedBackService feedBackService;  
  31.       
  32.     private InputStream excelStream;  
  33.     private String fileName="";  
  34.     private String filePath=File.separator+"excelTemplet"+File.separator;  
  35.       
  36.     @SuppressWarnings({ "rawtypes""unchecked""deprecation" })  
  37.     public String exportExcel() throws IOException{  
  38.         HttpServletRequest request = ServletActionContext.getRequest();  
  39.   
  40.         List<FeedBack> listFeedBack = feedBackService.getAll();  
  41.         if ( listFeedBack == null )  
  42.             return ERROR;  
  43.           
  44.         Map beans = new HashMap();  
  45.         beans.put("feedback", listFeedBack);  
  46.         SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");  
  47.         // 填充报表  
  48.         filePath += "feedBackTemplet.xls";  
  49.         fileName = "用户反馈信息报表.xls";  
  50.           
  51.         beans.put("createDate", df.format(new Date()));  
  52.           
  53.         excelStream = new ExcelReport().makeReportFromTemplet(request  
  54.                 .getRealPath("/WEB-INF")  
  55.                 + filePath, beans);  
  56.           
  57.         if (excelStream == null) {  
  58.             return INPUT;  
  59.         }  
  60.         return "excel";  
  61.     }  
  62.   
  63.     public String getFileName() {  
  64.         try {  
  65.             fileName = new String(fileName.getBytes(), "ISO8859-1");  
  66.         } catch (UnsupportedEncodingException e) {  
  67.             e.printStackTrace();  
  68.         }  
  69.         return fileName;  
  70.     }  
  71.       
  72.     public void setFileName(String fileName) {  
  73.         this.fileName = fileName;  
  74.     }  
  75.   
  76.     public String getFilePath() {  
  77.         return filePath;  
  78.     }  
  79.   
  80.     public void setFilePath(String filePath) {  
  81.         this.filePath = filePath;  
  82.     }  
  83.   
  84.     public InputStream getExcelStream() {  
  85.         return excelStream;  
  86.     }  
  87.   
  88.     public void setExcelStream(InputStream excelStream) {  
  89.         this.excelStream = excelStream;  
  90.     }  
  91.       
  92. }  

相关文章:

  • 2021-12-15
  • 2021-11-30
  • 2022-12-23
  • 2022-12-23
  • 2021-11-07
  • 2021-11-19
猜你喜欢
  • 2021-11-19
  • 2021-12-16
  • 2022-03-05
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-12
相关资源
相似解决方案