HTML:
<form action="userAction!exportExcel">
<input type="submit">导出</input>
</form>
Struts.xml
<package name="" namespace="/" extends="json-default">
<action name="userAction" class="com.truth99.action.UserAction">
<result name="excel" type="stream">
<param name="encode">true</param>
<param name="contentType">application/vnd.ms-excel;charset=GBK</param>
<param name="inputName">excelStream</param>
<param name="contentDisposition">attachment;filename=${fileName}</param>
<param name="bufferSize">20480</param>
</result>
</action>
</package>
<param name="encode">true</param> 允许编码
<param name="contentType">application/vnd.ms-excel;charset=GBK</param> 内容类型:就是excel,后面的charset是编码格式
<param name="inputName">excelStream</param> 输入流的名字定义,随便定义
<param name="contentDisposition">attachment;filename=${fileName}</param>输出时的文件名
UserAction:
public class UserAction{
private InputStream excelStream;
private String fileName = "golf.xls";//导出excel
public String exportExcel(){
try{
StringBuffer sb = new StringBuffer();
//\t表示下一列,\n表示下一行
sb.append("title1").append("\t").append("title2").append("\n");
//导入的数据进行迭代,拼成字符串
for(;;){
sb.append("content1").append("\t").append("content2").append("\n");
}
//将字符串放入流中
excelStream = new ByteArrayInputStream(sb.toString().getBytes("GBK"),
0,
sb.toString().getBytes("GBK").length);
}catch(Exception e){
}
return "excel";
}
public InputStream getExcelStream() {
return excelStream;
}
public void setExcelStream(InputStream excelStream) {
this.excelStream = excelStream;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
}
或者设置文件名fileName, 文件名fileName 对应 getFileName() 首字母小写
public String getFileName() {
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd ");
String fileName = (sf.format(new Date()).toString())+ "项目信息.xls";
try {
fileName = new String(downloadFileName.getBytes(),"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return fileName;
}
public void setFileName(String fileName){
this.fileName = fileName;
}
http://www.rjpx.cn/show.asp?id=276