在Groovy中读取Excel文件最简单的方法是什么?

11
有没有可用的包或工具可以在Groovy中读取Excel文件。我正在寻找类似于Groovy SQL的rows函数的东西,就像下面的spock测试示例中所示。我的意图是在Spock测试框架中使用它进行使用Excel进行数据驱动的测试。[链接]
import groovy.sql.Sql

import spock.lang.*

class DatabaseDriven extends Specification {
  @Shared sql = Sql.newInstance("jdbc:h2:mem:", "org.h2.Driver")

  // normally an external database would be used,
  // and the test data wouldn't have to be inserted here
  def setupSpec() {
    sql.execute("create table maxdata (id int primary key, a int, b int, c int)")
    sql.execute("insert into maxdata values (1, 3, 7, 7), (2, 5, 4, 5), (3, 9, 9, 9)")
  }

  def "maximum of two numbers"() {
    expect:
    Math.max(a, b) == c

    where:
    [a, b, c] << sql.rows("select a, b, c from maxdata")
  }
} 
4个回答

15

我的一个GUG组成员使用Apache POI创建了一个处理Excel的工具,与你描述的方式非常相似。目前还没有正式制作成库(据我所知),但可以在他的博客上找到。

它让你可以写出这样的代码:

new ExcelBuilder("customers.xls").eachLine([labels:true]) {
  new Person(name:"$firstname $lastname",
    address:address, telephone:phone).save()
}

可以在这里查看:http://www.technipelago.se/content/technipelago/blog/44


1
为了让人们的使用更加方便,我将Goran的代码转换成了一个Github仓库。我还修改了它,使用Grab来处理依赖项,使用xlsx文件,并只返回每个单元格的字符串。对于我需要做的事情,使用单元格类型会给我带来麻烦。https://github.com/dtanner/groovy-excel-reader - Dan Tanner

6

您需要的是POI http://poi.apache.org/,它是一个Java Lib,因此您可以从Groovy中使用它。不确定是否有任何Groovy封装器可用。


1
@Grab('org.apache.poi:poi:3.8')
@Grab('org.apache.poi:poi-ooxml:3.8')
@GrabExclude('xml-apis:xml-apis')
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.*;
import org.apache.poi.ss.usermodel.*;
def excelFile = new File('F:/test.xlsx')


excelFile.withInputStream { is ->
    workbook = new XSSFWorkbook(is)
    (0..<workbook.numberOfSheets).each { sheetNumber ->
        XSSFSheet sheet = workbook.getSheetAt( sheetNumber )
        sheet.rowIterator().each { row ->
            row.cellIterator().each { cell ->
                println cell.toString()
            }
        }
    }
}

0

我还可以推荐使用Groovy电子表格生成器。它可以在Maven仓库中获取(与ExcelBuilder相反),并且还具有富有表现力的Groovy语法:

SpreadsheetQuery query = PoiSpreadsheetCriteria.FACTORY.forFile(file)                      // <1>

Collection  cells = query.query {
    sheet {                                                                            
        row {                                                                           
            cell {
                value 'B'
            }
        }
    }
}

assert cells.size() == 1
assert cells.first().value == 'B'

或者:

Collection rows = query.query {
    sheet(name({ name.startsWith('Con') })) {
        row(1)
    }
}.rows

文档包含许多示例。它甚至可以以相同的方式编写Excel文件!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接