Skip to content

Instantly share code, notes, and snippets.

@LCHCAPITALHUMAIN
Forked from timyates/excel.groovy
Created May 19, 2016 10:46
Show Gist options
  • Save LCHCAPITALHUMAIN/4b646f61e9b29e219c97e09c8fc40f72 to your computer and use it in GitHub Desktop.
Save LCHCAPITALHUMAIN/4b646f61e9b29e219c97e09c8fc40f72 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 )
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment