Created
February 29, 2012 12:45
-
-
Save arkadiyk/1940550 to your computer and use it in GitHub Desktop.
Parse Excel with JRuby and POI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "java" | |
class ExcelController < ApplicationController | |
# Controller method | |
def parse_uploaded_file | |
excel_file = params[:excel_file] # file input element | |
begin | |
parsed_data = parse_excel(excel_file[0].read) | |
render :json => {:result => "OK"} | |
rescue Exception => e | |
logger.error "BOOM : #{e.inspect}" | |
render :json => {:result => "Error"} | |
end | |
end | |
private | |
def parse_excel content | |
upload_is = java.io.ByteArrayInputStream.new(content.to_java_bytes) | |
excel_fs = org.apache.poi.poifs.filesystem.POIFSFileSystem.new(upload_is) | |
work_book = org.apache.poi.hssf.usermodel.HSSFWorkbook.new(excel_fs) | |
sheet = work_book.sheet_at 0 | |
out_data = [] | |
sheet.row_iterator.entries.each do |row| | |
out_data << row.cell_iterator.entries.map{|c| cell_value(c)} | |
end | |
out_data | |
end | |
def cell_value cell | |
case cell.cell_type | |
when org.apache.poi.ss.usermodel.Cell::CELL_TYPE_NUMERIC then cell.numeric_cell_value | |
when org.apache.poi.ss.usermodel.Cell::CELL_TYPE_STRING then cell.string_cell_value | |
when org.apache.poi.ss.usermodel.Cell::CELL_TYPE_FORMULA then cell.numeric_cell_value | |
else "**ERROR** #{cell.cell_type}" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
may not work as it is because I took out some business logic which was not relevant to the parsing part