读取Groovy中Excel文件的最简单方法?

问题描述

| 是否有可用于读取Groovy中Excel文件的打包程序/实用程序。我正在寻找类似于Groovy sql的row函数的东西,如下面的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)\")
  }

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

    where:
    [a,b,c] << sql.rows(\"select a,c from maxdata\")
  }
} 
    

解决方法

        我的GUG成员之一已经创建了一种使用Apache POI来使用Excel的工具,其描述方式与您描述的几乎相同。它尚未正式形式化为库(AFAIK),但可以在他的博客上找到。 它允许您编写如下代码:
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     ,        POI是您http://poi.apache.org/之后的内容,它是Java Lib,因此您可以从Groovy使用它。不确定是否在任何地方都有Groovy包装器     ,        我也建议使用Groovy Spreadsheet Builder。它可以在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文件!