如何在 Groovy 中打开现有的 excel 文件以便开始操作它?
问问题
3222 次
1 回答
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 )
}
}
}
于 2013-07-09T08:05:08.410 回答