Java Struts2 实现数据库数据导出Excel文件

13 篇文章 0 订阅

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值