struts2导出数据到excel中方法(模板方法)

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

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

  • 前端jsp页面,加个点击的按钮或者超链接;

    <a href="feedBackReportAction_exportExcel.action">导出</a>
  • struts.xml中加个action:
              <action name="feedBackReportAction_exportExcel" class="feedBackReportAction" method="exportExcel">
			<result name="excel" type="stream">
				<param name="contentType">
					application/vnd.ms-excel
				</param>
				<param name="inputName">excelStream</param>
				<param name="contentDisposition">
					attachment;filename="${fileName}"
				</param>
				<param name="bufferSize">1024</param>
			</result>
			<result name="input" type="redirect">feedBackWebAction_queryAll.action</result>
		</action>

从action可以看出,result中 name为excel的类型为stream,并且有几个参数,对于自己的项目,其他的不需要动,只是需要注意"${fileName}",这个是后面action中定义的一个String名称,作为下载时显示的xls的文件名。当然名称为input的result跳转的地址需要自己定义的。

  • action只是很简单的类:

    其中的exportExcel方法如下:

    public String exportExcel() throws IOException{
    		HttpServletRequest request = ServletActionContext.getRequest();
    
    		List<FeedBack> listFeedBack = feedBackService.getAll();
    		if ( listFeedBack == null )
    			return ERROR;
    
    		Map beans = new HashMap();
    		beans.put("feedback", listFeedBack);
    		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    		// 填充报表
    		filePath += "feedBackTemplet.xls";
    		fileName = "用户反馈信息报表.xls";
    
    		beans.put("createDate", df.format(new Date()));
    
    		excelStream = new ExcelReport().makeReportFromTemplet(request
    				.getRealPath("/WEB-INF")
    				+ filePath, beans);
    
    		if (excelStream == null) {
    			return INPUT;
    		}
    		return "excel";
    	}

    很简单吧,我需要显示的bean就是数据库中的表,不需要作其他的操作,如果有需要,自己填充到Map中,上文提到的fileName也在这赋值了。其中

    excelStream = new ExcelReport().makeReportFromTemplet(request
    				.getRealPath("/WEB-INF")
    				+ filePath, beans);

    这句是核心,把beans的内容,写到excel模板中。用的类----ExcelReport。就是所谓的poi。这个类的代码,会贴到此文章的最后。

  • poi帮助类   (直接贴代码)

Report.java接口

import java.io.InputStream;
import java.util.Collection;
import java.util.Map;

public interface Report {
	@SuppressWarnings("rawtypes")
	public void makeReport(Collection collection, String filePath);

	public void makeReport(String[] dataStr, String filePath);

	@SuppressWarnings("rawtypes")
	public void makeReport(Collection collection, String[] collumHead, String filePath);
	/**
	 * 按模板生成报表,使用jxls设置报表模板,用于通过浏览器下载报表
	 * @param templetFileName 模板文件绝对路径+模板文件名
	 * @param beans 模板参数对象集合
	 * @return InputStream
	 */
	@SuppressWarnings("rawtypes")
	public InputStream makeReportFromTemplet(String templetFileName, Map beans);
	/**
	 * 按模板生成报表,使用jxls设置报表模板,直接生成本地文件
	 * @param templetFileName
	 * @param beans
	 * @param targetFileName
	 */
	@SuppressWarnings("rawtypes")
	public void makeReportFromTemplet(String templetFileName, Map beans, String targetFileName);

}

继承类,即action调用的类

ExcelReport.java

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Map;

import net.sf.jxls.exception.ParsePropertyException;
import net.sf.jxls.transformer.Configuration;
import net.sf.jxls.transformer.XLSTransformer;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
/**
 * Excel报表类
 *
 */
public class ExcelReport implements Report {
	public static final String POSTIFIX = ".xls";

	protected String reportName;
	protected Workbook workBook = new HSSFWorkbook();
	protected Sheet sheet;
	protected String sheetName;
	protected InputStream excelStream;

	public ExcelReport(String reportName, String sheetName) {
		super();
		this.reportName = reportName;
		this.sheetName = sheetName;
		sheet = workBook.createSheet(sheetName);
	}

	public ExcelReport() {
		super();
	}

	@SuppressWarnings({ "rawtypes" })
	@Override
	public void makeReport(Collection collection, String filePath) {

	}

