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

标签 excel grails groovy export export-to-excel

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

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

最佳答案

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

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

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))
        }
    }
}

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

关于excel - Grails:如何将 Grails 列表导出到 Microsoft Excel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3773758/

相关文章:

java - Grails:如何使用 MongoDB 进行数据库迁移?

maven - 为什么 Maven 要下载 Groovy 的_所有_版本?

c# - 获取合并单元格的高度和宽度以放置图片。

xml - 导出到 Excel - 中间文件格式?

javascript - SheetJS xlsx-style需要excel中的单元格样式

c# - 如何获得使用范围内的整个列?

Hibernate 事务边界

grails - 用于grails的Spring Security Core插件-无法从数据库访问RequestMap参数

groovy - 在 groovy 中获取闭包的内容

mysql - 如何使用命令行中的连接参数在 groovy 中连接 mysql 数据库?