Skip to content

Instantly share code, notes, and snippets.

@timyates
Last active June 13, 2017 18:43
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save timyates/5583967 to your computer and use it in GitHub Desktop.
Save timyates/5583967 to your computer and use it in GitHub Desktop.
Create a styled Excel spreadsheet with Groovy and Apache POI
@Grab( 'org.apache.poi:poi:3.9' )
import static org.apache.poi.ss.usermodel.CellStyle.*
import static org.apache.poi.ss.usermodel.IndexedColors.*
import org.apache.poi.hssf.usermodel.HSSFWorkbook
new HSSFWorkbook().with { workbook ->
def styles = [ LIGHT_BLUE, LIGHT_GREEN, LIGHT_ORANGE ].collect { color ->
createCellStyle().with { style ->
fillForegroundColor = color.index
fillPattern = SOLID_FOREGROUND
style
}
}
createSheet( 'Output' ).with { sheet ->
(0..4).each { rownum ->
createRow( rownum ).with { row ->
(0..4).each { colnum ->
createCell( colnum ).with { cell ->
setCellValue( "[$colnum,$rownum]" )
cellStyle = styles[ ( ( rownum * 5 ) + colnum ) % styles.size() ]
}
}
}
}
new File( '/tmp/test.xls' ).withOutputStream { os ->
write( os )
}
}
}
@jameskleeh
Copy link

Check out my new dsl for building excel documents http://github.com/jameskleeh/groovy-excel-builder

@sinaisix
Copy link

Thanks @jameskleeh, that looks very awesome. Testing it out in my Java EE app now.

@daniilshevelev
Copy link

@jameskleeh thanks for writing it and sharing the note here! I am looking to use it right now.

@daniilshevelev
Copy link

@jameskleeh I am having difficulties using your library. Please check out my question: https://stackoverflow.com/questions/44166979/idea-maven-not-resolving-apache-poi-classes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment