Excelドキュメントの基本的な書式設定コマンドを実行するGroovyの例を探しています。また、これらのコマンドのリポジトリがどこにあるかも知りたいです。
どのようにしますか:
行を挿入する
セルを短い日付、時刻などにフォーマットします。
列または行全体を太字にする
これはどうですか(POI 3.9で)。
に入力 XLS ファイルがあると仮定すると/tmp/test.xls
、これにより、要求した変更が行われ、ワークブックが新しいファイルに書き出されます/tmp/test2.xls
。コメントを追加したので、うまくいけば意味があるはずです:-)
@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.*
// Open the spreadsheet
new File( '/tmp/test.xls' ).withInputStream { ins ->
new HSSFWorkbook( ins ).with { workbook ->
// Select the first sheet
getSheetAt( 0 ).with { sheet ->
// Insert a row at row 2 (zero indexed)
shiftRows( 1, sheet.lastRowNum, 1 )
// Add a value to this row in cell 1
getRow( 1 ).with { row ->
createCell( 0 ).with { cell ->
cell.setCellValue( '12:32' )
}
}
// Set the cell format to Time
// First we need to declare a style
def timeStyle = workbook.createCellStyle().with { style ->
dataFormat = HSSFDataFormat.getBuiltinFormat( 'h:mm:ss AM/PM' )
style
}
// Then apply it to our cell
getRow( 1 ).with { row ->
getCell( 0 ).with { cell ->
cell.cellStyle = timeStyle
}
}
// Make row 1 bold
// First declare a style
def boldStyle = workbook.createCellStyle().with { style ->
style.font = workbook.createFont().with { f ->
f.boldweight = HSSFFont.BOLDWEIGHT_BOLD
f
}
style
}
// Then apply it to the row (I can only get this to work doing
// it to each cell in turn, setting the rowStyle seems to do nothing
getRow( 0 ).with { row ->
(0..10).each {
getCell( it )?.cellStyle = boldStyle
}
}
}
// Write the modified workbook out to another xls file
new File( '/tmp/test2.xls' ).withOutputStream { os ->
write( os )
}
}
}