如何在Groovy中打开现有的Excel文件,以便我可以开始操作它?
答案 0 :(得分:2)
以下是使用Groovy中的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
// 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 )
}
}
}