2

How do I open an existing excel file in Groovy so I can start manipulating it?

4
  • stackoverflow.com/questions/521274/… Commented Jul 8, 2013 at 22:54
  • That really doesn't show me how to open an existing file in Groovy. :/ Commented Jul 9, 2013 at 0:38
  • 1
    You 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. Commented Jul 9, 2013 at 2:28
  • Added a full example Groovy script Commented Jul 9, 2013 at 8:05

1 Answer 1

2

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 )
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.