struts2使用easypoi导出excel

1.maven依赖

    		 <dependency>
			<groupId>cn.afterturn</groupId>
			<artifactId>easypoi-base</artifactId>
			<version>3.0.1</version>
		</dependency>
		<dependency>
			<groupId>cn.afterturn</groupId>
			<artifactId>easypoi-annotation</artifactId>
			<version>3.0.1</version>
		</dependency>

2.struts2配置文件

		<action name="*_*" method="{2}" class="com.wzxy.nc.controller.{1}Controller">
			<result name="download" type="stream">
				<!-- 指定下载文件的类型 -->
				<param name="contentType">application/octet-stream</param>
				<!-- 指定下载文件的位置 -->
				<param name="inputName">fileInputStream</param>
				<param name="contentDisposition">attachement;filename=${downFileName}</param>
				<!-- 指定下载文件的缓冲大小 -->
				<param name="bufferSize">4096</param>
			</result> 
		</action>

3.User实体

@ExcelTarget("user")
public class User implements Serializable{
	
	/**  */
	private static final long serialVersionUID = -2527197546929818981L;

	/** 主键  */
	private Integer id;
	
	/** 用户名 */
	@Excel(name = "用户名", width=25, orderNum = "1", needMerge = true)
	private String username;
	
	/** 密码 */
	@Excel(name = "密码", orderNum = "2", needMerge = true)
	private String password;
	
       @Excel(name = "性别",orderNum = "3", replace = { "男_1", "女_2" }, needMerge = true)
	private Integer sex = 1;

        // 省略get、set方法
}

4.UserController

	// 下载的excel文件名
	protected String downFileName;
	// 下载的excel输入流
	protected InputStream fileInputStream;
        protected final String DOWNLOAD = "download";

	public String getDownFileName() {
		return downFileName;
	}

	public void setDownFileName(String downFileName) {
		this.downFileName = downFileName;
	}

	public InputStream getFileInputStream() {
		return fileInputStream;
	}

	public void setFileInputStream(InputStream fileInputStream) {
		this.fileInputStream = fileInputStream;
	}

	public String download(){
		try {
			List<User> list = userService.findAll();
			Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(
					"用户数据","用户数据"), User.class, list);
			// 将文件存到流中
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			workbook.write(os);
			byte[] fileContent = os.toByteArray();
			ByteArrayInputStream is = new ByteArrayInputStream(fileContent);
			// 文件流
			super.fileInputStream = is; 
			// 设置下载的文件名,解决无法显示中文名字的问题
			super.downFileName = new String("用户数据.xls".getBytes("gb2312"), "iso8859-1");
		} catch (IOException e) {
			e.printStackTrace();
		}	
		return DOWNLOAD;
	}

转载于:https://my.oschina.net/u/2489258/blog/1789299

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值