	@Override
	public void makeReport(String[] dataStr, String filePath) {

	}

	@SuppressWarnings("rawtypes")
	@Override
	public void makeReport(Collection collection, String[] collumHead,
			String filePath) {

	}

	@SuppressWarnings("rawtypes")
	@Override
	public InputStream makeReportFromTemplet(String templetFileName, Map beans) {
		Configuration config = new Configuration();
		XLSTransformer transformer = new XLSTransformer(config);
		InputStream is = null;
		try {
			is = new FileInputStream(templetFileName);
			try {
				workBook = transformer.transformXLS(is, beans);
			} catch (ParsePropertyException e) {
				e.printStackTrace();
			} catch (InvalidFormatException e) {
				e.printStackTrace();
			}
			// 产生POI输出流
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			workBook.write(os);
			excelStream = new ByteArrayInputStream(os.toByteArray());
			is.close();
		} catch (IOException ie) {
			ie.printStackTrace();
		}
		return excelStream;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public void makeReportFromTemplet(String templetFileName, Map beans,
			String targetFileName) {
		Configuration config = new Configuration();
		XLSTransformer transformer = new XLSTransformer(config);
		try{
			try {
				transformer.transformXLS(templetFileName, beans, targetFileName);
			} catch (ParsePropertyException e) {
				e.printStackTrace();
			} catch (InvalidFormatException e) {
				e.printStackTrace();
			}
		}catch(IOException ie){
			ie.printStackTrace();
		}
	}

	public String getReportName() {
		return reportName;
	}

	public void setReportName(String reportName) {
		this.reportName = reportName;
	}

	public Workbook getWorkBook() {
		return workBook;
	}

	public void setWorkBook(HSSFWorkbook workBook) {
		this.workBook = workBook;
	}

	public Sheet getSheet() {
		return sheet;
	}

	public void setSheet(HSSFSheet sheet) {
		this.sheet = sheet;
	}

	public String getSheetName() {
		return sheetName;
	}

	public void setSheetName(String sheetName) {
		this.sheetName = sheetName;
	}

	public InputStream getExcelStream() {
		return excelStream;
	}

	public void setExcelStream(InputStream excelStream) {
		this.excelStream = excelStream;
	}

}

注意,这里需要说明添加的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系统,只能屏幕截图了:

这个平铺的就是excel,这里面的布局,都是自己调整好的,和平常操作excel一样,想如何显示,就如何设计。

其中以$开头的,就是上文beans传过来的值,还有下面jx:forEach循环,如果传过来的是对象的list,就可以在此循环打印出来。

ok,想要说的就这些!

一切准备好,就可以下载了。

资料:

1、commons-jexl

2、http://jxls.sourceforge.net/reference/simplebeans.html

附录:

1、 action 代码:

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionSupport;
import com.wshouyou.bean.FeedBack;
import com.wshouyou.service.FeedBackService;
import com.wshouyou.util.ExcelReport;

@Component("feedBackReportAction")
@Scope("prototype")
public class FeedBackReportAction extends ActionSupport {

	private static final long serialVersionUID = 1L;

	@Autowired
	private FeedBackService feedBackService;

	private InputStream excelStream;
	private String fileName="";
	private String filePath=File.separator+"excelTemplet"+File.separator;

	@SuppressWarnings({ "rawtypes", "unchecked", "deprecation" })
	public String exportExcel() throws IOException{
		HttpServletRequest request = ServletActionContext.getRequest();

		List<FeedBack> listFeedBack = feedBackService.getAll();
		if ( listFeedBack == null )
			return ERROR;

		Map beans = new HashMap();
		beans.put("feedback", listFeedBack);
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		// 填充报表
		filePath += "feedBackTemplet.xls";
		fileName = "用户反馈信息报表.xls";

		beans.put("createDate", df.format(new Date()));

		excelStream = new ExcelReport().makeReportFromTemplet(request
				.getRealPath("/WEB-INF")
				+ filePath, beans);

		if (excelStream == null) {
			return INPUT;
		}
		return "excel";
	}

