struts导出excel并下载

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.bskcare.ch.base.action.BaseAction;
import com.bskcare.ch.service.ProductCardService;
import com.bskcare.ch.util.DateUtils;
import com.bskcare.ch.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;
}

}




2


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>


END



注意事项


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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值