wickedcoolthoughts
Friday, December 7, 2007
  Excel POI Wrapper in JRuby
Disclaimer:This is one of my very first JRuby/Ruby programs.
Dont be surprised if I am writing Java/C# in JRuby.



require '../../poi-3.0.1-FINAL-20070705.jar'
include Java

include_class java.io.FileInputStream
include_class Java::org.apache.poi.hssf.usermodel.HSSFWorkbook
include_class Java::org.apache.poi.hssf.usermodel.HSSFSheet
include_class Java::org.apache.poi.hssf.usermodel.HSSFRow
include_class Java::org.apache.poi.hssf.usermodel.HSSFCell

class ExcelWorkBook

def initialize(xlsFile)
input = FileInputStream.new(xlsFile)
@hssfworkbook = HSSFWorkbook.new(input)
end

def worksheet(sheet_position)
ExcelWorkSheet.new(@hssfworkbook.getSheetAt(sheet_position),sheet_position)
end

class ExcelWorkSheet

def initialize(hssfworksheet, sheet_position)
@index = sheet_position
@hssfworksheet = hssfworksheet
end

def row_at(rownumber)
return Row.new(@hssfworksheet.getRow(rownumber))
end

def rows
rows = []
for row in @hssfworksheet.rowIterator
rows << Row.new(row)
end
rows
end

class Row

def initialize(hssfrow)
@hssfrow = hssfrow
end

def value_at(columnindex)

cell = @hssfrow.getCell(columnindex)

if(cell == nil)
''
elsif(HSSFCell::CELL_TYPE_NUMERIC == cell.getCellType())
cell.getNumericCellValue()

elsif(HSSFCell::CELL_TYPE_STRING == cell.getCellType())
cell.getRichStringCellValue()
end

end

end

end
end



 
Comments:
One minor suggestion.

instead of:

def rows
  rows = []
  for row in @hssfworksheet.rowIterator
    rows << Row.new(row)
  end
  rows
end

you could say:

def rows
  @hssfworksheet.rowIterator.map do |row|
    Row.new(row)
  end
end

Either way, it does the same thing; but I like closures :-)
 
Post a Comment

Subscribe to Post Comments [Atom]





<< Home

My Photo
Name:
Location: India

I am passionate about making Better Software Solutions,that helps businesses to stay agile, by applying Agile,Lean and Systems Thinking principles. Also I grow coffee,spices and in general has big interest in pesticide free food!

Archives
December 2007 / January 2008 / February 2008 / March 2008 / June 2011 /


Powered by Blogger

Subscribe to
Posts [Atom]