Guest User

Untitled

a guest
Jun 24th, 2018
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. // g100pon *9 Jakarta POI のGroovyサンプル
  2. //
  3. // usage: groovy sampleOfPOI.groovy <入力Excelファイル> <出力Excelファイル名>
  4. // 入力用に適当なExcelファイルを用意してください
  5.  
  6. // ----------------------------
  7. // Grapeによるライブラリ取得
  8. @Grab(group='org.apache.poi', module='poi', version='3.5-beta3')
  9. import org.apache.poi.hssf.usermodel.*
  10. import org.apache.poi.poifs.filesystem.*
  11.  
  12. // ----------------------------
  13. // Excelファイルの読み込み
  14. def inputFile = new File(args[0])
  15. def book = new HSSFWorkbook(new POIFSFileSystem(new FileInputStream(inputFile)))
  16. def sheet1 = book.getSheetAt(0) // 第1シート
  17. def sheet2 = book.getSheetAt(1) // 第2シート
  18. def sheet3 = book.getSheet("Sheet3") // シート名で指定も可能
  19.  
  20. def sheet = sheet1 // 以降で使うシートを選択
  21. //def sheet = sheet2
  22. //def sheet = sheet3
  23.  
  24. // ----------------------------
  25. // セルの書き換え
  26. // HSSFCellの特定は読み込みと同じであるため、簡単のためヘルパメソッドを利用する
  27. def cell = { row, col ->
  28. sheet.getRow(row)?.getCell((short) col)
  29. }
  30.  
  31. // 事前の値確認
  32. println cell(0, 0).stringCellValue // A1
  33. println cell(1, 0).stringCellValue // A2
  34. println cell(2, 0).numericCellValue.intValue() // A3 (double->int)
  35. println cell(3, 0).dateCellValue // A4
  36. println cell(4, 0).booleanCellValue // A5
  37.  
  38. // 書き換え
  39. cell(0, 0).setCellValue("Modified_A1") // A1
  40. cell(1, 0).setCellValue("変更した_A2") // A2
  41. cell(2, 0).setCellValue(7890) // A3
  42. cell(3, 0).setCellValue(new Date()) // A4
  43. cell(4, 0).setCellValue(false) // A5
  44.  
  45. // 事後の値確認
  46. println cell(0, 0).stringCellValue // A1
  47. println cell(1, 0).stringCellValue // A2
  48. println cell(2, 0).numericCellValue.intValue() // A3 (double->int)
  49. println cell(3, 0).dateCellValue // A4
  50. println cell(4, 0).booleanCellValue // A5
  51.  
  52. // ----------------------------
  53. // 新規Excelファイルへの出力
  54. def outputFile = new File(args[1])
  55. outputFile.withOutputStream { out ->
  56. book.write(out)
  57. }
Add Comment
Please, Sign In to add comment