下面是一个将 Styles 与 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.ss.usermodel.IndexedColors
import org.apache.poi.hssf.usermodel.HSSFWorkbook
new HSSFWorkbook().with { workbook ->
// Create a RED font and a BLACK font
def fonts = [ 'RED', 'BLACK' ].collectEntries { color ->
[ color, createFont().with { font ->
font.color = IndexedColors."$color".index
font
} ]
}
def styles = [ LIGHT_BLUE, LIGHT_GREEN, LIGHT_ORANGE ].collect { color ->
createCellStyle().with { style ->
fillForegroundColor = color.index
fillPattern = SOLID_FOREGROUND
// Set the font for this style
if( color == LIGHT_GREEN ) {
font = fonts.RED
}
else {
font = fonts.BLACK
}
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 )
}
}
}
一个可能更容易理解的例子是:
@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.ss.usermodel.IndexedColors
import org.apache.poi.hssf.usermodel.HSSFWorkbook
new HSSFWorkbook().with { workbook ->
// Helper closure to create a font
def fontMaker = { color ->
createFont().with { font ->
font.color = color.index
font
}
}
// Helper closure to create a style
def styleMaker = { fg, font ->
createCellStyle().with { style ->
fillForegroundColor = fg.index
fillPattern = SOLID_FOREGROUND
style.font = font
style
}
}
// Make 2 fonts, one for ERROR, one for OK
def fonts = [ ERROR : fontMaker( WHITE ),
OK : fontMaker( BLACK ) ]
// Make 2 styles, one for ERROR cells, one for OK
def styles = [ ERROR: styleMaker( DARK_RED, fonts.ERROR ),
OK : styleMaker( WHITE, fonts.OK ) ]
createSheet( 'Output' ).with { sheet ->
(0..4).each { rownum ->
createRow( rownum ).with { row ->
(0..4).each { colnum ->
createCell( colnum ).with { cell ->
setCellValue( "[$colnum,$rownum]" )
// Some logic
if( colnum == 2 && rownum == 2 ) {
// Mark cell with ERROR style
cellStyle = styles.ERROR
}
else {
cellStyle = styles.OK
}
}
}
}
}
new File( '/tmp/test.xls' ).withOutputStream { os ->
write( os )
}
}
}