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;
	}

猜你喜欢

转载自my.oschina.net/u/2489258/blog/1789299
今日推荐