在Grails中将查询的数据库导出到excel的csv文件

刚好工作中用到此功能,网上找了一下,有很多例子,但在我这都试验不成功,可能是我的RP问题。只好慢慢摸索,将人家的例子改成以下的样子,终于通过了:

首先在包(package)的开头增加输入语句:
import org.codehaus.groovy.grails.commons.ConfigurationHolder
不然后面response.setHeader等子程序将无法解析。其余的代码如下:

        response.setHeader("Content-disposition", "attachment; filename=bxmx-list.csv")
        response.contentType = "application/vnd.ms-excel"   //在这里设置charset多余,csv文件永远都只是ansi格式。

        render(text:"序号,姓名,日期,其他字段等\r\n",encoding:"GB2312") //这里encoding是关键,不然excel打开乱码,
                     // 奇怪的是,记事本打开永远都不乱码。

        def outp=Bxmx.findAll()  //这里可以查找数据,你可以用findAllBy等其他手段

        outp.each{
            render(text:it.xuhao+',')    //序号是数字,无需转码
            render(text:it.name+',',encoding:"GB2312") //姓名是由中文字符的,需要转码
            render(text:it.date.format('yyyy-MM-dd')+',') //日期无需转码
            ....... 
            render(text:'\r\n')
        }
        return false

题外话,这个日期格式的转换,我起初在Grails的文档找不到资料,后来才想起在Groovy的网站上找,找到文档后试验时又不小心用了'yy-mm-dd',怎么结果是乱的?可见我是完全不懂java,原来中间那个mm必须是大写。

posted on 2011-04-23 11:06 家1阳 阅读(1307) 评论(4)  编辑 收藏 引用

评论

# BION I'm imprsesed! Cool post![未登录] 2011-05-23 06:45 Vicky

BION I'm imprsesed! Cool post!  回复  更多评论   

# re: 在Grails中将查询的数据库导出到excel的csv文件 2011-07-17 11:21 uggs

together the way, fell out from the excellent old tree leaves appered in official <A href="http://www.cheapghdpurpleuk.com/"><STRONG>ghd mini</STRONG></A> remain alone, while using sunset at the property of sunset  回复  更多评论   

# re: 在Grails中将查询的数据库导出到excel的csv文件 2011-07-17 11:22 ghds

ghds  回复  更多评论   

只有注册用户登录后才能发表评论。

导航

<2011年7月>
262728293012
3456789
10111213141516
17181920212223
24252627282930
31123456

统计

常用链接

留言簿(2)

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