How do I open an existing excel file in Groovy so I can start manipulating it?
-
stackoverflow.com/questions/521274/…tim_yates– tim_yates2013-07-08 22:54:43 +00:00Commented Jul 8, 2013 at 22:54
-
That really doesn't show me how to open an existing file in Groovy. :/Marco Polo– Marco Polo2013-07-09 00:38:39 +00:00Commented Jul 9, 2013 at 0:38
-
1You can browse an example or get Apache POI to see all the examples in Java. It will be easy enough to convert them to Groovy.dmahapatro– dmahapatro2013-07-09 02:28:36 +00:00Commented Jul 9, 2013 at 2:28
-
Added a full example Groovy scripttim_yates– tim_yates2013-07-09 08:05:22 +00:00Commented Jul 9, 2013 at 8:05
Add a comment
|
1 Answer
Here's a full example of using POI from Groovy:
@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
// Make a workbook from scratch
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 )
}
}
}
// Open the spreadsheet, change cell 3, 3 to 'WOO' and save it back out to a new file
new File( '/tmp/test.xls' ).withInputStream { ins ->
new HSSFWorkbook( ins ).with { workbook ->
getSheetAt( 0 ).with { sheet ->
getRow( 2 ).getCell( 2 ).setCellValue( 'WOO' )
}
new File( '/tmp/test2.xls' ).withOutputStream { os ->
write( os )
}
}
}