	public String getFileName() {
		try {
			fileName = new String(fileName.getBytes(), "ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getFilePath() {
		return filePath;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	public InputStream getExcelStream() {
		return excelStream;
	}

	public void setExcelStream(InputStream excelStream) {
		this.excelStream = excelStream;
	}

}
时间: 2024-07-31 02:00:46

struts2导出数据到excel中方法(模板方法)的相关文章

MVC导出数据到EXCEL新方法:将视图或分部视图转换为HTML后再直接返回FileResult

MVC导出数据到EXCEL新方法:将视图或分部视图转换为HTML后再直接返回FileResult 导出EXCEL方法总结:MVC导出数据到EXCEL的方法有很多种,常见的是: 1.采用EXCEL COM组件来动态生成XLS文件并保存到服务器上,然后转到该文件存放路径即可:优点:可设置丰富的EXCEL格式,缺点:需要依赖EXCEL组件,且EXCEL进程在服务器中无法及时关闭,以及服务器上会存留大量的不必要的XLS文件: 2.设置输出头为:application/ms-excel,再输出拼接的HTM

pl/sql developer导出数据到excel的方法

http://yedward.net/?id=92 问题说明:使用pl/sql developer导出数据到excel表格中是非常有必要的,一般的可能直接在导出的时候选择csv格式即可,因为该格式可以直接用excel打开.但是,在导出的时候出现了这样的问题,导出成csv格式的时候出现了数据乱码,而导出为xml或者html的时候却不会出现问题. 图1:pl/sql developer导出为csv出现乱码 问题解析:出现上面的问题,可能是字符集的设置问题.我找到了一些其他的数据导出方法,下面一一列出

c# winform DataGridView导出数据到Excel中,可以导出当前页和全部数据

准备工作就是可以分页的DataGridView,和两个按钮,一个用来导出当前页数据到Excel,一个用来导出全部数据到Excel 没有使用SaveFileDialog,但却可以弹出保存对话框来 先做导出当前页数据到Excel的 DataGridView命名为dataGridView1 1 //按下导出按钮 2 private void button7_Click(object sender, EventArgs e) 3 { 4 print(dataGridView1); 5 } 6 publi

C#不用COM组件导出数据到Excel中

<?xml version='1.0'?><?mso-application progid='Excel.Sheet'?><Workbook xmlns='urn:schemas-microsoft-com:office:spreadsheet' xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns:ss='urn:sch

PHP导出数据到excel的方法

很简单,看内容,不多说了: <?php //设置标题 $header[] = "ID"; $header[] = "订单"; $header[] = "模式"; $header[] = "账号"; $header[] = "角色ID"; $header[] = "角色名"; $header[] = "元宝"; $header[] = "金额"

从DataTable高效率导出数据到Excel

首先从数据库读取数据到DataTable,这我就不提了,大家都明白.下面直接介绍如何从DataTable高效率导出数据到Excel中的方法,代码如下: 1 using Microsoft.Office.Interop.Excel; 2 using System.Runtime.InteropServices; 3 4 [DllImport("User32.dll", CharSet = CharSet.Auto)] 5 public static extern int GetWindo

ASP.NET导出数据到Excel 实例介绍

ASP.NET导出数据到Excel  该方法只是把asp.net页面保存成html页面只是把后缀改为xlc不过excel可以读取,接下连我看看还有别的方式能导出数据,并利用模版生成. 下面是代码 新建一个asp.ne的tweb应用程序把代码粘贴进去就好了 html页面代码 <%@ Page language="c#" Codebehind="OutExcel.aspx.cs" AutoEventWireup="false" Inherits

Delphi 导出数据至Excel的7种方法【转】

转自:http://blog.csdn.net/zang141588761/article/details/52275948 一; delphi 快速导出excel uses ComObj,clipbrd; function ToExcel(sfilename:string; ADOQuery:TADOQuery):boolean; const xlNormal=-4143; var y : integer; tsList : TStringList; s,filename :string; a

导出数据到Excel方法总结

导出数据到Excel方法总结 一,问题的提出 近来在网上经常有人问怎样把数据导出到Excel中?针对这个问题网上也有很多资料.大都比较的琐碎.本人当前从事的项目中,刚好涉及到这些内容.就顺便做了一些归纳整理.共享给大家.避免大家再花费很多时间研究这个老生长谈的问题. 二,解决方法 1.       用NPOI导出数据到Excel. 简介:NPOI是一个开源的dotnet类库,官方网站:http://npoi.codeplex.com/. 优点:支持Excel 2003格式,读写速度快,基于.NE