Struts2导出Excel(poi)步骤及问题汇总(二) 下载

该部分内容是在《Struts2导出Excel步骤及问题汇总(一)》的前提下完成的,该部分内容可以参考百度经验Struts2导出Excel步骤及问题汇总(一) poi分页  或者 本博客中 Struts2导出Excel步骤及问题汇总(一) poi分页

Action中处理,包含下载中文文件乱码、为空的问题。

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Date;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;

import com.monkey.base.action.BaseAction;
import com.monkey.service.ProductCardService;
import com.monkey.util.DateUtils;
import com.monkey.vo.ProductCard;
import com.opensymphony.xwork2.ModelDriven;

public class ProductCardAction2 extends BaseAction implements
ModelDriven<ProductCard> {

private static final long serialVersionUID = 6658682414884709427L;

@Autowired
private ProductCardService productCardService;

private ProductCard pc;

private String fileName; // 下载文件名称
private InputStream excelFile; // 下载文件流

public ProductCard getModel() {
if (null == pc)
pc = new ProductCard();
return pc;
}

public String download() throws Exception {
HSSFWorkbook workbook = xxx(); // 这个为调用service层返回的HSSFWorkbook对象
ByteArrayOutputStream output = new ByteArrayOutputStream();
workbook.write(output);
byte[] ba = output.toByteArray();
excelFile = new ByteArrayInputStream(ba);
output.flush();
output.close();
return "excel";
}

public String getDownloadFileName() {
return fileName;
}

public ProductCard getPc() {
return pc;
}

public void setPc(ProductCard pc) {
this.pc = pc;
}

/**
* 返回类型为"中文名字-20130612231234.xls"
*
* @return
*/
public String getFileName() throws Exception {
String tempName = "中文名字"
+ "-"
+ DateUtils.formatDate(DateUtils.LONG_DATE_PATTERN_PLAIN,
new Date()) + ".xls";

fileName = new String(tempName.getBytes(), "ISO8859-1");
System.out.println(fileName);
return fileName;
}

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

public InputStream getExcelFile() {
return excelFile;
}

public void setExcelFile(InputStream excelFile) {
this.excelFile = excelFile;
}

}


struts.xml下载项配置说明:

<!-- 下载导出excle -->
<result name="excel" type="stream">  
   <param name="contentType">application/vnd.ms-excel,charset=ISO8859-1</param>
   <param name="contentDisposition">attachment;filename="${fileName}"</param>  
   <param name="bufferSize">4096</param>
   <param name="inputName">excelFile</param>  
</result>

 

注意事项:

  1. 请注意文中加粗部分内容
  2. 中文解决办法汇总:

代码部分:

String tempName = "中文名字"+"-" 
               + DateUtils.formatDate(DateUtils.LONG_DATE_PATTERN_PLAIN, new Date())
               + ".xls";
       
fileName = new String(tempName.getBytes(), "ISO8859-1");

 

配置文件部分:

<param name="contentType">application/vnd.ms-excel,charset=ISO8859-1</param>

 

原文地址:Struts2导出Excel(poi)步骤及问题汇总(二) 下载

posted on 2014-07-01 17:31  寻找大牛  阅读(262)  评论(0)    收藏  举报