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