crek 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 7c404206925061b8e726700f12cded8e1ea2ff3c64525e378ba389d47b1d5655
4
+ data.tar.gz: 005125795034be22ad11df10b85dbb73aeeae06f4e3f7448f346850d610b3a8c
5
+ SHA512:
6
+ metadata.gz: d118c391ce7ff9744e1b81ed15983f86e592c114cbeadf33f8b18cabb386555779af401bbf2f5ecd012aa58d204e403ffc71db53b67cdd2a3d9c1f227ab93f70
7
+ data.tar.gz: fb18ce3335fd78f7b3caa130b2983e83050b9b03dceac501ef417715b7890617fe7eca21e22ff16f9f122027bb7ce61f8a1de6a2121c17568e3252977bc87cb8
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -0,0 +1,7 @@
1
+ ---
2
+ sudo: false
3
+ language: ruby
4
+ cache: bundler
5
+ rvm:
6
+ - 2.6.0
7
+ before_install: gem install bundler -v 1.17.2
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at dibyajit.g@treniq.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in crek.gemspec
6
+ gemspec
@@ -0,0 +1,42 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ crek (0.1.0)
5
+ nokogiri (~> 1.6.0)
6
+ rubyzip (>= 1.0.0)
7
+
8
+ GEM
9
+ remote: https://rubygems.org/
10
+ specs:
11
+ coderay (1.1.2)
12
+ diff-lcs (1.3)
13
+ method_source (0.9.2)
14
+ mini_portile2 (2.1.0)
15
+ nokogiri (1.6.8.1)
16
+ mini_portile2 (~> 2.1.0)
17
+ pry (0.12.2)
18
+ coderay (~> 1.1.0)
19
+ method_source (~> 0.9.0)
20
+ rake (10.5.0)
21
+ rspec (2.13.0)
22
+ rspec-core (~> 2.13.0)
23
+ rspec-expectations (~> 2.13.0)
24
+ rspec-mocks (~> 2.13.0)
25
+ rspec-core (2.13.1)
26
+ rspec-expectations (2.13.0)
27
+ diff-lcs (>= 1.1.3, < 2.0)
28
+ rspec-mocks (2.13.1)
29
+ rubyzip (1.2.2)
30
+
31
+ PLATFORMS
32
+ ruby
33
+
34
+ DEPENDENCIES
35
+ bundler (~> 1.3)
36
+ crek!
37
+ pry
38
+ rake (< 11.0)
39
+ rspec (~> 2.13.0)
40
+
41
+ BUNDLED WITH
42
+ 1.17.2
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 Dibyajit
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,76 @@
1
+ = Crek -- Stream parser for large Excel(xlsx and xlsm) files.
2
+
3
+ Crek is a Ruby gem that provide a fast, simple and efficient method of parsing large Excel(xlsx and xlsm) files.
4
+
5
+
6
+ == Installation
7
+
8
+ Crek can be used from the command line or as part of a Ruby web framework. To install the gem using terminal, run the following command:
9
+
10
+ gem install Crek
11
+
12
+ To use it in Rails, add this line to your Gemfile:
13
+
14
+ gem "Crek"
15
+
16
+
17
+ == Basic Usage
18
+ Crek can simply parse an Excel file by looping through the rows enumerator:
19
+
20
+ require 'Crek'
21
+ Crek = Crek::Book.new "specs/fixtures/sample.xlsx"
22
+ sheet= Crek.sheets[0]
23
+
24
+ sheet.rows.each do |row|
25
+ puts row # => {"A1"=>"Content 1", "B1"=>nil, C1"=>nil, "D1"=>"Content 3"}
26
+ end
27
+
28
+
29
+ sheet.rows_with_meta_data.each do |row|
30
+ puts row # => {"collapsed"=>"false", "customFormat"=>"false", "customHeight"=>"true", "hidden"=>"false", "ht"=>"12.1", "outlineLevel"=>"0", "r"=>"1", "cells"=>{"A1"=>"Content 1", "B1"=>nil, C1"=>nil, "D1"=>"Content 3"}}
31
+ end
32
+
33
+
34
+ sheet.state # => 'visible'
35
+ sheet.name # => 'Sheet1'
36
+ sheet.rid # => 'rId2'
37
+
38
+ == Filename considerations
39
+ By default, Crek will ensure that the file extension is either *.xlsx or *.xlsm, but this check can be circumvented as needed:
40
+
41
+ path = 'sample-as-zip.zip'
42
+ Crek::Book.new path, :check_file_extension => false
43
+
44
+ By default, the Rails {file_field_tag}[http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-file_field_tag] uploads to a temporary location and stores the original filename with the StringIO object. (See {this section}[http://guides.rubyonrails.org/form_helpers.html#uploading-files] of the Rails Guides for more information.)
45
+
46
+ Crek can parse this directly without the need for file upload gems such as Carrierwave or Paperclip by passing the original filename as an option:
47
+
48
+ # Import endpoint in Rails controller
49
+ def import
50
+ file = params[:file]
51
+ Crek::Book.new file.path, check_file_extension: false
52
+ end
53
+
54
+ == Contributing
55
+
56
+ Contributions are welcomed. You can fork a repository, add your code changes to the forked branch, ensure all existing unit tests pass, create new unit tests cover your new changes and finally create a pull request.
57
+
58
+ After forking and then cloning the repository locally, install Bundler and then use it
59
+ to install the development gem dependecies:
60
+
61
+ gem install bundler
62
+ bundle install
63
+
64
+ Once this is complete, you should be able to run the test suite:
65
+
66
+ rake
67
+
68
+
69
+ == Bug Reporting
70
+
71
+ Please use the {Issues}[https://github.com/pythonicrubyist/Crek/issues] page to report bugs or suggest new enhancements.
72
+
73
+
74
+ == License
75
+
76
+ Crek has been published under {MIT License}[https://github.com/pythonicrubyist/Crek/blob/master/LICENSE.txt]
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new('spec')
5
+
6
+ task :default => :spec
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "crek"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,48 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "crek/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "crek"
8
+ spec.version = Crek::VERSION
9
+ spec.authors = ["Dibyajit"]
10
+ spec.email = ["dibyajit.g@treniq.com"]
11
+
12
+ spec.summary = %q{Creek with image read from xlsx feature for Creek 1.1.2.}
13
+ spec.description = %q{Creek with image read from xlsx feature for Creek 1.1.2.}
14
+ spec.homepage = "https://github.com/dibyajitgoswamidg/crek"
15
+ spec.license = "MIT"
16
+
17
+ # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
18
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
19
+ #if spec.respond_to?(:metadata)
20
+ #spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'"
21
+
22
+ #spec.metadata["homepage_uri"] = spec.homepage
23
+ #spec.metadata["source_code_uri"] = "TODO: Put your gem's public repo URL here."
24
+ #spec.metadata["changelog_uri"] = "TODO: Put your gem's CHANGELOG.md URL here."
25
+ #else
26
+ #raise "RubyGems 2.0 or newer is required to protect against " \
27
+ #"public gem pushes."
28
+ #end
29
+
30
+ # Specify which files should be added to the gem when it is released.
31
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
32
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
33
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
34
+ end
35
+ spec.bindir = "exe"
36
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
37
+ spec.require_paths = ["lib"]
38
+
39
+ spec.required_ruby_version = '>= 2.0.0'
40
+
41
+ spec.add_development_dependency "bundler", "~> 1.3"
42
+ spec.add_development_dependency "rake", "< 11.0"
43
+ spec.add_development_dependency 'rspec', '~> 2.13.0'
44
+ spec.add_development_dependency 'pry'
45
+
46
+ spec.add_dependency 'nokogiri', '~> 1.6.0'
47
+ spec.add_dependency 'rubyzip', '>= 1.0.0'
48
+ end
@@ -0,0 +1,15 @@
1
+ require "crek/version"
2
+ require 'creek/book'
3
+ require 'creek/styles/constants'
4
+ require 'creek/styles/style_types'
5
+ require 'creek/styles/converter'
6
+ require 'creek/utils' #added later
7
+ require 'creek/styles'
8
+ require 'creek/drawing' #added later
9
+ require 'creek/sheet'
10
+ require 'creek/shared_strings'
11
+
12
+ module Crek
13
+ class Error < StandardError; end
14
+ # Your code goes here...
15
+ end
@@ -0,0 +1,84 @@
1
+ require 'zip/filesystem'
2
+ require 'nokogiri'
3
+ require 'date'
4
+ #require 'http'
5
+
6
+ module Crek
7
+
8
+ class Crek::Book
9
+
10
+ attr_reader :files,
11
+ :sheets,
12
+ :shared_strings
13
+
14
+ DATE_1900 = Date.new(1899, 12, 30).freeze
15
+ DATE_1904 = Date.new(1904, 1, 1).freeze
16
+
17
+ def initialize path, options = {}
18
+ check_file_extension = options.fetch(:check_file_extension, true)
19
+ if check_file_extension
20
+ extension = File.extname(options[:original_filename] || path).downcase
21
+ raise 'Not a valid file format.' unless (['.xlsx', '.xlsm'].include? extension)
22
+ end
23
+ if options[:remote]
24
+ zipfile = Tempfile.new("file")
25
+ zipfile.binmode
26
+ zipfile.write(HTTP.get(path).to_s)
27
+ zipfile.close
28
+ path = zipfile.path
29
+ end
30
+ @files = Zip::File.open path
31
+ @shared_strings = SharedStrings.new(self)
32
+ end
33
+
34
+ def sheets
35
+ doc = @files.file.open "xl/workbook.xml"
36
+ xml = Nokogiri::XML::Document.parse doc
37
+ namespaces = xml.namespaces
38
+
39
+ cssPrefix = ''
40
+ namespaces.each do |namespace|
41
+ if namespace[1] == 'http://schemas.openxmlformats.org/spreadsheetml/2006/main' && namespace[0] != 'xmlns' then
42
+ cssPrefix = namespace[0].split(':')[1]+'|'
43
+ end
44
+ end
45
+
46
+ rels_doc = @files.file.open "xl/_rels/workbook.xml.rels"
47
+ rels = Nokogiri::XML::Document.parse(rels_doc).css("Relationship")
48
+
49
+ @sheets = xml.css(cssPrefix+'sheet').map do |sheet|
50
+ sheetfile = rels.find { |el| sheet.attr("r:id") == el.attr("Id") }.attr("Target")
51
+ Sheet.new(self, sheet.attr("name"), sheet.attr("sheetid"), sheet.attr("state"), sheet.attr("visible"), sheet.attr("r:id"), sheetfile)
52
+ end
53
+ end
54
+
55
+ def style_types
56
+ @style_types ||= Crek::Styles.new(self).style_types
57
+ end
58
+
59
+ def close
60
+ @files.close
61
+ end
62
+
63
+ def base_date
64
+ @base_date ||=
65
+ begin
66
+ # Default to 1900 (minus one day due to excel quirk) but use 1904 if
67
+ # it's set in the Workbook's workbookPr
68
+ # http://msdn.microsoft.com/en-us/library/ff530155(v=office.12).aspx
69
+ result = DATE_1900 # default
70
+
71
+ doc = @files.file.open "xl/workbook.xml"
72
+ xml = Nokogiri::XML::Document.parse doc
73
+ xml.css('workbookPr[date1904]').each do |workbookPr|
74
+ if workbookPr['date1904'] =~ /true|1/i
75
+ result = DATE_1904
76
+ break
77
+ end
78
+ end
79
+
80
+ result
81
+ end
82
+ end
83
+ end
84
+ end
@@ -0,0 +1,109 @@
1
+ require 'pathname'
2
+
3
+ module Crek
4
+ class Crek::Drawing
5
+ include Crek::Utils
6
+
7
+ COLUMNS = ('A'..'AZ').to_a
8
+
9
+ def initialize(book, drawing_filepath)
10
+ @book = book
11
+ @drawing_filepath = drawing_filepath
12
+ @drawings = []
13
+ @drawings_rels = []
14
+ @images_pathnames = Hash.new { |hash, key| hash[key] = [] }
15
+
16
+ if file_exist?(@drawing_filepath)
17
+ load_drawings_and_rels
18
+ load_images_pathnames_by_cells if has_images?
19
+ end
20
+ end
21
+
22
+ ##
23
+ # Returns false if there are no images in the drawing file or the drawing file does not exist, true otherwise.
24
+ def has_images?
25
+ @has_images ||= !@drawings.empty?
26
+ end
27
+
28
+ ##
29
+ # Extracts images from excel to tmpdir for a cell, if the images are not already extracted (multiple calls or same image file in multiple cells).
30
+ # Returns array of images as Pathname objects or nil.
31
+ def images_at(cell_name)
32
+ coordinate = calc_coordinate(cell_name)
33
+ pathnames_at_coordinate = @images_pathnames[coordinate]
34
+ return if pathnames_at_coordinate.empty?
35
+
36
+ pathnames_at_coordinate.map do |image_pathname|
37
+ if image_pathname.exist?
38
+ image_pathname
39
+ else
40
+ excel_image_path = "xl/media#{image_pathname.to_path.split(tmpdir).last}"
41
+ IO.copy_stream(@book.files.file.open(excel_image_path), image_pathname.to_path)
42
+ image_pathname
43
+ end
44
+ end
45
+ end
46
+
47
+ private
48
+
49
+ ##
50
+ # Transforms cell name to [row, col], e.g. A1 => [0, 0], B3 => [1, 2]
51
+ # Rows and cols start with 0.
52
+ def calc_coordinate(cell_name)
53
+ col = COLUMNS.index(cell_name.slice /[A-Z]+/)
54
+ row = (cell_name.slice /\d+/).to_i - 1 # rows in drawings start with 0
55
+ [row, col]
56
+ end
57
+
58
+ ##
59
+ # Creates/loads temporary directory for extracting images from excel
60
+ def tmpdir
61
+ @tmpdir ||= ::Dir.mktmpdir('Crek__drawing')
62
+ end
63
+
64
+ ##
65
+ # Parses drawing and drawing's relationships xmls.
66
+ # Drawing xml contains relationships ID's and coordinates (row, col).
67
+ # Drawing relationships xml contains images' locations.
68
+ def load_drawings_and_rels
69
+ @drawings = parse_xml(@drawing_filepath).css('xdr|twoCellAnchor')
70
+ drawing_rels_filepath = expand_to_rels_path(@drawing_filepath)
71
+ @drawings_rels = parse_xml(drawing_rels_filepath).css('Relationships')
72
+ end
73
+
74
+ ##
75
+ # Iterates through the drawings and saves images' paths as Pathname objects to a hash with [row, col] keys.
76
+ # As multiple images can be located in a single cell, hash values are array of Pathname objects.
77
+ # One image can be spread across multiple cells (defined with from-row/to-row/from-col/to-col attributes) - same Pathname object is associated to each row-col combination for the range.
78
+ def load_images_pathnames_by_cells
79
+ image_selector = 'xdr:pic/xdr:blipFill/a:blip'.freeze
80
+ row_from_selector = 'xdr:from/xdr:row'.freeze
81
+ row_to_selector = 'xdr:to/xdr:row'.freeze
82
+ col_from_selector = 'xdr:from/xdr:col'.freeze
83
+ col_to_selector = 'xdr:to/xdr:col'.freeze
84
+
85
+ @drawings.xpath('//xdr:twoCellAnchor').each do |drawing|
86
+ embed = drawing.xpath(image_selector).first.attributes['embed']
87
+ next if embed.nil?
88
+
89
+ rid = embed.value
90
+ path = Pathname.new("#{tmpdir}/#{extract_drawing_path(rid).slice(/[^\/]*$/)}")
91
+
92
+ row_from = drawing.xpath(row_from_selector).text.to_i
93
+ col_from = drawing.xpath(col_from_selector).text.to_i
94
+ row_to = drawing.xpath(row_to_selector).text.to_i
95
+ col_to = drawing.xpath(col_to_selector).text.to_i
96
+
97
+ (col_from..col_to).each do |col|
98
+ (row_from..row_to).each do |row|
99
+ @images_pathnames[[row, col]].push(path)
100
+ end
101
+ end
102
+ end
103
+ end
104
+
105
+ def extract_drawing_path(rid)
106
+ @drawings_rels.css("Relationship[@Id=#{rid}]").first.attributes['Target'].value
107
+ end
108
+ end
109
+ end
@@ -0,0 +1,44 @@
1
+ require 'zip/filesystem'
2
+ require 'nokogiri'
3
+
4
+ module Crek
5
+
6
+ class Crek::SharedStrings
7
+
8
+ attr_reader :book, :dictionary
9
+
10
+ def initialize book
11
+ @book = book
12
+ parse_shared_shared_strings
13
+ end
14
+
15
+ def parse_shared_shared_strings
16
+ path = "xl/sharedStrings.xml"
17
+ if @book.files.file.exist?(path)
18
+ doc = @book.files.file.open path
19
+ xml = Nokogiri::XML::Document.parse doc
20
+ parse_shared_string_from_document(xml)
21
+ end
22
+ end
23
+
24
+ def parse_shared_string_from_document(xml)
25
+ @dictionary = self.class.parse_shared_string_from_document(xml)
26
+ end
27
+
28
+ def self.parse_shared_string_from_document(xml)
29
+ dictionary = Hash.new
30
+
31
+ xml.css('si').each_with_index do |si, idx|
32
+ text_nodes = si.css('t')
33
+ if text_nodes.count == 1 # plain text node
34
+ dictionary[idx] = text_nodes.first.content
35
+ else # rich text nodes with text fragments
36
+ dictionary[idx] = text_nodes.map{ |n| Crek::Styles::Converter.unescape_string(n.content) }.join('')
37
+ end
38
+ end
39
+
40
+ dictionary
41
+ end
42
+
43
+ end
44
+ end
@@ -0,0 +1,175 @@
1
+ require 'zip/filesystem'
2
+ require 'nokogiri'
3
+
4
+ module Crek
5
+ class Crek::Sheet
6
+ include Crek::Utils
7
+
8
+ attr_reader :book,
9
+ :name,
10
+ :sheetid,
11
+ :state,
12
+ :visible,
13
+ :rid,
14
+ :index
15
+
16
+
17
+ def initialize book, name, sheetid, state, visible, rid, sheetfile
18
+ @book = book
19
+ @name = name
20
+ @sheetid = sheetid
21
+ @visible = visible
22
+ @rid = rid
23
+ @state = state
24
+ @sheetfile = sheetfile
25
+ @images_present = false
26
+ end
27
+
28
+ ##
29
+ # Preloads images info (coordinates and paths) from related drawing.xml and drawing rels.
30
+ # Must be called before #rows method if you want to have images included.
31
+ # Returns self so you can chain the calls (sheet.with_images.rows).
32
+ def with_images
33
+ @drawingfile = extract_drawing_filepath
34
+ if @drawingfile
35
+ @drawing = Crek::Drawing.new(@book, @drawingfile.sub('..', 'xl'))
36
+ @images_present = @drawing.has_images?
37
+ end
38
+ self
39
+ end
40
+
41
+ ##
42
+ # Extracts images for a cell to a temporary folder.
43
+ # Returns array of Pathnames for the cell.
44
+ # Returns nil if images asre not found for the cell or images were not preloaded with #with_images.
45
+ def images_at(cell)
46
+ @drawing.images_at(cell) if @images_present
47
+ end
48
+
49
+
50
+ ##
51
+ # Provides an Enumerator that returns a hash representing each row.
52
+ # The key of the hash is the column ID and the value is the value of the cell.
53
+ def simple_rows
54
+ rows_generator false, true
55
+ end
56
+
57
+ ##
58
+ # Provides an Enumerator that returns a hash representing each row.
59
+ # The key of the hash is the Cell id and the value is the value of the cell.
60
+ def rows
61
+ rows_generator false, false
62
+ end
63
+
64
+ ##
65
+ # Provides an Enumerator that returns a hash representing each row.
66
+ # The hash contains meta data of the row and a 'cells' embended hash which contains the cell contents.
67
+ def rows_with_meta_data
68
+ rows_generator true, false
69
+ end
70
+
71
+ ##
72
+ # Provides an Enumerator that returns a hash representing each row.
73
+ # The hash contains meta data of the row and a 'cells' embended hash which contains the cell contents.
74
+ def simple_rows_with_meta_data
75
+ rows_generator true, true
76
+ end
77
+
78
+ private
79
+
80
+ ##
81
+ # Returns a hash per row that includes the cell ids and values.
82
+ # Empty cells will be also included in the hash with a nil value.
83
+ def rows_generator include_meta_data=false, use_simple_rows_format=false
84
+ path = if @sheetfile.start_with? "/xl/" or @sheetfile.start_with? "xl/" then @sheetfile else "xl/#{@sheetfile}" end
85
+ if @book.files.file.exist?(path)
86
+ # SAX parsing, Each element in the stream comes through as two events:
87
+ # one to open the element and one to close it.
88
+ opener = Nokogiri::XML::Reader::TYPE_ELEMENT
89
+ closer = Nokogiri::XML::Reader::TYPE_END_ELEMENT
90
+ Enumerator.new do |y|
91
+ row, cells, cell = nil, {}, nil
92
+ cell_type = nil
93
+ cell_style_idx = nil
94
+ @book.files.file.open(path) do |xml|
95
+ Nokogiri::XML::Reader.from_io(xml).each do |node|
96
+ if (node.name.eql? 'row') and (node.node_type.eql? opener)
97
+ row = node.attributes
98
+ row['cells'] = Hash.new
99
+ cells = Hash.new
100
+ y << (include_meta_data ? row : cells) if node.self_closing?
101
+ elsif (node.name.eql? 'row') and (node.node_type.eql? closer)
102
+ processed_cells = fill_in_empty_cells(cells, row['r'], cell, use_simple_rows_format)
103
+
104
+ if @images_present
105
+ processed_cells.each do |cell_name, cell_value|
106
+ next unless cell_value.nil?
107
+ processed_cells[cell_name] = images_at(cell_name)
108
+ end
109
+ end
110
+
111
+ row['cells'] = processed_cells
112
+ y << (include_meta_data ? row : processed_cells)
113
+ elsif (node.name.eql? 'c') and (node.node_type.eql? opener)
114
+ cell_type = node.attributes['t']
115
+ cell_style_idx = node.attributes['s']
116
+ cell = node.attributes['r']
117
+ elsif (['v', 't'].include? node.name) and (node.node_type.eql? opener)
118
+ unless cell.nil?
119
+ cells[(use_simple_rows_format ? cell.tr("0-9", "") : cell)] = convert(node.inner_xml, cell_type, cell_style_idx)
120
+ end
121
+ end
122
+ end
123
+ end
124
+ end
125
+ end
126
+ end
127
+
128
+ def convert(value, type, style_idx)
129
+ style = @book.style_types[style_idx.to_i]
130
+ Crek::Styles::Converter.call(value, type, style, converter_options)
131
+ end
132
+
133
+ def converter_options
134
+ @converter_options ||= {
135
+ shared_strings: @book.shared_strings.dictionary,
136
+ base_date: @book.base_date
137
+ }
138
+ end
139
+
140
+ ##
141
+ # The unzipped XML file does not contain any node for empty cells.
142
+ # Empty cells are being padded in using this function
143
+ def fill_in_empty_cells(cells, row_number, last_col, use_simple_rows_format)
144
+ new_cells = Hash.new
145
+
146
+ unless cells.empty?
147
+ last_col = last_col.gsub(row_number, '')
148
+
149
+ ("A"..last_col).to_a.each do |column|
150
+ id = use_simple_rows_format ? "#{column}" : "#{column}#{row_number}"
151
+ new_cells[id] = cells[id]
152
+ end
153
+ end
154
+
155
+ new_cells
156
+ end
157
+
158
+ ##
159
+ # Find drawing filepath for the current sheet.
160
+ # Sheet xml contains drawing relationship ID.
161
+ # Sheet relationships xml contains drawing file's location.
162
+ def extract_drawing_filepath
163
+ # Read drawing relationship ID from the sheet.
164
+ sheet_filepath = "xl/#{@sheetfile}"
165
+ drawing = parse_xml(sheet_filepath).css('drawing').first
166
+ return if drawing.nil?
167
+
168
+ drawing_rid = drawing.attributes['id'].value
169
+
170
+ # Read sheet rels to find drawing file's location.
171
+ sheet_rels_filepath = expand_to_rels_path(sheet_filepath)
172
+ parse_xml(sheet_rels_filepath).css("Relationship[@Id='#{drawing_rid}']").first.attributes['Target'].value
173
+ end
174
+ end
175
+ end
@@ -0,0 +1,27 @@
1
+ module Crek
2
+ class Styles
3
+ attr_accessor :book
4
+ def initialize(book)
5
+ @book = book
6
+ end
7
+
8
+ def path
9
+ "xl/styles.xml"
10
+ end
11
+
12
+ def styles_xml
13
+ @styles_xml ||= begin
14
+ if @book.files.file.exist?(path)
15
+ doc = @book.files.file.open path
16
+ Nokogiri::XML::Document.parse doc
17
+ end
18
+ end
19
+ end
20
+
21
+ def style_types
22
+ @style_types ||= begin
23
+ Crek::Styles::StyleTypes.new(styles_xml).call
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,41 @@
1
+ module Creek
2
+ class Styles
3
+ module Constants
4
+ # Map of non-custom numFmtId to casting symbol
5
+ NumFmtMap = {
6
+ 0 => :string, # General
7
+ 1 => :fixnum, # 0
8
+ 2 => :float, # 0.00
9
+ 3 => :fixnum, # #,##0
10
+ 4 => :float, # #,##0.00
11
+ 5 => :unsupported, # $#,##0_);($#,##0)
12
+ 6 => :unsupported, # $#,##0_);[Red]($#,##0)
13
+ 7 => :unsupported, # $#,##0.00_);($#,##0.00)
14
+ 8 => :unsupported, # $#,##0.00_);[Red]($#,##0.00)
15
+ 9 => :percentage, # 0%
16
+ 10 => :percentage, # 0.00%
17
+ 11 => :bignum, # 0.00E+00
18
+ 12 => :unsupported, # # ?/?
19
+ 13 => :unsupported, # # ??/??
20
+ 14 => :date, # mm-dd-yy
21
+ 15 => :date, # d-mmm-yy
22
+ 16 => :date, # d-mmm
23
+ 17 => :date, # mmm-yy
24
+ 18 => :time, # h:mm AM/PM
25
+ 19 => :time, # h:mm:ss AM/PM
26
+ 20 => :time, # h:mm
27
+ 21 => :time, # h:mm:ss
28
+ 22 => :date_time, # m/d/yy h:mm
29
+ 37 => :unsupported, # #,##0 ;(#,##0)
30
+ 38 => :unsupported, # #,##0 ;[Red](#,##0)
31
+ 39 => :unsupported, # #,##0.00;(#,##0.00)
32
+ 40 => :unsupported, # #,##0.00;[Red](#,##0.00)
33
+ 45 => :time, # mm:ss
34
+ 46 => :time, # [h]:mm:ss
35
+ 47 => :time, # mmss.0
36
+ 48 => :bignum, # ##0.0E+0
37
+ 49 => :unsupported # @
38
+ }
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,103 @@
1
+ require 'set'
2
+
3
+ module Creek
4
+ class Styles
5
+ class Converter
6
+ include Creek::Styles::Constants
7
+ ##
8
+ # The heart of typecasting. The ruby type is determined either explicitly
9
+ # from the cell xml or implicitly from the cell style, and this
10
+ # method expects that work to have been done already. This, then,
11
+ # takes the type we determined it to be and casts the cell value
12
+ # to that type.
13
+ #
14
+ # types:
15
+ # - s: shared string (see #shared_string)
16
+ # - n: number (cast to a float)
17
+ # - b: boolean
18
+ # - str: string
19
+ # - inlineStr: string
20
+ # - ruby symbol: for when type has been determined by style
21
+ #
22
+ # options:
23
+ # - shared_strings: needed for 's' (shared string) type
24
+ # - base_date: from what date to begin, see method #base_date
25
+
26
+ DATE_TYPES = [:date, :time, :date_time].to_set
27
+ def self.call(value, type, style, options = {})
28
+ return nil if value.nil? || value.empty?
29
+
30
+ # Sometimes the type is dictated by the style alone
31
+ if type.nil? || (type == 'n' && DATE_TYPES.include?(style))
32
+ type = style
33
+ end
34
+
35
+ case type
36
+
37
+ ##
38
+ # There are few built-in types
39
+ ##
40
+
41
+ when 's' # shared string
42
+ options[:shared_strings][value.to_i]
43
+ when 'n' # number
44
+ value.to_f
45
+ when 'b'
46
+ value.to_i == 1
47
+ when 'str'
48
+ value
49
+ when 'inlineStr'
50
+ value
51
+
52
+ ##
53
+ # Type can also be determined by a style,
54
+ # detected earlier and cast here by its standardized symbol
55
+ ##
56
+
57
+ when :string, :unsupported
58
+ value
59
+ when :fixnum
60
+ value.to_i
61
+ when :float
62
+ value.to_f
63
+ when :percentage
64
+ value.to_f / 100
65
+ when :date, :time, :date_time
66
+ convert_date(value, options)
67
+ when :bignum
68
+ convert_bignum(value)
69
+
70
+ ## Nothing matched
71
+ else
72
+ value
73
+ end
74
+ end
75
+
76
+ # the trickiest. note that all these formats can vary on
77
+ # whether they actually contain a date, time, or datetime.
78
+ def self.convert_date(value, options)
79
+ value = value.to_f
80
+ days_since_date_system_start = value.to_i
81
+ fraction_of_24 = value - days_since_date_system_start
82
+
83
+ # http://stackoverflow.com/questions/10559767/how-to-convert-ms-excel-date-from-float-to-date-format-in-ruby
84
+ date = options.fetch(:base_date, Date.new(1899, 12, 30)) + days_since_date_system_start
85
+
86
+ if fraction_of_24 > 0 # there is a time associated
87
+ seconds = (fraction_of_24 * 86400).round
88
+ return Time.utc(date.year, date.month, date.day) + seconds
89
+ else
90
+ return date
91
+ end
92
+ end
93
+
94
+ def self.convert_bignum(value)
95
+ if defined?(BigDecimal)
96
+ BigDecimal.new(value)
97
+ else
98
+ value.to_f
99
+ end
100
+ end
101
+ end
102
+ end
103
+ end
@@ -0,0 +1,85 @@
1
+ # https://github.com/hmcgowan/roo/blob/master/lib/roo/excelx.rb
2
+ # https://github.com/woahdae/simple_xlsx_reader/blob/master/lib/simple_xlsx_reader.rb#L231
3
+ module Creek
4
+ class Styles
5
+ class StyleTypes
6
+ include Creek::Styles::Constants
7
+ attr_accessor :styles_xml_doc
8
+ def initialize(styles_xml_doc)
9
+ @styles_xml_doc = styles_xml_doc
10
+ end
11
+
12
+ # Excel doesn't record types for some cells, only its display style, so
13
+ # we have to back out the type from that style.
14
+ #
15
+ # Some of these styles can be determined from a known set (see NumFmtMap),
16
+ # while others are 'custom' and we have to make a best guess.
17
+ #
18
+ # This is the array of types corresponding to the styles a spreadsheet
19
+ # uses, and includes both the known style types and the custom styles.
20
+ #
21
+ # Note that the xml sheet cells that use this don't reference the
22
+ # numFmtId, but instead the array index of a style in the stored list of
23
+ # only the styles used in the spreadsheet (which can be either known or
24
+ # custom). Hence this style types array, rather than a map of numFmtId to
25
+ # type.
26
+ def call
27
+ @style_types ||= begin
28
+ styles_xml_doc.css('styleSheet cellXfs xf').map do |xstyle|
29
+ a = num_fmt_id(xstyle)
30
+ style_type_by_num_fmt_id( a )
31
+ end
32
+ end
33
+ end
34
+
35
+ #returns the numFmtId value if it's available
36
+ def num_fmt_id(xstyle)
37
+ return nil unless xstyle.attributes['numFmtId']
38
+ xstyle.attributes['numFmtId'].value
39
+ end
40
+
41
+ # Finds the type we think a style is; For example, fmtId 14 is a date
42
+ # style, so this would return :date.
43
+ #
44
+ # Note, custom styles usually (are supposed to?) have a numFmtId >= 164,
45
+ # but in practice can sometimes be simply out of the usual "Any Language"
46
+ # id range that goes up to 49. For example, I have seen a numFmtId of
47
+ # 59 specified as a date. In Thai, 59 is a number format, so this seems
48
+ # like a bad idea, but we try to be flexible and just go with it.
49
+ def style_type_by_num_fmt_id(id)
50
+ return nil unless id
51
+ id = id.to_i
52
+ NumFmtMap[id] || custom_style_types[id]
53
+ end
54
+
55
+ # Map of (numFmtId >= 164) (custom styles) to our best guess at the type
56
+ # ex. {164 => :date_time}
57
+ def custom_style_types
58
+ @custom_style_types ||= begin
59
+ styles_xml_doc.css('styleSheet numFmts numFmt').inject({}) do |acc, xstyle|
60
+ index = xstyle.attributes['numFmtId'].value.to_i
61
+ value = xstyle.attributes['formatCode'].value
62
+ acc[index] = determine_custom_style_type(value)
63
+ acc
64
+ end
65
+ end
66
+ end
67
+
68
+ # This is the least deterministic part of reading xlsx files. Due to
69
+ # custom styles, you can't know for sure when a date is a date other than
70
+ # looking at its format and gessing. It's not impossible to guess right,
71
+ # though.
72
+ #
73
+ # http://stackoverflow.com/questions/4948998/determining-if-an-xlsx-cell-is-date-formatted-for-excel-2007-spreadsheets
74
+ def determine_custom_style_type(string)
75
+ return :float if string[0] == '_'
76
+ return :float if string[0] == ' 0'
77
+
78
+ # Looks for one of ymdhis outside of meta-stuff like [Red]
79
+ return :date_time if string =~ /(^|\])[^\[]*[ymdhis]/i
80
+
81
+ return :unsupported
82
+ end
83
+ end
84
+ end
85
+ end
@@ -0,0 +1,16 @@
1
+ module Crek
2
+ module Utils
3
+ def expand_to_rels_path(filepath)
4
+ filepath.sub(/(\/[^\/]+$)/, '/_rels\1.rels')
5
+ end
6
+
7
+ def file_exist?(path)
8
+ @book.files.file.exist?(path)
9
+ end
10
+
11
+ def parse_xml(xml_path)
12
+ doc = @book.files.file.open(xml_path)
13
+ Nokogiri::XML::Document.parse(doc)
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,3 @@
1
+ module Crek
2
+ VERSION = "0.1.0"
3
+ end
metadata ADDED
@@ -0,0 +1,151 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: crek
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Dibyajit
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2019-02-15 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.3'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.3'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "<"
32
+ - !ruby/object:Gem::Version
33
+ version: '11.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "<"
39
+ - !ruby/object:Gem::Version
40
+ version: '11.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: 2.13.0
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: 2.13.0
55
+ - !ruby/object:Gem::Dependency
56
+ name: pry
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: nokogiri
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: 1.6.0
76
+ type: :runtime
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: 1.6.0
83
+ - !ruby/object:Gem::Dependency
84
+ name: rubyzip
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: 1.0.0
90
+ type: :runtime
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: 1.0.0
97
+ description: Creek with image read from xlsx feature for Creek 1.1.2.
98
+ email:
99
+ - dibyajit.g@treniq.com
100
+ executables: []
101
+ extensions: []
102
+ extra_rdoc_files: []
103
+ files:
104
+ - ".gitignore"
105
+ - ".rspec"
106
+ - ".travis.yml"
107
+ - CODE_OF_CONDUCT.md
108
+ - Gemfile
109
+ - Gemfile.lock
110
+ - LICENSE.txt
111
+ - README.md
112
+ - Rakefile
113
+ - bin/console
114
+ - bin/setup
115
+ - crek.gemspec
116
+ - lib/crek.rb
117
+ - lib/crek/book.rb
118
+ - lib/crek/drawing.rb
119
+ - lib/crek/shared_strings.rb
120
+ - lib/crek/sheet.rb
121
+ - lib/crek/styles.rb
122
+ - lib/crek/styles/constants.rb
123
+ - lib/crek/styles/converter.rb
124
+ - lib/crek/styles/style_types.rb
125
+ - lib/crek/utils.rb
126
+ - lib/crek/version.rb
127
+ homepage: https://github.com/dibyajitgoswamidg/crek
128
+ licenses:
129
+ - MIT
130
+ metadata: {}
131
+ post_install_message:
132
+ rdoc_options: []
133
+ require_paths:
134
+ - lib
135
+ required_ruby_version: !ruby/object:Gem::Requirement
136
+ requirements:
137
+ - - ">="
138
+ - !ruby/object:Gem::Version
139
+ version: 2.0.0
140
+ required_rubygems_version: !ruby/object:Gem::Requirement
141
+ requirements:
142
+ - - ">="
143
+ - !ruby/object:Gem::Version
144
+ version: '0'
145
+ requirements: []
146
+ rubyforge_project:
147
+ rubygems_version: 2.7.8
148
+ signing_key:
149
+ specification_version: 4
150
+ summary: Creek with image read from xlsx feature for Creek 1.1.2.
151
+ test_files: []