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>
分享到:
评论