Java Struts2 实现导出Excel文件


现在开始

<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>输出时的文件名

package com.truth99.action; 
 
import java.io.ByteArrayInputStream; 
import java.io.InputStream; 
 
public class UserAction{ 
 
private InputStream excelStream; 
private String fileName = "golf.xls";//导出excel 
 
public String exportExcel(){ 
        try{ 
            StringBuffer sb = new StringBuffer(); 
            sb.append("title1").append("\t").append("title2").append("\n");
//\t表示下一列,\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; 
    } 
} 


这样就完事儿了,挺简单的。

你可能感兴趣的:(java,html,struts,Excel)