Easiest way to read Excel files in groovy?

我们两清 提交于 2019-12-21 04:06:58

问题


Are there any warappers/utils available to read Excel files in Groovy. I am looking for something similar to Groovy SQL's rows function as shown in below spock test example. My intention is to use this for data driven testing using excel in Spock test framework

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

回答1:


One of my fellow GUG members has created a tool for working with Excel using Apache POI in very much the same way you describe. It's not formalized into a library yet (AFAIK) but is available on his blog.

It allows you to write code like this:

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

Check it out here: http://www.technipelago.se/content/technipelago/blog/44




回答2:


POI is what your after http://poi.apache.org/ its a Java Lib so you can use it from Groovy. Not sure if there are Groovy wrappers for it anywhere




回答3:


I could also recommend use Groovy Spreadsheet Builder. It available in maven repository (contrary to ExcelBuilder) and also have expressive Groovy-syntax:

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'

Or:

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

Documentation contains many examples. It even may write Excel files in same way!



来源:https://stackoverflow.com/questions/6157114/easiest-way-to-read-excel-files-in-groovy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!