Grails:如何将 Grails 列表导出到 Microsoft Excel?

发布于 2024-09-25 00:27:10 字数 96 浏览 1 评论 0原文

我有一个包含信息的列表,我想将其导出到 Excel。 我该怎么做?

“导出插件”好用吗?我想我不久前看到过一个将文件导出到 Excel 的功能,但现在找不到了。

I have a list with information and I want to export it to Excel.
How do I do it?

Is the "Export Plugin" any good? I think I saw one a while ago to export files to Excel but I can't find it anymore.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

吲‖鸣 2024-10-02 00:27:10

如果您想要实际 Excel 文档(而不仅仅是 CSV 文件),我使用了 JExcel 库 取得了一些成功。这是一个快速编写的示例,可能需要一点 Groovy 化。

编辑:更新了我的示例以在控制器中执行此操作。从架构上来说,将其分开一点会更有意义,但这只是为了举例。

import jxl.*
import jxl.write.*

class SomeController {

    def report = {
        def file = createReport(MyDomain.list())

        response.setHeader('Content-disposition', 'attachment;filename=Report.xls')
        response.setHeader('Content-length', "${file.size()}")

        OutputStream out = new BufferedOutputStream(response.outputStream)

        try {
            out.write(file.bytes)

        } finally {
            out.close()
            return false
        }
    }

    private File createReport(def list) {
        WorkbookSettings workbookSettings = new WorkbookSettings()
        workbookSettings.locale = Locale.default

        def file = File.createTempFile('myExcelDocument', '.xls')
        file.deleteOnExit()

        WritableWorkbook workbook = Workbook.createWorkbook(file, workbookSettings)

        WritableFont font = new WritableFont(WritableFont.ARIAL, 12)
        WritableCellFormat format = new WritableCellFormat(font)

        def row = 0
        WritableSheet sheet = workbook.createSheet('MySheet', 0)

        list.each {
            // if list contains objects with 'foo' and 'bar' properties, this will
            // output one row per list item, with column A containing foo and column
            // B containing bar
            sheet.addCell(new Label(0, row, it.foo, format))
            sheet.addCell(new Label(1, row++, it.bar, format))
        }
    }
}

使用此库可以让您执行格式化、使用多个工作表等操作。

If you want actual Excel documents (rather than just CSV files), I've used the JExcel library with some success. Here's a quickly-written example that could probably be Groovy-fied a little bit.

Edit: Updated my example to do this in a controller. Architecturally it would make more sense to split this up a bit, but this is just for example's sake.

import jxl.*
import jxl.write.*

class SomeController {

    def report = {
        def file = createReport(MyDomain.list())

        response.setHeader('Content-disposition', 'attachment;filename=Report.xls')
        response.setHeader('Content-length', "${file.size()}")

        OutputStream out = new BufferedOutputStream(response.outputStream)

        try {
            out.write(file.bytes)

        } finally {
            out.close()
            return false
        }
    }

    private File createReport(def list) {
        WorkbookSettings workbookSettings = new WorkbookSettings()
        workbookSettings.locale = Locale.default

        def file = File.createTempFile('myExcelDocument', '.xls')
        file.deleteOnExit()

        WritableWorkbook workbook = Workbook.createWorkbook(file, workbookSettings)

        WritableFont font = new WritableFont(WritableFont.ARIAL, 12)
        WritableCellFormat format = new WritableCellFormat(font)

        def row = 0
        WritableSheet sheet = workbook.createSheet('MySheet', 0)

        list.each {
            // if list contains objects with 'foo' and 'bar' properties, this will
            // output one row per list item, with column A containing foo and column
            // B containing bar
            sheet.addCell(new Label(0, row, it.foo, format))
            sheet.addCell(new Label(1, row++, it.bar, format))
        }
    }
}

Using this library lets you do things like formatting, using multiple worksheets, etc.

少女净妖师 2024-10-02 00:27:10

Grails 导出插件 的功能非常出色:将域对象(或查询结果)列表导出到单个工作表(或页面),采用多种格式 - 包括 Excel。命名列、指示宽度、动态转换数据的能力非常棒——我已经在几个项目中使用过它。

if( params.format && params.format != "html"){
    response.contentType = grailsApplication.config.grails.mime.types[params.format]
    response.setHeader("Content-disposition", "attachment; filename=Docs_${new Date().format('yyyy-MM-dd')}.${params.extension}")

    List fields = ["documentNo", "modifiedBy", "modifiedDate"]
    Map labels = ["documentNo": 'Document No', "modifiedBy":'Modified by', "modifiedDate":'Last modified']

    def fullDocId = { domain, value ->
        return domain.fullDocId()
    }
    def formatDate = { domain, value ->
        return value.format('yyyy-MM-dd HH-mm')
    }

    Map formatters = [documentNo:fullDocId, modifiedDate:formatDate]
    Map parameters = [title: "${query}", "column.widths": [20, 15, 15]]

    exportService.export(params.format, response.outputStream, Document.list(), fields, labels, formatters, parameters)
}

然而,当我想要除简单列表之外的其他内容时,我也按照 Rob 的建议使用了 JExcel。适合工作的工具等等。 :-)

The Grails Export Plugin is excellent at what it does: export a list of domain objects (or query results) onto a single sheet (or page), in a number of formats -- including Excel. The ability to name columns, indicate width, transform your data on-the-fly is great -- I've used it in several projects.

if( params.format && params.format != "html"){
    response.contentType = grailsApplication.config.grails.mime.types[params.format]
    response.setHeader("Content-disposition", "attachment; filename=Docs_${new Date().format('yyyy-MM-dd')}.${params.extension}")

    List fields = ["documentNo", "modifiedBy", "modifiedDate"]
    Map labels = ["documentNo": 'Document No', "modifiedBy":'Modified by', "modifiedDate":'Last modified']

    def fullDocId = { domain, value ->
        return domain.fullDocId()
    }
    def formatDate = { domain, value ->
        return value.format('yyyy-MM-dd HH-mm')
    }

    Map formatters = [documentNo:fullDocId, modifiedDate:formatDate]
    Map parameters = [title: "${query}", "column.widths": [20, 15, 15]]

    exportService.export(params.format, response.outputStream, Document.list(), fields, labels, formatters, parameters)
}

However, I've also used JExcel as suggested by Rob, when I wanted something other than a simple list. The right tool for the job, and all that. :-)

江城子 2024-10-02 00:27:10

我已经使用 Grails 的 JXL 插件有一段时间了,它运行得很好。

它甚至可以选择将 Excel 文件写入响应,以便用户可以使用我的 REST 服务直接下载文件。

链接是: http://grails.org/plugin/jxl

下面是一个示例,说明它是多么简单是创建工作簿:

new ExcelBuilder().workbook('/path/to/test.xls') {
    sheet('SheetName') {
        cell(0,0,'DEF')
    }
}

您可以在此处找到更多信息。

I've been using the JXL plugin for Grails for a while and it works perfectly.

It even has an option to write the Excel file to the response, so that the user can directly download the file using my REST service.

The link is: http://grails.org/plugin/jxl

Here is an example of how simple it is to create workbooks:

new ExcelBuilder().workbook('/path/to/test.xls') {
    sheet('SheetName') {
        cell(0,0,'DEF')
    }
}

You can find more information here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文