Module: Excelinator
- Defined in:
- lib/excelinator/xls.rb,
lib/excelinator/rails.rb,
lib/excelinator/version.rb
Defined Under Namespace
Modules: Rails
Constant Summary collapse
- MIME_TYPE =
'application/vnd.ms-excel'
- VERSION =
'1.3.1'
Class Method Summary collapse
-
.convert_content(content) ⇒ Object
Detects HTML table content (with a rather stupid regex: /<table/) and re-uses it, or attempts to convert from CSV if HTML not detected.
- .csv_to_xls(csv_content, separator = ",") ⇒ Object
-
.csv_to_xls_file(csv_path, file, separator = ",") ⇒ Object
memory ftw.
-
.html_as_xls(html_content, options = {}) ⇒ Object
This only strips a <table> out of the html and adds a meta tag for utf-8 support.
Class Method Details
.convert_content(content) ⇒ Object
Detects HTML table content (with a rather stupid regex: /<table/) and re-uses it, or attempts to convert from CSV if HTML not detected.
6 7 8 |
# File 'lib/excelinator/xls.rb', line 6 def self.convert_content(content) content =~ /<table/ ? Excelinator.html_as_xls(content) : Excelinator.csv_to_xls(content) end |
.csv_to_xls(csv_content, separator = ",") ⇒ Object
10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# File 'lib/excelinator/xls.rb', line 10 def self.csv_to_xls(csv_content, separator=",") ary = (!old_ruby? ? CSV : FasterCSV).parse(csv_content, { :col_sep => separator} ) book = Spreadsheet::Workbook.new sheet = book.create_worksheet ary.each_with_index do |row_ary, index| row = sheet.row(index) row.push(*row_ary) end content = '' ios = StringIO.new(content) book.write(ios) content end |
.csv_to_xls_file(csv_path, file, separator = ",") ⇒ Object
memory ftw
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/excelinator/xls.rb', line 26 def self.csv_to_xls_file(csv_path, file, separator=",") book = Spreadsheet::Workbook.new sheet = book.create_worksheet CSV.open(csv_path, { :col_sep => separator} ) do |csv| index = 0 csv.each do |raw_row| row = sheet.row(index) row.push(*raw_row) index +=1 end end book.write(file) file end |
.html_as_xls(html_content, options = {}) ⇒ Object
This only strips a <table> out of the html and adds a meta tag for utf-8 support. Excel will open an .xls file with this content and grok it correctly (including formatting); however, many alternate spreadsheet applications will not do this.
If the html_content is very large, the default behavior of scanning out the table contents will consume a lot of memory. If the :do_not_strip option is passed, this expensive scan call will be skipped and the entire contents will be returned.
If you don’t have need of utf-8 encoding, or want to prepend that yourself, there’s no need to use this method.
52 53 54 55 |
# File 'lib/excelinator/xls.rb', line 52 def self.html_as_xls(html_content, ={}) = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8">' + (.delete(:do_not_strip) ? html_content : html_content.scan(/<table.*\/table>/mi).join) end |