Skip to content

Instantly share code, notes, and snippets.

@osima
Created December 15, 2010 06:18
Show Gist options
  • Select an option

  • Save osima/741691 to your computer and use it in GitHub Desktop.

Select an option

Save osima/741691 to your computer and use it in GitHub Desktop.
convert XLS to XML using groovy
@Grab(group='poi', module='poi', version='3.1-FINAL')
@Grab(group='jdom', module='jdom', version='1.1')
import org.jdom.*
import org.jdom.output.*
import org.apache.poi.hssf.usermodel.HSSFWorkbook
def xlsfile = new File(args[0])
def xmlfile = new File(args[1])
def rowlist = []
def book = new HSSFWorkbook( new FileInputStream(xlsfile) )
if( book.getNumberOfSheets() < 1 ) System.exit(0)
def sheet = book.getSheetAt(0)
def j = 0
while( true ){
def row = sheet.getRow(j)
if( row == null ) break
j++
def list = []
def i = 0
while( true ){
def cell = row.getCell(i)
if( cell == null ) break
i++
def getvalue = {
try{
return it.getStringCellValue()
}catch(Exception ex){
return "${it.getNumericCellValue()}"
}
}
def cellValue = getvalue(cell)
list.add( cellValue )
}
rowlist.add( list )
}
def eRoot = new Element('root')
rowlist.each{ list->
def eRow = new Element('row')
eRoot.addContent(eRow)
list.each{
def eCell = new Element('cell')
eCell.setText( it )
eRow.addContent( eCell )
}
}
def w = xmlfile.newWriter('UTF-8')
def outputter = new XMLOutputter(Format.getPrettyFormat())
outputter.output( new Document(eRoot),w )
w.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment