repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
dinesh/mongo-memcached
|
lib/mongo_memcached/patches/_array.rb
|
<filename>lib/mongo_memcached/patches/_array.rb
class Array
alias_method :count, :size
def in_groups_of(number, fill_with = nil)
padding = (number - size % number) % number
collection = dup.concat([fill_with] * padding)
if block_given?
collection.each_slice(number) { |slice| yield(slice) }
else
[].tap do |groups|
collection.each_slice(number) { |group| groups << group }
end
end
end
def to_hash
keys_and_values_without_nils = in_groups_of(2).reject{|pair| pair[0].nil? }
hash = {}
keys_and_values_without_nils.map{|p1, p2| hash.store(p1, p2) }
hash
end
end
|
dinesh/mongo-memcached
|
lib/mongo_memcached/patches/_mongoid.rb
|
module Mongoid
module Document
include MongoMemcached
def shallow_clone
MongoMemcached::CachedDocument.new.tap do |other|
self.class.hot_fields.each{|name| other.attributes[name] = self.send(name).dup if self.class.hot?(name) }
other.id = self.id
other.klass = self.class
end
end
end
end
module Mongoid
module Contexts
class Mongo
def attribute_value_pair
criteria.selector.collect{|key, value| [key.to_s, value.to_s ] }.flatten
end
def indexed_on?(keys)
klass.indices.select{|c| c.attributes.sort == keys.collect(&:to_sym).sort }.first
end
def cached_execute selector, paginating = false
cursor = klass.collection.find(selector, process_options)
if cursor
@count = cursor.count if paginating
cursor
else
[]
end
end
protected
def advance_operators
['$all', '$exists', '$mod', '$ne', '$in', '$nin', '$nor', '$or', '$size', '$type', '$elemMatch' ]
end
def hit_or_miss index
key = index.cache_key(attribute_value_pair)
unless ( cached_entries = klass.get(key) )
_, cached_entries, hit = index.get_key_and_value_at_index(attribute_value_pair)
end
cached_entries
end
def cached_documents index
key = index.cache_key(attribute_value_pair)
cached_entries = hit_or_miss(index)
selector['_id'] = { "$nin" => cached_entries } if cached_entries
case cached_entries
when Array
if cached_entries.present?
keys = cached_entries.map{|e| index.cache_key(['_id', e]) }
cached_entries = klass.get(keys) do |missed_keys|
puts "missed => #{missed_keys.inspect}"
primary_index = indexed_on?('_id')
missed_ids = missed_keys.map{|t| t.split('_id/').last }
klass.where(:_id.in => missed_ids).entries.map do |doc|
key = primary_index.cache_key(['_id', doc.id ])
doc.shallow_clone
end
end
end
else
cached_entries = { }
end
cached_entries
end
def caching(&block)
if defined? @collection
@collection.each(&block)
else
cached_entries = {}
key = criteria.selector.keys.sort
if index = indexed_on?(key) and criteria.selector.any?{|k, v| v.class == Hash } == false
cached_entries = cached_documents(index)
cached_entries.each do |key, doc|
puts "\t>> [CACHED] #{key} : #{doc.inspect}"
yield doc if block_given?
end
selector.delete('_id')
else
cached_execute(criteria.selector).each{|doc| yield doc if block_given? }
end
end
end
end
end
end
|
dinesh/mongo-memcached
|
lib/mongo_memcached.rb
|
require 'mongo_memcached/patches/_array'
require 'mongo_memcached/patches/_symbol'
require 'mongo_memcached/membase'
require 'mongo_memcached/synchronize'
require 'mongo_memcached/index'
require 'mongo_memcached/cache_config'
Mongoid.configure do |config|
host = 'localhost'
config.master = Mongo::Connection.new.db('weigo')
config.persist_in_safe_mode = false
end
module MongoMemcached
extend ActiveSupport::Concern
module ClassMethods
def acts_as_memcached *args
_setup_for_memcached(self)
self.cache_config = CacheConfig.new( args || self.fields.keys )
end
def hot_fields
@cache_config ? @cache_config.hot_fields : []
end
def hot?(field)
self.hot_fields.include?(field)
end
def _setup_for_memcached(base)
class << base
attr_accessor :indices, :membase, :cache_config
include Membase
alias :repository :membase
end
base.class_eval do
@indices ||= []
@membase ||= Memcached.new
include Synchronize
end
end
def memcached?
respond_to?(:indices)
end
def memcached
where().cache
end
def primary_index
self.indices.select{|i| i.primary_key? }.first
end
def index_on attrs, options = { }
options.assert_valid_keys(:ttl, :order)
index = Index.new self, attrs, options || {}
self.indices.unshift( Index.new(self, attrs, options || {}) )
self.indices.sort_by{|index| index.attributes.size }
end
def cache_key(key, primary = false)
key = key.split(':').last
primary ? "#{name.downcase}/p:#{key.to_s.gsub(' ', '+')}" :
"#{name.downcase}:#{key.to_s.gsub(' ', '+')}"
end
end
end
require 'mongo_memcached/patches/_mongoid'
|
dinesh/mongo-memcached
|
lib/mongo_memcached/synchronize.rb
|
<filename>lib/mongo_memcached/synchronize.rb
module MongoMemcached
module Synchronize
def self.included base
base.class_eval do
include InstanceMethods
extend ClassMethods
end
end
module InstanceMethods
def self.included(mongo_class)
mongo_class.class_eval do
after_create :add_to_caches
after_update :update_caches
after_destroy :remove_from_caches
end
end
def add_to_caches
InstanceMethods.unfold(self.class, :add_to_caches, self)
end
def update_caches
InstanceMethods.unfold(self.class, :update_caches, self)
end
def remove_from_caches
return if new_record?
InstanceMethods.unfold(self.class, :remove_from_caches, self)
end
def expire_caches
InstanceMethods.unfold(self.class, :expire_caches, self)
end
private
def self.unfold(klass, operation, object)
klass.send(operation, object)
klass = klass.superclass
end
end
module ClassMethods
def add_to_caches(object)
indices.each { |index| index.add(object) }
end
def update_caches(object)
indices.each { |index| index.update(object) }
end
def remove_from_caches(object)
indices.each { |index| index.remove(object) }
end
def expire_caches(object)
indices.each { |index| index.delete(object) }
end
end
end
end
|
dinesh/mongo-memcached
|
mongo-memcached.gemspec
|
<filename>mongo-memcached.gemspec
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{mongo-memcached}
s.version = "0.0.1"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["dinesh"]
s.date = %q{2011-02-25}
s.description = %q{A elegent caching memchanism for mongodb with memecached backend}
s.email = %q{<EMAIL>}
s.extra_rdoc_files = [
"LICENSE.txt",
"README.rdoc"
]
s.files = [
"lib/mongo-memcached.rb",
"lib/mongo_memcached.rb",
"lib/mongo_memcached/index.rb",
"lib/mongo_memcached/membase.rb",
"lib/mongo_memcached/patches.rb",
"lib/mongo_memcached/patches/_array.rb",
"lib/mongo_memcached/patches/_mongoid.rb",
"lib/mongo_memcached/patches/_symbol.rb",
"lib/mongo_memcached/synchronize.rb"
]
s.homepage = %q{http://github.com/dinesh/mongo-memcached}
s.licenses = ["MIT"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.4.1}
s.summary = %q{A elegent write-through caching memchanism for mongodb with memecached backend}
s.test_files = [
"test/helper.rb",
"test/test_mongo-memcached.rb"
]
if s.respond_to? :specification_version then
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<memcached>, [">= 0"])
s.add_runtime_dependency(%q<mongoid>, [">= 0"])
s.add_runtime_dependency(%q<bson>, [">= 0"])
s.add_runtime_dependency(%q<bson_ext>, [">= 0"])
s.add_development_dependency(%q<shoulda>, [">= 0"])
s.add_development_dependency(%q<bundler>, ["~> 1.0.0"])
s.add_development_dependency(%q<jeweler>, ["~> 1.5.2"])
s.add_development_dependency(%q<rcov>, [">= 0"])
else
s.add_dependency(%q<memcached>, [">= 0"])
s.add_dependency(%q<mongoid>, [">= 0"])
s.add_dependency(%q<bson>, [">= 0"])
s.add_dependency(%q<bson_ext>, [">= 0"])
s.add_dependency(%q<shoulda>, [">= 0"])
s.add_dependency(%q<bundler>, ["~> 1.0.0"])
s.add_dependency(%q<jeweler>, ["~> 1.5.2"])
s.add_dependency(%q<rcov>, [">= 0"])
end
else
s.add_dependency(%q<memcached>, [">= 0"])
s.add_dependency(%q<mongoid>, [">= 0"])
s.add_dependency(%q<bson>, [">= 0"])
s.add_dependency(%q<bson_ext>, [">= 0"])
s.add_dependency(%q<shoulda>, [">= 0"])
s.add_dependency(%q<bundler>, ["~> 1.0.0"])
s.add_dependency(%q<jeweler>, ["~> 1.5.2"])
s.add_dependency(%q<rcov>, [">= 0"])
end
end
|
dinesh/mongo-memcached
|
test/run.rb
|
require 'helper'
require 'db'
require 'pp'
User.delete_all
Category.delete_all
types = ['hotel', 'nightlife', 'restaurant']
2.times do |i|
u = User.new(:name => "user_#{i}", :username => "username_#{i}", :admin => i%2, :age => i*10 )
1.times do |j|
u.categories.build(:name => 'cat_' + j.to_s , :system_type => types[j%3], :location_id => j % 20)
end
pp u
u.save
end
u = User.where(:username => 'username_0').memcached
u.each do |user|
puts user.man
puts user.age
end
|
dinesh/mongo-memcached
|
lib/mongo_memcached/index.rb
|
<filename>lib/mongo_memcached/index.rb
module MongoMemcached
class Index
attr_accessor :collection, :attributes, :options, :membase
def initialize collection, attributes, opts = { :limit => 1000 }
@collection, @attributes, @options = collection, Array(attributes), opts.update(opts)
end
def repository
collection.membase
end
def attribute_value_pairs object
attributes.inject([]){|pairs, field| pairs << [ field, object.attributes[field] ] }.flatten
end
def add_objects_to_cache pairs, objects, options = {}
if primary_key?
add_object_to_primary_key_cache(pairs, objects, options)
else
add_to_index(pairs, objects, options)
end
end
def add_object_to_primary_key_cache pairs, object, options = {}
repository.set(key = cache_key(pairs), serialize_objects(object) )
repository.set(key = primary_cache_key(pairs), object )
end
def add_to_index pairs, object, options = {}
order = options[:order] || :asc
key = cache_key(pairs)
_, cache_value, hit = get_key_and_value_at_index(pairs)
if hit
object_to_add = serialize_objects(object)
objects = (cache_value + [object_to_add]).sort do |a, b|
(a <=> b) * (order == :asc ? 1 : -1)
end.uniq
collection.set(key, objects)
end
end
def remove_from_index pairs, objects, options = {}
primary_key? ? remove_from_primary_key_index(pairs, objects, options) : remove_from_other_index(pairs, objects, options)
end
def remove_from_primary_key_index pairs, object, options = {}
key = cache_key(pairs)
repository.set(key, [])
end
def remove_from_other_index pairs, objects, options = {}
key, cache_value, _ = get_key_and_value_at_index(pairs)
end
def stalled? objects
objects = Array(objects)
objects.any?{|o| attributes.any?{|option| o.changes.has_key?(option.to_s) } }
end
def update_in_index pairs, objects, options = {}
if stalled?(objects)
primary_key? ? update_in_primary_key_index(pairs, objects, options) : update_in_other_index(pairs, objects, options)
end
end
def update_in_primary_key_index pairs, object, options = {}
key = cache_key(pairs)
repository.set(key, serialize_objects(object))
end
def update_in_other_index pairs, objects, options = {}
key, cache_value, _ = get_key_and_value_at_index(pairs)
end
def serialize_objects objects
objects = objects.collect{|doc| primary_key? ? doc.shallow_clone : doc._id }
primary_key? ? objects.first : objects
end
def append_objects key, pre_value, new_value, owerite = false
primary_key? ? new_value : ( pre_value + new_value ).uniq
end
def primary_key?
attributes.size == 1 and attributes.first == :_id
end
def cache_key key, primary = false
key = key.class == Array ? key.join('/') : key
collection.cache_key( key, primary )
end
def get_key_and_value_at_index pairs, options = {}
key, cache_hit = cache_key(pairs, options[:primary]), true
cache_value = collection.get(key, options) do
cache_hit = false
objects = collection.where(pairs.to_hash).entries
options[:primary] && primary_key? ? objects.first : serialize_objects( objects )
end
[key, cache_value, cache_hit]
end
module Commands
def add(object)
clone, pairs = object, attribute_value_pairs(object)
add_to_index(pairs, [clone], { :overwite => true } )
end
def update(object)
clone = object
update_in_index(attribute_value_pairs(object), [clone])
end
def remove(object)
remove_from_index(attribute_value_pairs(object), object)
end
def delete(object)
key = cache_key(attribute_value_pairs(object))
expire(key)
end
end
include Commands
end
end
|
dinesh/mongo-memcached
|
lib/mongo-memcached.rb
|
<gh_stars>1-10
require 'mongo_memcached'
|
dinesh/mongo-memcached
|
lib/mongo_memcached/patches/_symbol.rb
|
class Symbol
include Comparable
def <=>(other)
self.to_s <=> other.to_s
end
end
class BSON::ObjectId
include Comparable
def <=>(other)
self.to_s <=> other.to_s
end
end
|
dinesh/mongo-memcached
|
lib/mongo_memcached/patches.rb
|
require 'mongo_memcached/patches/_array'
require 'mongo_memcached/patches/_mongoid'
require 'mongo_memcached/patches/_symbol'
|
dinesh/mongo-memcached
|
test/db.rb
|
<filename>test/db.rb<gh_stars>1-10
class User
include Mongoid::Document
field :name
field :username
field :age, :type => Integer
field :admin, :type => Boolean
references_many :categories, :foreign_key => :owner_id, :dependent => :destroy, :autosave => true
acts_as_memcached :name, :username, :contacts
def contacts
User.all.collect(&:id)
end
def man
'dinesh'
end
index_on :_id, :ttl => 1.hour
index_on [:_id, :admin] , :ttl => 1.day
index_on :username
end
class Category
include Mongoid::Document
field :system_type
field :name
referenced_in :owner, :class_name => 'User'
field :location_id, :type => Integer
acts_as_memcached
index_on :_id
index_on :owner_id
index_on [:owner_id, :system_type ]
index_on [:system_type]
index_on [:system_type, :location_id]
end
module DB
def self.clear
User.delete_all
Category.delete_all
end
end
|
dinesh/mongo-memcached
|
lib/mongo_memcached/cache_config.rb
|
module MongoMemcached
class CacheConfig
attr_accessor :fields
def initialize _fields = []
@fields = Array(_fields).sort
end
def hot_fields
@fields
end
end
class CachedDocument
attr_accessor :attributes, :klass, :id, :parent
def initialize attrs = {}
@attributes = attrs
end
def _load_parent
@parent || (@parent = load_parent)
end
def method_missing sym, *args, &block
begin
if attributes.has_key?(sym)
attributes[sym]
else
args.size > 0 ? _load_parent.send(sym, args, &block) : _load_parent.send(sym)
end
rescue Exception => e
puts e.message
pp e.backtrace
super
end
end
def load_parent
if index = klass.primary_index
key = index.cache_key('_id', id)
_, primary_object, hit = index.get_key_and_value_at_index(['_id', id], { :primary => true } )
primary_object
end
end
end
end
|
jeefberkey/rspec-puppet
|
lib/rspec-puppet/coverage.rb
|
unless defined?(RSpec::Core::NullReporter)
module RSpec::Core
class NullReporter
def self.method_missing(*)
# ignore
end
private_class_method :method_missing
end
end
end
module RSpec::Puppet
class Coverage
attr_accessor :filters
class << self
extend Forwardable
def_delegators(:instance, :add, :cover!, :report!,
:filters, :add_filter, :add_from_catalog,
:results)
attr_writer :instance
def instance
@instance ||= new
end
end
def initialize
@collection = {}
@filters = ['Stage[main]', 'Class[Settings]', 'Class[main]', 'Node[default]']
end
def add(resource)
if !exists?(resource) && !filtered?(resource)
@collection[resource.to_s] = ResourceWrapper.new(resource)
end
end
def add_filter(type, title)
def capitalize_name(name)
name.split('::').map { |subtitle| subtitle.capitalize }.join('::')
end
type = capitalize_name(type)
if type == 'Class'
title = capitalize_name(title)
end
@filters << "#{type}[#{title}]"
end
# add all resources from catalog declared in module test_module
def add_from_catalog(catalog, test_module)
coverable_resources = catalog.to_a.reject { |resource| !test_module.nil? && filter_resource?(resource, test_module) }
coverable_resources.each do |resource|
add(resource)
end
end
def filtered?(resource)
filters.include?(resource.to_s)
end
def cover!(resource)
if !filtered?(resource) && (wrapper = find(resource))
wrapper.touch!
end
end
def report!(coverage_desired = nil)
report = results
puts <<-EOH.gsub(/^ {8}/, '')
Total resources: #{report[:total]}
Touched resources: #{report[:touched]}
Resource coverage: #{report[:coverage]}%
EOH
if report[:coverage] != "100.00"
puts <<-EOH.gsub(/^ {10}/, '')
Untouched resources:
#{
untouched_resources = report[:resources].reject do |_,rsrc|
rsrc[:touched]
end
untouched_resources.inject([]) do |memo, (name,_)|
memo << " #{name}"
end.sort.join("\n")
}
EOH
if coverage_desired
coverage_test(coverage_desired, report[:coverage])
end
end
end
def coverage_test(coverage_desired, coverage_actual)
if coverage_desired.is_a?(Numeric) && coverage_desired.to_f <= 100.00 && coverage_desired.to_f >= 0.0
coverage_test = RSpec.describe("Code coverage.")
coverage_results = coverage_test.example("Must be at least #{coverage_desired}% of code coverage") {
expect( coverage_actual.to_f ).to be >= coverage_desired.to_f
}
coverage_test.run(RSpec::Core::NullReporter)
passed = if coverage_results.execution_result.respond_to? :status then
coverage_results.execution_result.status == :passed
else
coverage_results.execution_result[:status] == 'passed'
end
RSpec.configuration.reporter.example_failed coverage_results unless passed
else
puts "The desired coverage must be 0 <= x <= 100, not '#{coverage_desired.inspect}'"
end
end
def results
report = {}
report[:total] = @collection.size
report[:touched] = @collection.count { |_, resource| resource.touched? }
report[:untouched] = report[:total] - report[:touched]
report[:coverage] = "%5.2f" % ((report[:touched].to_f / report[:total].to_f) * 100)
report[:resources] = Hash[*@collection.map do |name, wrapper|
[name, wrapper.to_hash]
end.flatten]
report
end
private
# Should this resource be excluded from coverage reports?
#
# The resource is not included in coverage reports if any of the conditions hold:
#
# * The resource has been explicitly filtered out.
# * Examples: autogenerated resources such as 'Stage[main]'
# * The resource is a class but does not belong to the module under test.
# * Examples: Class dependencies included from a fixture module
# * The resource was declared in a file outside of the test module or site.pp
# * Examples: Resources declared in a dependency of this module.
#
# @param resource [Puppet::Resource] The resource that may be filtered
# @param test_module [String] The name of the module under test
# @return [true, false]
def filter_resource?(resource, test_module)
if @filters.include?(resource.to_s)
return true
end
if resource.type == 'Class'
module_name = resource.title.split('::').first.downcase
if module_name != test_module
return true
end
end
if resource.file
paths = module_paths(test_module)
unless paths.any? { |path| resource.file.include?(path) }
return true
end
end
return false
end
# Find all paths that may contain testable resources for a module.
#
# @return [Array<String>]
def module_paths(test_module)
adapter = RSpec.configuration.adapter
paths = adapter.modulepath.map do |dir|
File.join(dir, test_module, 'manifests')
end
paths << adapter.manifest if adapter.manifest
paths
end
def find(resource)
@collection[resource.to_s]
end
def exists?(resource)
!find(resource).nil?
end
class ResourceWrapper
attr_reader :resource
def initialize(resource = nil)
@resource = resource
end
def to_s
@resource.to_s
end
def to_hash
{
:touched => touched?,
}
end
def touch!
@touched = true
end
def touched?
!!@touched
end
end
end
end
|
jeefberkey/rspec-puppet
|
spec/classes/relationship__titles_spec.rb
|
<filename>spec/classes/relationship__titles_spec.rb<gh_stars>0
require 'spec_helper'
describe 'relationships::titles' do
let(:facts) { {:operatingsystem => 'Debian', :kernel => 'Linux'} }
it { should compile }
it { should compile.with_all_deps }
it { should contain_file('/etc/svc') }
it { should contain_service('svc-title') }
it { should contain_file('/etc/svc').that_notifies('Service[svc-name]') }
it { should contain_file('/etc/svc').that_comes_before('Service[svc-name]') }
it { should contain_service('svc-title').that_requires('File[/etc/svc]') }
it { should contain_service('svc-title').that_subscribes_to('File[/etc/svc]') }
end
|
jeefberkey/rspec-puppet
|
spec/classes/test_windows_spec.rb
|
require 'spec_helper'
describe 'test::windows' do
let(:facts) { {:operatingsystem => 'windows' } }
it { should compile.with_all_deps }
end
|
jeefberkey/rspec-puppet
|
lib/rspec-puppet/tasks/release_test.rb
|
require 'rake'
require 'open3'
require 'json'
require 'parser/current'
task :release_test do
modules_to_test = [
'puppetlabs/puppetlabs-apt',
'puppetlabs/puppetlabs-tomcat',
'puppetlabs/puppetlabs-apache',
'puppetlabs/puppetlabs-mysql',
'puppetlabs/puppetlabs-ntp',
'puppetlabs/puppetlabs-acl',
'puppetlabs/puppetlabs-chocolatey',
'voxpupuli/puppet-archive',
'voxpupuli/puppet-collectd',
'garethr/garethr-docker',
'sensu/sensu-puppet',
'jenkinsci/puppet-jenkins',
]
Bundler.with_clean_env do
FileUtils.mkdir_p('tmp')
Dir.chdir('tmp') do
modules_to_test.each do |module_name|
puts "Testing #{module_name}..."
module_dir = File.basename(module_name)
if File.directory?(module_dir)
Dir.chdir(module_dir) do
print ' Updating repository... '
_, status = Open3.capture2e('git', 'pull', '--rebase')
if status.success?
puts 'Done'
else
puts 'FAILED'
next
end
end
else
print ' Cloning repository... '
_, status = Open3.capture2e('git', 'clone', "https://github.com/#{module_name}")
if status.success?
puts 'Done'
else
puts 'FAILED'
next
end
end
Dir.chdir(module_dir) do
print ' Installing dependencies... '
bundle_install_output, status = Open3.capture2e('bundle', 'install', '--path', 'vendor/gems')
if status.success?
puts 'Done'
else
puts 'FAILED'
puts bundle_install_output
next
end
print ' Running baseline tests... '
baseline_output, _, status = Open3.capture3({'SPEC_OPTS' => '--format json'}, 'bundle', 'exec', 'rake', 'spec')
if status.success?
puts 'Done'
else
puts 'Done (tests failed)'
end
print ' Updating Gemfile to use rspec-puppet HEAD... '
buffer = Parser::Source::Buffer.new('Gemfile')
buffer.source = File.read('Gemfile')
parser = Parser::CurrentRuby.new
ast = parser.parse(buffer)
modified_gemfile = GemfileRewrite.new.rewrite(buffer, ast)
gem_root = File.expand_path(File.join(__FILE__, '..', '..', '..', '..'))
if modified_gemfile == buffer.source
File.open('Gemfile', 'a') do |f|
f.puts "gem 'rspec-puppet', :path => '#{gem_root}'"
end
else
File.open('Gemfile', 'w') do |f|
f.puts modified_gemfile
end
end
puts 'Done'
print ' Installing dependencies... '
_, status = Open3.capture2e('bundle', 'install', '--path', 'vendor/gems')
if status.success?
puts 'Done'
else
puts "FAILED"
next
end
print ' Running tests against rspec-puppet HEAD... '
head_output, _, status = Open3.capture3({'SPEC_OPTS' => '--format json'}, 'bundle', 'exec', 'rake', 'spec')
if status.success?
puts 'Done'
else
puts 'Done (tests failed)'
end
print ' Restoring Gemfile... '
_, status = Open3.capture2e('git', 'checkout', '--', 'Gemfile')
if status.success?
puts 'Done'
else
puts 'FAILED'
end
json_regex = %r{\{(?:[^{}]|(?:\g<0>))*\}}x
baseline_results = JSON.parse(baseline_output.scan(json_regex).last)
head_results = JSON.parse(head_output.scan(json_regex).last)
if head_results['summary_line'] == baseline_results['summary_line']
puts " PASS: #{head_results['summary_line']}"
else
puts "!!FAILED: baseline:(#{baseline_results['summary_line']}) head:(#{head_results['summary_line']})"
end
end
end
end
end
end
class GemfileRewrite < Parser::Rewriter
def on_send(node)
_, method_name, *args = *node
if method_name == :gem
gem_name = args.first
if gem_name.type == :str && gem_name.children.first == 'rspec-puppet'
gem_root = File.expand_path(File.join(__FILE__, '..', '..', '..', '..'))
replace(node.location.expression, "gem 'rspec-puppet', :path => '#{gem_root}'")
end
end
super
end
end
|
emilio2601/hot-girl-summer
|
listening_history_service.rb
|
class ListeningHistoryService
def self.for(csv_file)
new(csv_file)
end
def initialize(csv_file)
@scrobbles = csv_file.map(&method(:parse_row)).compact
end
def parse_row(row_data)
artist, album, track_name, timestamp = row_data
return nil unless timestamp
dt_timestamp = DateTime.parse(timestamp)
Scrobble.new(artist, album, track_name, dt_timestamp)
end
def get_scrobbles_within(range)
@scrobbles.select do |scrobble|
range.cover? scrobble.timestamp
end
end
end
class Scrobble
attr_accessor :artist, :album, :track_name, :timestamp
def initialize(artist, album, track_name, timestamp)
@artist = artist
@album = album
@track_name = track_name
@timestamp = timestamp
end
def to_s
"#{track_name} - #{artist} at #{timestamp.iso8601}"
end
def uid
"track:#{track_name} artist:#{artist}"
end
end
|
emilio2601/hot-girl-summer
|
generate_playlist.rb
|
<gh_stars>1-10
require "csv"
require "date"
require "rspotify"
require "dotenv/load"
require "./listening_history_service.rb"
SUMMER_START = DateTime.iso8601("2021-06-01")
SUMMER_END = DateTime.iso8601("2021-09-01")
SUMMER = SUMMER_START..SUMMER_END
INCLUSION_THRESHOLD = 25
PLAYLIST_ID = "04rbVkoutryqe1riHtYWTX"
SONG_BLACKLIST = %w[4WeFxTWbIphMs0j96hH3Lx 30fGAryPIZTx0RHNtQ2QQR 5cFSGxC26QRmbWx5Zup49L 4uNxEmMsMfO7DtaLHqPXWz 4m7WHxxBQkHvhcqJw3LdSt 10bGyWxBsksEb5QN4c2Jt1 2s5Bm2Miv88YIcpDE5dqKq 63y4ZibWpnXxv7im3e5HEt 6UDwJbSKySZ4RqBl9cz2c8 7EBpervzdzoOgA1bgk1sSm 7bra7QzKZP9wmyhIZTjKT0 7nlz9iIydZFHOzOBBm6X8B 2898wbxGjsuzB16jb18cbE 4W5ujj9ZiCesGUxpHVgUyZ]
RSpotify.authenticate(ENV["SPOTIFY_CLIENT_ID"], ENV["SPOTIFY_CLIENT_SECRET"])
creds = { "token" => ENV["SPOTIFY_ACCESS_TOKEN"], "refresh_token" => ENV["SPOTIFY_REFRESH_TOKEN"] }
user = RSpotify::User.new({ "credentials" => creds, "id" => "1276652802" })
lh_data = CSV.read("data/lastfm_2021_10_3.csv")
lh_svc = ListeningHistoryService.for(lh_data)
listen_count = d = Hash.new { |h, k| h[k] = 0 }
tracks = lh_svc.get_scrobbles_within(SUMMER)
tracks.each do |t|
listen_count[t.uid] += 1
end
sp_playlist = user.playlists.select { |p| p.id == PLAYLIST_ID }.first
tracks = listen_count.sort_by { |t, c| c }.reverse.select { |t, c| c >= INCLUSION_THRESHOLD }.map do |track, count|
sp_track = RSpotify::Track.search(track).reject { |t| SONG_BLACKLIST.include? t.id }.first
puts "Adding #{sp_track.name} - #{sp_track.id}"
sp_track
end
sp_playlist.replace_tracks!(tracks)
|
netuno-org/platform
|
bundle/base/apps/demo/server/services/samples/ruby/print-template.rb
|
<reponame>netuno-org/platform
#
# EN: RETURN THE CONTENT OF TEMPLATES
# EN: When you need to render HTML and keep the code simple and organized.
# EN: Check the contents of the folder server/templates/samples.
#
# PT: RETORNA O CONTEÚDO DE TEMPLATES
# EN: Quando precisa processar HTML e manter o código simples e organizado.
# EN: Verifique o conteúdo da pasta server/templates/samples.
#
data = _val.init()
data.set("title", "Netuno")
data.set("link", "<a href=\"https://www.netuno.org\">https://www.netuno.org</a>")
header = _template.getOutput("samples/header", data)
_out.print(header)
_template.output("samples/content-1", data)
_template.output("samples/content-2", data)
footer = _template.getOutput("samples/footer")
_out.print(footer)
|
netuno-org/platform
|
bundle/base/apps/demo/server/services/samples/ruby/query-parameter.rb
|
#
# EN: EXECUTE A QUERY WITH PARAMETERS AND RETURN THE RESULT AS JSON
#
# PT: EXECUTA UMA QUERY COM PARÂMETROS E RETORNA O RESULTADO COMO JSON
#
_out.json(
_db.query(
'SELECT * FROM trabalhador '+
'WHERE id = ?::int AND nome like \'%\' || ?::varchar || \'%\' '+
'ORDER BY nome',
[
_req['id'],
_req['name']
]
)
)
|
netuno-org/platform
|
bundle/base/apps/demo/server/services/samples/ruby/query-result.rb
|
<filename>bundle/base/apps/demo/server/services/samples/ruby/query-result.rb<gh_stars>10-100
#
# EN: EXECUTE A QUERY AND RETURN THE RESULT AS JSON
#
# PT: EXECUTA UMA QUERY E RETORNA O RESULTADO COMO JSON
#
_out.json(
_db.query("SELECT uid, nome FROM trabalhador WHERE active = true")
)
|
netuno-org/platform
|
bundle/base/apps/demo/server/services/samples/ruby/user.rb
|
<filename>bundle/base/apps/demo/server/services/samples/ruby/user.rb
#
# EN: USER
# EN: Show information about the user logged.
#
# PT: UTILIZADOR
# PT: Apresenta a informação do utilizador logado.
#
data = _val.init()
data.set('title', 'This is your user data...')
data.set('id', _user.id)
data.set('name', _user.name)
data.set('code', _user.code)
data.set('full', _user.data())
_template.output('samples/identity', data)
|
netuno-org/platform
|
bundle/base/apps/demo/server/services/samples/ruby/mail-send.rb
|
#
# EN: MAIL SEND
# EN: Example of how to send email using a Google/GMail account.
# EN: Replace ***** with their account information.
# EN: You must set your mail configuration in config/_[environment].json, like:
#
# PT: ENVIAR E-MAIL
# PT: Exemplo de como enviar e-mail utilizando uma conta Google/GMail.
# PT: Troque os ***** pelas informações da respectivas da conta.
# PT: Deve definir a sua configuração de mail em config/_[ambiente].json, como:
#
# {
# ...
# "smtp": {
# "default": {
# "enabled": true,
# "host": "smtp.gmail.com",
# "port": 465,
# "ssl": true,
# "username": "*****<EMAIL>",
# "password": "*****"
# }
# }
# }
#
smtp = _smtp.init()
smtp.to = "*****<EMAIL>"
smtp.from = "*****<EMAIL>"
smtp.subject = "Test from Netuno"
smtp.text = "Did you receive this email?"
smtp.html = "<div>"
smtp.html << "<img src=\"cid:logo\" width=\"200\" />"
smtp.html << "<p>Did you receive this email?</p>"
smtp.html << "</div>"
smtp.attachment(
"logo.png",
"image/png",
_storage.filesystem("server", "samples/mail", "logo.png").file(),
"logo"
)
if (smtp.enabled)
smtp.send()
_out.println("<h2>Mail sent...</h2>")
else
_out.println("<h2>The SMTP configuration is disabled!</h2>")
_out.println("<p>Please define your configurations and enable it.</p>")
end
|
netuno-org/platform
|
bundle/base/apps/demo/server/services/samples/ruby/export-pdf.rb
|
#
# EN: Export PDF
# EN: Generates a PDF file in realtime showing some kind of content features.
#
# PT: Export PDF
# PT: Gera um ficheiro PDF em tempo real mostrando alguns tipos de recursos de conteúdo.
#
_header.contentType('pdf')
pdfDocument = _pdf.newDocument(_pdf.pageSize('A4'));
viksiScript = _pdf.font(_storage.filesystem('server', 'samples/export-pdf', 'viksi-script.ttf'), true);
helvetica = _pdf.font('helvetica');
helveticaBold = _pdf.font('helvetica-bold');
helveticaBoldOblique = _pdf.font('helvetica-boldoblique');
helveticaOblique = _pdf.font('helvetica-oblique');
pdfDocument.add(
_pdf.image(_storage.filesystem('server', 'samples/export-pdf', 'logo.png'))
.scaleAbsolute(120, 36)
)
pdfDocument.add(
_pdf.paragraph('My Custom Font!')
.setFixedPosition(250, 770, 350)
.setFont(viksiScript)
.setFontSize(30)
.setFontColor(_pdf.color("#1abc9c"))
)
pdfDocument.add(
_pdf.paragraph('Helvetica!')
.setFixedPosition(37, 730, 100)
.setFont(helvetica)
.setFontSize(15)
)
pdfDocument.add(
_pdf.paragraph('Helvetica Bold!')
.setFixedPosition(130, 730, 150)
.setFont(helveticaBold)
.setFontSize(15)
)
pdfDocument.add(
_pdf.paragraph('Helvetica Bold Oblique!')
.setFixedPosition(260, 730, 200)
.setFont(helveticaBoldOblique)
.setFontSize(15)
)
pdfDocument.add(
_pdf.paragraph('Helvetica Oblique!')
.setFixedPosition(450, 730, 200)
.setFont(helveticaOblique)
.setFontSize(15)
)
pdfDocument.add(
_pdf.paragraph('\n\nTable with flexible columns:\n')
.setFont(helvetica)
.setFontSize(15)
)
pdfDocument.add(
_pdf.table(3)
.addCell(
_pdf.cell()
.add(
_pdf.paragraph('Person')
.setFont(helvetica)
.setFontSize(10)
)
.setBorder(_pdf.border('solid', 2))
.setBackgroundColor(_pdf.colorRGB(1, 0, 0))
)
.addCell(
_pdf.cell()
.add(
_pdf.paragraph('Age')
.setFont(helvetica)
.setFontSize(10)
)
.setBorder(_pdf.border('solid', 2))
.setBackgroundColor(_pdf.color('cyan'))
)
.addCell(
_pdf.cell()
.add(
_pdf.paragraph('Hobby')
.setFont(helvetica)
.setFontSize(10)
)
.setBorder(_pdf.border('solid', 2))
.setBackgroundColor(_pdf.colorCMYK(0.2, 0.4, 0.4, 0.1))
)
.addCell(
_pdf.cell()
.add(
_pdf.paragraph('John')
.setFont(helvetica)
.setFontSize(10)
)
)
.addCell(
_pdf.cell()
.add(
_pdf.paragraph('16')
.setFont(helvetica)
.setFontSize(10)
)
)
.addCell(
_pdf.cell()
.add(
_pdf.paragraph('Boxing')
.setFont(helvetica)
.setFontSize(10)
)
)
.addCell(
_pdf.cell()
.add(
_pdf.paragraph('Nicole')
.setFont(helvetica)
.setFontSize(10)
)
)
.addCell(
_pdf.cell()
.add(
_pdf.paragraph('24')
.setFont(helvetica)
.setFontSize(10)
.setFontColor(_pdf.color('#fff'))
)
.setBackgroundColor(_pdf.colorGray(0.5))
)
.addCell(
_pdf.cell()
.add(
_pdf.paragraph('Basketball')
.setFont(helvetica)
.setFontSize(10)
)
)
.addCell(
_pdf.cell()
.add(
_pdf.paragraph('Clair')
.setFont(helvetica)
.setFontSize(10)
)
)
.addCell(
_pdf.cell()
.add(
_pdf.paragraph('20')
.setFont(helvetica)
.setFontSize(10)
)
)
.addCell(
_pdf.cell()
.add(
_pdf.paragraph('Surf')
.setFont(helvetica)
.setFontSize(10)
)
)
)
pdfDocument.add(
_pdf.paragraph('\nTable with fixed columns width:\n')
.setFont(helvetica)
.setFontSize(15)
)
pdfDocument.add(
_pdf.table([150, 150])
.addCell(
_pdf.cell()
.add(
_pdf.paragraph('Cell 1')
.setFont(helvetica)
.setFontSize(10)
)
.setBorderTop(_pdf.border('dotted', 1))
)
.addCell(
_pdf.cell()
.add(
_pdf.paragraph('Cell 2')
.setFont(helvetica)
.setFontSize(10)
)
.setBorderTop(_pdf.border('double', 2))
.setBorderRight(_pdf.border('round-dots', 2))
)
.addCell(
_pdf.cell()
.add(
_pdf.paragraph('Cell 3')
.setFont(helvetica)
.setFontSize(10)
)
.setBorderLeft(_pdf.border('no-border'))
)
.addCell(
_pdf.cell()
.add(
_pdf.paragraph('Cell 4')
.setFont(helvetica)
.setFontSize(10)
)
.setBorderBottom(_pdf.border('dashed', 2))
.setBorderRight(_pdf.border(_pdf.colorRGB(1, 0, 0), 'solid', 1))
)
)
pdfDocument.add(
_pdf.areaBreak()
)
pdfDocument.add(
_pdf.paragraph('My Second Page!')
.setFixedPosition(50, 770, 350)
.setFont(viksiScript)
.setFontSize(30)
.setFontColor(_pdf.color("#d28809"))
)
pdfDocument.close()
|
netuno-org/platform
|
bundle/base/apps/demo/server/services/samples/ruby/uid.rb
|
#
# EN: UID / GUID
# EN: Generates an UID/GUID, a random unique identifier string.
#
# PT: UID / GUID
# PT: Gera um UID/GUID, uma string aleatório de identificação única.
#
_out.println(_uid.generate())
|
netuno-org/platform
|
bundle/base/apps/demo/server/services/samples/ruby/export-excel.rb
|
#
# EN: Export EXCEL
# EN: Generates an Excel file in real time showing how to inject data,
# EN: use formulas, and apply graphic styles.
#
# PT: Export EXCEL
# PT: Gera um ficheiro Excel em tempo real mostrando como injetar dados,
# PT: utilizar fórmulas e aplicar estilos gráficos.
#
excel = _xls.create()
fontTitle = excel.workbook.createFont()
fontTitle.setBold(true)
fontTitle.setFontHeightInPoints(14)
fontTitle.setColor(_xls.color('yellow'))
fontTotal = excel.workbook.createFont()
fontTotal.setBold(true)
fontTotal.setFontHeightInPoints(12)
fontTotal.setColor(_xls.color('grey-50-percent'))
styleHeader = excel.workbook.createCellStyle()
styleHeader.setFillPattern(_xls.fillPattern('solid-foreground'))
styleHeader.setFillBackgroundColor(_xls.color('black'))
styleHeader.setAlignment(_xls.horizontalAlignment('center'))
styleHeader.setFont(fontTitle);
styleData = excel.workbook.createCellStyle()
styleData.setBorderBottom(_xls.borderStyle('thin'))
styleData.setBorderTop(_xls.borderStyle('thin'))
styleData.setBorderLeft(_xls.borderStyle('thin'))
styleData.setBorderRight(_xls.borderStyle('thin'))
styleTotal = excel.workbook.createCellStyle()
styleTotal.setBorderBottom(_xls.borderStyle('thin'))
styleTotal.setBorderTop(_xls.borderStyle('thin'))
styleTotal.setBorderLeft(_xls.borderStyle('thin'))
styleTotal.setBorderRight(_xls.borderStyle('thin'))
styleTotal.setTopBorderColor(_xls.color('red'))
styleTotal.setBottomBorderColor(_xls.color('blue'))
styleTotal.setLeftBorderColor(_xls.color('pink'))
styleTotal.setRightBorderColor(_xls.color('orange'))
styleTotal.setAlignment(_xls.horizontalAlignment('center'))
styleTotal.setFont(fontTotal);
excel.insertPicture(
_storage.filesystem('server', 'samples/export-excel', 'logo.png'),
1, 1
).resize(2.3)
excel.sheet.addMergedRegion(_xls.cellRangeAddress(1, 3, 1, 3))
dataTitle = [
{
value: 'Name',
style: styleHeader
},
{
value: 'Age',
style: styleHeader
},
{
value: 'Weight',
style: styleHeader
}
]
data = [
[
{
value: 'Briana',
style: styleData
},
{
value: 24,
style: styleData
},
{
value: 73.2,
style: styleData
}
], [
{
value: 'Kelly',
style: styleData
},
{
value: 27,
style: styleData
},
{
value: 79.5,
style: styleData
}
], [
{
value: 'Peter',
style: styleData
},
{
value: 28,
style: styleData
},
{
value: 84.9,
style: styleData
}
],[
{
value: 'Simon',
style: styleData
},
{
value: 21,
style: styleData
},
{
value: 68.3,
style: styleData
}
]
]
dataResult = [
{
value: 'Result',
style: styleTotal
},
{
formula: 'ROUND(SUM(C8:C11)/COUNT(C8:C11), 2)',
style: styleTotal
},
{
formula: 'ROUND(SUM(D8:D11)/COUNT(D8:D11), 2)',
style: styleTotal
}
]
endPosition = excel.addDataTable(6, 1, dataTitle)
endPosition = excel.addDataTable(endPosition.row, 1, data)
endPosition = excel.addDataTable(endPosition.row, 1, dataResult)
endPosition = excel.addDataTable(6, endPosition.col + 2, dataTitle, true)
endPosition = excel.addDataTable(6, endPosition.col, data, true)
endPosition = excel.addDataTable(6, endPosition.col, dataResult, true)
excel.output('test.xls')
|
netuno-org/platform
|
bundle/base/apps/demo/server/services/samples/ruby/print-lines.rb
|
<reponame>netuno-org/platform<gh_stars>10-100
#
# EN: RETURN LINES AS TEXT
#
# PT: RETORNA LINHAS COMO TEXTO
#
_header.contentType("text/plain")
_out.println("line number: 1")
_out.print("line number: ")
_out.print(2)
_out.println()
|
netuno-org/platform
|
bundle/base/apps/demo/server/services/samples/ruby/group.rb
|
#
# EN: GROUP
# EN: Show information about the group of user logged.
#
# PT: GRUPO
# PT: Apresenta a informação do grupo do utilizador logado.
#
data = _val.init()
data.set('title', 'This is your group...')
data.set('id', _group.id)
data.set('name', _group.name)
data.set('code', _group.code)
data.set('full', _group.data())
_template.output('samples/identity', data)
|
netuno-org/platform
|
bundle/base/apps/demo/server/services/samples/ruby/query-interaction.rb
|
<gh_stars>10-100
#
# EN: EXECUTE A QUERY WITH PARAMETER AND INTERACTION TO RESULT AS JSON
#
# PT: EXECUTA UMA QUERY COM PARÂMETROS E INTERAGE PARA RESULTAR COMO JSON
#
rows = _db.query(
"SELECT * FROM trabalhador "+
"WHERE id > ?::int AND active = true "+
"ORDER BY nome",
[ _req.getInt("id") ]
)
list = _val.init()
rows.each do|it|
item = _val.init()
item.set("id", it.getInt("id"))
item.set("nome", it.getString("nome"))
list.push(item)
end
_out.json(list)
|
netuno-org/platform
|
bundle/base/apps/demo/server/services/samples/ruby/db.rb
|
<filename>bundle/base/apps/demo/server/services/samples/ruby/db.rb<gh_stars>10-100
#
# EN: Database Operations
# EN: Here you will found how simple is to manage database records.
#
# PT: Operações de Base de Dados
# PT: Aqui vai encontrará como é simples gerir os registos em dados na base.
#
#
# INSERT
#
_out.println('<h4>Insert</h4>')
id = _db.insert(
"trabalhador",
{
nome: "<NAME>"
}
)
_out.println("<p>Id: "+ id +"</p>")
_out.println("<pre>")
_out.println(
_db.get("trabalhador", id).toJSON()
)
_out.println("</pre>")
#
# UPDATE
#
_out.println('<h4>Update</h4>')
rows = _db.update(
"trabalhador", id,
{
nome: "<NAME>"
}
)
_out.println("<p>Id: "+ id +"</p>")
_out.println("<pre>")
_out.println(
_db.get("trabalhador", id).toJSON()
)
_out.println("</pre>")
#
# DELETE
#
if (rows == 1) {
_out.println('<h4>Delete</h4>')
_db.delete("trabalhador", id)
_out.println("<p>Id: "+ id +"</p>")
}
#
# INSERT LIST
#
_out.println('<h4>Insert List</h4>')
ids = _db.insert(
"trabalhador", [
{
nome: "<NAME>"
},
{
nome: "<NAME>"
}
]
)
_out.println("<ul>")
for each (var id in ids) {
_out.print("<li>"+ id +"</li>")
}
_out.println("</ul>")
#
# UPDATE LIST
#
_out.println('<h4>Update List</h4>')
records = []
for each (var id in ids) {
records.push({
id: id,
nome: "Trabalhador "+ id
})
}
updates = _db.update(
"trabalhador", records
)
_out.println("<ul>")
for each (var result in updates) {
_out.print("<li>"+ result +"</li>")
}
_out.println("</ul>")
#
# DELETE LIST
#
_out.println('<h4>Delete List</h4>')
deletes = _db.delete(
"trabalhador", records
)
_out.println("<ul>")
for each (var result in deletes) {
_out.print("<li>"+ result +"</li>")
}
_out.println("</ul>")
|
Radanisk/writeexcel
|
examples/properties.rb
|
<filename>examples/properties.rb
#!/usr/bin/ruby
# -*- coding: utf-8 -*-
##############################################################################
#
# An example of adding document properties to a WriteExcel file.
#
# reverse('©'), August 2008, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
workbook = WriteExcel.new('properties.xls')
worksheet = workbook.add_worksheet
workbook.set_properties(
:title => 'This is an example spreadsheet',
:subject => 'With document properties',
:author => '<NAME>',
:manager => '<NAME>',
:company => 'Rubygem',
:category => 'Example spreadsheets',
:keywords => 'Sample, Example, Properties',
:comments => 'Created with Ruby and WriteExcel'
)
worksheet.set_column('A:A', 50)
worksheet.write('A1', 'Select File->Properties to see the file properties')
workbook.close
|
Radanisk/writeexcel
|
lib/writeexcel/write_file.rb
|
<filename>lib/writeexcel/write_file.rb
# -*- coding: utf-8 -*-
class WriteFile
def initialize
@data = ''
@datasize = 0
@limit = 8224
# Open a tmp file to store the majority of the Worksheet data. If this fails,
# for example due to write permissions, store the data in memory. This can be
# slow for large files.
@filehandle = Tempfile.new('writeexcel')
@filehandle.binmode
# failed. store temporary data in memory.
@using_tmpfile = @filehandle ? true : false
end
###############################################################################
#
# _prepend($data)
#
# General storage function
#
def prepend(*args)
data = join_data(args)
@data = data + @data
data
end
###############################################################################
#
# _append($data)
#
# General storage function
#
def append(*args)
data = join_data(args)
if @using_tmpfile
@filehandle.write(data)
else
@data += data
end
data
end
private
def join_data(args)
data =
ruby_18 { args.join } ||
ruby_19 { args.compact.collect{ |arg| arg.dup.force_encoding('ASCII-8BIT') }.join }
# Add CONTINUE records if necessary
data = add_continue(data) if data.bytesize > @limit
@datasize += data.bytesize
data
end
end
|
Radanisk/writeexcel
|
examples/merge3.rb
|
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
###############################################################################
#
# Example of how to use WriteExcel to write a hyperlink in a
# merged cell. There are two options write_url_range() with a standard merge
# format or merge_range().
#
# reverse('©'), September 2002, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
# Create a new workbook and add a worksheet
workbook = WriteExcel.new("merge3.xls")
worksheet = workbook.add_worksheet()
# Increase the cell size of the merged cells to highlight the formatting.
[1, 3,6,7].each { |row| worksheet.set_row(row, 30) }
worksheet.set_column('B:D', 20)
###############################################################################
#
# Example 1: Merge cells containing a hyperlink using write_url_range()
# and the standard Excel 5+ merge property.
#
format1 = workbook.add_format(
:center_across => 1,
:border => 1,
:underline => 1,
:color => 'blue'
)
# Write the cells to be merged
worksheet.write_url_range('B2:D2', 'http://www.perl.com', format1)
worksheet.write_blank('C2', format1)
worksheet.write_blank('D2', format1)
###############################################################################
#
# Example 2: Merge cells containing a hyperlink using merge_range().
#
format2 = workbook.add_format(
:border => 1,
:underline => 1,
:color => 'blue',
:align => 'center',
:valign => 'vcenter'
)
# Merge 3 cells
worksheet.merge_range('B4:D4', 'http://www.perl.com', format2)
# Merge 3 cells over two rows
worksheet.merge_range('B7:D8', 'http://www.perl.com', format2)
workbook.close
|
Radanisk/writeexcel
|
lib/writeexcel/worksheets.rb
|
<filename>lib/writeexcel/worksheets.rb<gh_stars>10-100
class Workbook < BIFFWriter
require 'writeexcel/properties'
require 'writeexcel/helper'
class Worksheets < Array
attr_accessor :activesheet
attr_writer :firstsheet
def initialize
@activesheet = nil
end
def activesheet_index
index(@activesheet)
end
def firstsheet_index
index(@firstsheet) || 0
end
def selected_count
self.select { |sheet| sheet.selected? }.size
end
end
end
|
Radanisk/writeexcel
|
examples/hyperlink.rb
|
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
###############################################################################
#
# Example of how to use the WriteExcel module to write hyperlinks
#
# See also hyperlink2.pl for worksheet URL examples.
#
# reverse('©'), March 2001, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
# Create a new workbook and add a worksheet
workbook = WriteExcel.new("hyperlink.xls")
worksheet = workbook.add_worksheet('Hyperlinks')
# Format the first column
worksheet.set_column('A:A', 30)
worksheet.set_selection('B1')
# Add a sample format
format = workbook.add_format
format.set_size(12)
format.set_bold
format.set_color('red')
format.set_underline
# Write some hyperlinks
worksheet.write('A1', 'http://www.perl.com/' )
worksheet.write('A3', 'http://www.perl.com/', 'Perl home' )
worksheet.write('A5', 'http://www.perl.com/', nil, format)
worksheet.write('A7', 'mailto:<EMAIL>', 'Mail me')
# Write a URL that isn't a hyperlink
worksheet.write_string('A9', 'http://www.perl.com/')
workbook.close
|
Radanisk/writeexcel
|
examples/chart_stock.rb
|
<reponame>Radanisk/writeexcel
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
#
###############################################################################
#
# A simple demo of Stock charts in Spreadsheet::WriteExcel.
#
# reverse('©'), January 2010, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
workbook = WriteExcel.new('chart_stock.xls')
worksheet = workbook.add_worksheet
###############################################################################
#
# Set up the data worksheet that the charts will refer to. We read the example
# data from the __DATA__ section at the end of the file. This simulates
# reading the data from a database or other source.
#
# The default Excel Stock chart is an Open-High-Low-Close chart. Therefore
# we will need data for each of those series.
#
# The layout of the __DATA__ section is similar to the layout of the worksheet.
#
# Add some formats.
bold = workbook.add_format(:bold => 1)
date_format = workbook.add_format(:num_format => 'dd/mm/yyyy')
# Increase the width of the column used for date to make it clearer.
worksheet.set_column('A:A', 12)
stock_data = [
%w(Date Open High Low Close),
['2009-08-19', 100.00, 104.06, 95.96, 100.34],
['2009-08-20', 101.01, 109.08, 100.50, 108.31],
['2009-08-23', 110.75, 113.48, 109.05, 109.40],
['2009-08-24', 111.24, 111.60, 103.57, 104.87],
['2009-08-25', 104.96, 108.00, 103.88, 106.00],
['2009-08-26', 104.95, 107.95, 104.66, 107.91],
['2009-08-27', 108.10, 108.62, 105.69, 106.15],
['2009-08-30', 105.28, 105.49, 102.01, 102.01],
['2009-08-31', 102.30, 103.71, 102.16, 102.37]
]
# Write the data to the worksheet.
row = 0
col = 0
headers = stock_data.shift
worksheet.write(row, col, headers, bold)
row += 1
stock_data.each do |data|
date = data.shift
worksheet.write(row, col, date, date_format)
worksheet.write(row, col + 1, data)
row += 1
end
###############################################################################
#
# Example 1. A default Open-High-Low-Close chart with series names, axes labels
# and a title.
#
chart1 = workbook.add_chart(:type => 'Chart::Stock')
# Add a series for each of the Open-High-Low-Close columns. The categories are
# the dates in the first column.
chart1.add_series(
:categories => '=Sheet1!$A$2:$A$10',
:values => '=Sheet1!$B$2:$B$10',
:name => 'Open'
)
chart1.add_series(
:categories => '=Sheet1!$A$2:$A$10',
:values => '=Sheet1!$C$2:$C$10',
:name => 'High'
)
chart1.add_series(
:categories => '=Sheet1!$A$2:$A$10',
:values => '=Sheet1!$D$2:$D$10',
:name => 'Low'
)
chart1.add_series(
:categories => '=Sheet1!$A$2:$A$10',
:values => '=Sheet1!$E$2:$E$10',
:name => 'Close'
)
# Add a chart title and axes labels.
chart1.set_title(:name => 'Open-High-Low-Close')
chart1.set_x_axis(:name => 'Date')
chart1.set_y_axis(:name => 'Share price')
###############################################################################
#
# Example 2. Same as the previous as an embedded chart.
#
chart2 = workbook.add_chart(:type => 'Chart::Stock', :embedded => 1)
# Add a series for each of the Open-High-Low-Close columns. The categories are
# the dates in the first column.
chart2.add_series(
:categories => '=Sheet1!$A$2:$A$10',
:values => '=Sheet1!$B$2:$B$10',
:name => 'Open'
)
chart2.add_series(
:categories => '=Sheet1!$A$2:$A$10',
:values => '=Sheet1!$C$2:$C$10',
:name => 'High'
)
chart2.add_series(
:categories => '=Sheet1!$A$2:$A$10',
:values => '=Sheet1!$D$2:$D$10',
:name => 'Low'
)
chart2.add_series(
:categories => '=Sheet1!$A$2:$A$10',
:values => '=Sheet1!$E$2:$E$10',
:name => 'Close'
)
# Add a chart title and axes labels.
chart2.set_title(:name => 'Open-High-Low-Close')
chart2.set_x_axis(:name => 'Date')
chart2.set_y_axis(:name => 'Share price')
# Insert the chart into the main worksheet.
worksheet.insert_chart('G2', chart2)
# File save
workbook.close
|
Radanisk/writeexcel
|
test/test_24_txo.rb
|
# -*- coding: utf-8 -*-
##########################################################################
# test_24_txo.rb
#
# Tests for some of the internal method used to write the NOTE record that
# is used in cell comments.
#
# reverse('©'), September 2005, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
#########################################################################
require 'helper'
require 'stringio'
class TC_txo < Test::Unit::TestCase
def setup
@workbook = WriteExcel.new(StringIO.new)
@worksheet = @workbook.add_worksheet
end
def teardown
if @workbook.instance_variable_get(:@filehandle)
@workbook.instance_variable_get(:@filehandle).close(true)
end
if @worksheet.instance_variable_get(:@filehandle)
@worksheet.instance_variable_get(:@filehandle).close(true)
end
end
def test_txo
string = 'aaa'
comment = Writeexcel::Worksheet::Comment.new(@worksheet, 1, 1, ' ')
caption = " \t_store_txo()"
target = %w(
B6 01 12 00 12 02 00 00 00 00 00 00 00 00 03 00
10 00 00 00 00 00
).join(' ')
result = unpack_record(comment.__send__("store_txo", string.length))
assert_equal(target, result, caption)
end
def test_first_continue_record_after_txo
string = 'aaa'
comment = Writeexcel::Worksheet::Comment.new(@worksheet, 1, 1, ' ')
caption = " \t_store_txo_continue_1()"
target = %w(
3C 00 04 00 00 61 61 61
).join(' ')
result = unpack_record(comment.__send__("store_txo_continue_1", string))
assert_equal(target, result, caption)
end
def test_second_continue_record_after_txo
string = 'aaa'
comment = Writeexcel::Worksheet::Comment.new(@worksheet, 1, 1, ' ')
caption = " \t_store_txo_continue_2()"
target = %w(
3C 00 10 00 00 00 00 00 00 00 00 00 03 00 00 00
00 00 00 00
).join(' ')
formats = [
[0, 0],
[string.length, 0]
]
result = unpack_record(comment.__send__("store_txo_continue_2", formats))
assert_equal(target, result, caption)
end
end
|
Radanisk/writeexcel
|
lib/writeexcel/convert_date_time.rb
|
# -*- encoding: utf-8 -*-
module ConvertDateTime
#
# The function takes a date and time in ISO8601 "yyyy-mm-ddThh:mm:ss.ss" format
# and converts it to a decimal number representing a valid Excel date.
#
# Dates and times in Excel are represented by real numbers. The integer part of
# the number stores the number of days since the epoch and the fractional part
# stores the percentage of the day in seconds. The epoch can be either 1900 or
# 1904.
#
# Parameter: Date and time string in one of the following formats:
# yyyy-mm-ddThh:mm:ss.ss # Standard
# yyyy-mm-ddT # Date only
# Thh:mm:ss.ss # Time only
#
# Returns:
# A decimal number representing a valid Excel date, or
# undef if the date is invalid.
#
def convert_date_time(date_time_string, date_1904 = false) #:nodoc:
date_time = date_time_string.sub(/^\s+/, '').sub(/\s+$/, '').sub(/Z$/, '')
# Check for invalid date char.
return nil if date_time =~ /[^0-9T:\-\.Z]/
# Check for "T" after date or before time.
return nil unless date_time =~ /\dT|T\d/
seconds = 0 # Time expressed as fraction of 24h hours in seconds
# Split into date and time.
date, time = date_time.split(/T/)
# We allow the time portion of the input DateTime to be optional.
if time
# Match hh:mm:ss.sss+ where the seconds are optional
if time =~ /^(\d\d):(\d\d)(:(\d\d(\.\d+)?))?/
hour = $1.to_i
min = $2.to_i
sec = $4.to_f || 0
else
return nil # Not a valid time format.
end
# Some boundary checks
return nil if hour >= 24
return nil if min >= 60
return nil if sec >= 60
# Excel expresses seconds as a fraction of the number in 24 hours.
seconds = (hour * 60* 60 + min * 60 + sec) / (24.0 * 60 * 60)
end
# We allow the date portion of the input DateTime to be optional.
return seconds if date == ''
# Match date as yyyy-mm-dd.
if date =~ /^(\d\d\d\d)-(\d\d)-(\d\d)$/
year = $1.to_i
month = $2.to_i
day = $3.to_i
else
return nil # Not a valid date format.
end
# Set the epoch as 1900 or 1904. Defaults to 1900.
# Special cases for Excel.
unless date_1904
return seconds if date == '1899-12-31' # Excel 1900 epoch
return seconds if date == '1900-01-00' # Excel 1900 epoch
return 60 + seconds if date == '1900-02-29' # Excel false leapday
end
# We calculate the date by calculating the number of days since the epoch
# and adjust for the number of leap days. We calculate the number of leap
# days by normalising the year in relation to the epoch. Thus the year 2000
# becomes 100 for 4 and 100 year leapdays and 400 for 400 year leapdays.
#
epoch = date_1904 ? 1904 : 1900
offset = date_1904 ? 4 : 0
norm = 300
range = year -epoch
# Set month days and check for leap year.
mdays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
leap = 0
leap = 1 if year % 4 == 0 && year % 100 != 0 || year % 400 == 0
mdays[1] = 29 if leap != 0
# Some boundary checks
return nil if year < epoch or year > 9999
return nil if month < 1 or month > 12
return nil if day < 1 or day > mdays[month -1]
# Accumulate the number of days since the epoch.
days = mdays[0, month - 1].inject(day) {|result, mday| result + mday} # days from 1, Jan
days += range *365 # Add days for past years
days += ((range) / 4) # Add leapdays
days -= ((range + offset) /100) # Subtract 100 year leapdays
days += ((range + offset + norm)/400) # Add 400 year leapdays
days -= leap # Already counted above
# Adjust for Excel erroneously treating 1900 as a leap year.
days += 1 if !date_1904 and days > 59
days + seconds
end
end
|
Radanisk/writeexcel
|
examples/password_protection.rb
|
<gh_stars>10-100
require 'writeexcel'
workbook = WriteExcel.new('password_protection.xls')
worksheet = workbook.add_worksheet
# Create some format objects
locked = workbook.add_format(:locked => 1)
unlocked = workbook.add_format(:locked => 0)
hidden = workbook.add_format(:hidden => 1)
# Format the columns
worksheet.set_column('A:A', 42)
worksheet.set_selection('B3:B3')
# Protect the worksheet
worksheet.protect('password')
# Examples of cell locking and hiding
worksheet.write('A1', 'Cell B1 is locked. It cannot be edited.')
worksheet.write('B1', '=1+2', locked)
worksheet.write('A2', 'Cell B2 is unlocked. It can be edited.')
worksheet.write('B2', '=1+2', unlocked)
worksheet.write('A3', "Cell B3 is hidden. The formula isn't visible.")
worksheet.write('B3', '=1+2', hidden)
worksheet.write('A5', 'Use Menu->Tools->Protection->Unprotect Sheet')
worksheet.write('A6', 'to remove the worksheet protection. ')
worksheet.write('A7', 'The password is "password". ')
workbook.close
|
Radanisk/writeexcel
|
test/test_big_workbook.rb
|
<filename>test/test_big_workbook.rb
# -*- coding: utf-8 -*-
require 'helper'
require 'stringio'
class TC_BigWorkbook < Test::Unit::TestCase
def test_big_workbook_saves
workbook = Workbook.new(StringIO.new)
4.times do
worksheet = workbook.add_worksheet
500.times {|i| worksheet.write_row(i, 0, [rand(10000).to_s])}
end
assert_nothing_raised { workbook.close }
end
end
|
Radanisk/writeexcel
|
examples/chart_legend.rb
|
#!/usr/bin/ruby
# -*- coding: utf-8 -*-
#
###############################################################################
#
# Chart legend visible/invisible sample.
#
# copyright 2013 <NAME>, <EMAIL>
#
require 'writeexcel'
# Create a new workbook called chart_legend.xls and add a worksheet
workbook = WriteExcel.new('chart_legend.xls')
worksheet = workbook.add_worksheet
bold = workbook.add_format(:bold => 1)
# Add the worksheet data that the charts will refer to.
headings = [ 'Category', 'Values 1', 'Values 2' ]
data = [
[ 2, 3, 4, 5, 6, 7 ],
[ 1, 4, 5, 2, 1, 5 ],
[ 3, 6, 7, 5, 4, 3 ]
]
worksheet.write('A1', headings, bold)
worksheet.write('A2', data)
#
# chart with legend
#
chart1 = workbook.add_chart(:type => 'Chart::Area', :embedded => 1)
chart1.add_series( :values => '=Sheet1!$B$2:$B$7' )
worksheet.insert_chart('E2', chart1)
#
# chart without legend
#
chart2 = workbook.add_chart(:type => 'Chart::Area', :embedded => 1)
chart2.add_series( :values => '=Sheet1!$B$2:$B$7' )
chart2.set_legend(:position => 'none')
worksheet.insert_chart('E27', chart2)
workbook.close
|
Radanisk/writeexcel
|
test/test_compatibility.rb
|
<reponame>Radanisk/writeexcel
# -*- coding: utf-8 -*-
require 'helper'
require 'nkf'
class TC_Compatibility < Test::Unit::TestCase
def test_ord
a = 'a'
abc = 'abc'
assert_equal(97, a.ord, "#{a}.ord faild\n")
assert_equal(97, abc.ord, "#{abc}.ord faild\n")
end
end
|
Radanisk/writeexcel
|
test/test_26_autofilter.rb
|
<reponame>Radanisk/writeexcel
# -*- coding: utf-8 -*-
##########################################################################
# test_26_autofilter.rb
#
# Tests for the internal methods used to write the AUTOFILTER record.
#
# reverse('©'), September 2005, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
#########################################################################
require 'helper'
require 'stringio'
class TC_26_autofilter < Test::Unit::TestCase
def test_26_autofilter
@tests.each do |test|
column = test['column']
expression = test['expression']
tokens = @worksheet.__send__("extract_filter_tokens", expression)
tokens = @worksheet.__send__("parse_filter_expression", expression, tokens)
result = @worksheet.__send__("store_autofilter", column, *tokens)
target = test['data'].join(" ")
caption = " \tfilter_column(#{column}, '#{expression}')"
result = unpack_record(result)
assert_equal(target, result, caption)
end
end
def setup
@workbook = WriteExcel.new(StringIO.new)
@worksheet = @workbook.add_worksheet
@tests = [
{
'column' => 0,
'expression' => 'x = Blanks',
'data' => [%w(
9E 00 18 00 00 00 84 32 0C 02 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00
)]
},
{
'column' => 1,
'expression' => 'x = Nonblanks',
'data' => [%w(
9E 00 18 00 01 00 84 32 0E 05 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00
)]
},
{
'column' => 2,
'expression' => 'x > 1.001',
'data' => [%w(
9E 00 18 00 02 00 80 32 04 04 6A BC 74 93 18 04
F0 3F 00 00 00 00 00 00 00 00 00 00
)]
},
{
'column' => 3,
'expression' => 'x >= 1.001',
'data' => [%w(
9E 00 18 00 03 00 80 32 04 06 6A BC 74 93 18 04
F0 3F 00 00 00 00 00 00 00 00 00 00
)]
},
{
'column' => 4,
'expression' => 'x < 1.001',
'data' => [%w(
9E 00 18 00 04 00 80 32 04 01 6A BC 74 93 18 04
F0 3F 00 00 00 00 00 00 00 00 00 00
)]
},
{
'column' => 5,
'expression' => 'x <= 1.001',
'data' => [%w(
9E 00 18 00 05 00 80 32 04 03 6A BC 74 93 18 04
F0 3F 00 00 00 00 00 00 00 00 00 00
)]
},
{
'column' => 6,
'expression' => 'x > 1.001 and x <= 5.001',
'data' => [%w(
9E 00 18 00 06 00 80 32 04 04 6A BC 74 93 18 04
F0 3F 04 03 1B 2F DD 24 06 01 14 40
)]
},
{
'column' => 7,
'expression' => 'x > 1.001 or x <= 5.001',
'data' => [%w(
9E 00 18 00 07 00 81 32 04 04 6A BC 74 93 18 04
F0 3F 04 03 1B 2F DD 24 06 01 14 40
)]
},
{
'column' => 8,
'expression' => 'x <> 2.001',
'data' => [%w(
9E 00 18 00 08 00 80 32 04 05 35 5E BA 49 0C 02
00 40 00 00 00 00 00 00 00 00 00 00
)]
},
{
'column' => 9,
'expression' => 'x = 1.001',
'data' => [%w(
9E 00 1E 00 09 00 84 32 06 02 00 00 00 00 05 00
00 00 00 00 00 00 00 00 00 00 00 00 00 31 2E 30
30 31
)]
},
{
'column' => 10,
'expression' => 'x = West',
'data' => [%w(
9E 00 1D 00 0A 00 84 32 06 02 00 00 00 00 04 00
00 00 00 00 00 00 00 00 00 00 00 00 00 57 65 73
74
)]
},
{
'column' => 11,
'expression' => 'x = East',
'data' => [%w(
9E 00 1D 00 0B 00 84 32 06 02 00 00 00 00 04 00
00 00 00 00 00 00 00 00 00 00 00 00 00 45 61 73
74
)]
},
{
'column' => 12,
'expression' => 'x <> West',
'data' => [%w(
9E 00 1D 00 0C 00 80 32 06 05 00 00 00 00 04 00
00 00 00 00 00 00 00 00 00 00 00 00 00 57 65 73
74
)]
},
{
'column' => 13,
'expression' => 'x =~ b*',
'data' => [%w(
9E 00 1B 00 0D 00 80 32 06 02 00 00 00 00 02 00
00 00 00 00 00 00 00 00 00 00 00 00 00 62 2A
)]
},
{
'column' => 14,
'expression' => 'x !~ b*',
'data' => [%w(
9E 00 1B 00 0E 00 80 32 06 05 00 00 00 00 02 00
00 00 00 00 00 00 00 00 00 00 00 00 00 62 2A
)]
},
{
'column' => 15,
'expression' => 'x =~ *b',
'data' => [%w(
9E 00 1B 00 0F 00 80 32 06 02 00 00 00 00 02 00
00 00 00 00 00 00 00 00 00 00 00 00 00 2A 62
)]
},
{
'column' => 16,
'expression' => 'x !~ *b',
'data' => [%w(
9E 00 1B 00 10 00 80 32 06 05 00 00 00 00 02 00
00 00 00 00 00 00 00 00 00 00 00 00 00 2A 62
)]
},
{
'column' => 17,
'expression' => 'x =~ *b*',
'data' => [%w(
9E 00 1C 00 11 00 80 32 06 02 00 00 00 00 03 00
00 00 00 00 00 00 00 00 00 00 00 00 00 2A 62 2A
)]
},
{
'column' => 18,
'expression' => 'x !~ *b*',
'data' => [%w(
9E 00 1C 00 12 00 80 32 06 05 00 00 00 00 03 00
00 00 00 00 00 00 00 00 00 00 00 00 00 2A 62 2A
)]
},
{
'column' => 19,
'expression' => 'x = fo?',
'data' => [%w(
9E 00 1C 00 13 00 80 32 06 02 00 00 00 00 03 00
00 00 00 00 00 00 00 00 00 00 00 00 00 66 6F 3F
)]
},
{
'column' => 20,
'expression' => 'x = fo~?',
'data' => [%w(
9E 00 1D 00 14 00 80 32 06 02 00 00 00 00 04 00
00 00 00 00 00 00 00 00 00 00 00 00 00 66 6F 7E
3F
)]
},
{
'column' => 21,
'expression' => 'x = East and x = West',
'data' => [%w(
9E 00 22 00 15 00 8C 32 06 02 00 00 00 00 04 00
00 00 06 02 00 00 00 00 04 00 00 00 00 45 61 73
74 00 57 65 73 74
)]
},
{
'column' => 22,
'expression' => 'top 10 items',
'data' => [%w(
9E 00 18 00 16 00 30 05 04 06 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00
)]
},
{
'column' => 23,
'expression' => 'top 10 %',
'data' => [%w(
9E 00 18 00 17 00 70 05 04 06 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00
)]
},
{
'column' => 24,
'expression' => 'bottom 10 items',
'data' => [%w(
9E 00 18 00 18 00 10 05 04 03 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00
)]
},
{
'column' => 25,
'expression' => 'bottom 10 %',
'data' => [%w(
9E 00 18 00 19 00 50 05 04 03 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00
)]
},
{
'column' => 26,
'expression' => 'top 5 items',
'data' => [%w(
9E 00 18 00 1A 00 B0 02 04 06 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00
)]
},
{
'column' => 27,
'expression' => 'top 100 items',
'data' => [%w(
9E 00 18 00 1B 00 30 32 04 06 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00
)]
},
{
'column' => 28,
'expression' => 'top 101 items',
'data' => [%w(
9E 00 18 00 1C 00 B0 32 04 06 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00
)]
}
]
end
end
|
Radanisk/writeexcel
|
lib/writeexcel/embedded_chart.rb
|
<filename>lib/writeexcel/embedded_chart.rb
module Writeexcel
class Worksheet < BIFFWriter
require 'writeexcel/helper'
class EmbeddedChart
attr_reader :row, :col, :chart, :vertices
def initialize(worksheet, row, col, chart, x_offset = 0, y_offset = 0, scale_x = 1, scale_y = 1)
@worksheet = worksheet
@row, @col, @chart, @x_offset, @y_offset, @scale_x, @scale_y =
row, col, chart, x_offset, y_offset, scale_x, scale_y
@width = default_width * scale_x
@height = default_height * scale_y
@vertices = calc_vertices
end
# Calculate the positions of comment object.
def calc_vertices
@worksheet.position_object( @col, @row, @x_offset, @y_offset, @width, @height)
end
private
def default_width
526
end
def default_height
319
end
end
end
end
|
Radanisk/writeexcel
|
examples/merge1.rb
|
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
###############################################################################
#
# Simple example of merging cells using the WriteExcel module.
#
# This merges three cells using the "Centre Across Selection" alignment.
# This was the Excel 5 method of achieving a merge. Use the merge_range()
# worksheet method instead. See merge3.pl - merge6.pl.
#
# reverse('©'), August 2002, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
# Create a new workbook and add a worksheet
workbook = WriteExcel.new('merge1.xls')
worksheet = workbook.add_worksheet
# Increase the cell size of the merged cells to highlight the formatting.
worksheet.set_column('B:D', 20)
worksheet.set_row(2, 30)
# Create a merge format
format = workbook.add_format(:center_across => 1)
# Only one cell should contain text, the others should be blank.
worksheet.write(2, 1, "Center across selection", format)
worksheet.write_blank(2, 2, format)
worksheet.write_blank(2, 3, format)
workbook.close
|
Radanisk/writeexcel
|
examples/protection.rb
|
<filename>examples/protection.rb
# -*- coding: utf-8 -*-
#!/usr/bin/ruby -w
########################################################################
#
# Example of cell locking and formula hiding in an Excel worksheet via
# the WriteExcel module.
#
# reverse('©'), August 2001, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
workbook = WriteExcel.new("protection.xls")
worksheet = workbook.add_worksheet
# Create some format objects
locked = workbook.add_format(:locked => 1)
unlocked = workbook.add_format(:locked => 0)
hidden = workbook.add_format(:hidden => 1)
# Format the columns
worksheet.set_column('A:A', 42)
worksheet.set_selection('B3:B3')
# Protect the worksheet
worksheet.protect
# Examples of cell locking and hiding
worksheet.write('A1', 'Cell B1 is locked. It cannot be edited.')
worksheet.write('B1', '=1+2', locked)
worksheet.write('A2', 'Cell B2 is unlocked. It can be edited.')
worksheet.write('B2', '=1+2', unlocked)
worksheet.write('A3', "Cell B3 is hidden. The formula isn't visible.")
worksheet.write('B3', '=1+2', hidden)
worksheet.write('A5', 'Use Menu->Tools->Protection->Unprotect Sheet')
worksheet.write('A6', 'to remove the worksheet protection. ')
workbook.close
|
Radanisk/writeexcel
|
examples/formula_result.rb
|
<gh_stars>10-100
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
#######################################################################
#
# Example of how to write Spreadsheet::WriteExcel formulas with a user
# specified result.
#
# This is generally only required when writing a spreadsheet for an
# application other than Excel where the formula isn't evaluated.
#
# reverse('©'), August 2005, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
workbook = WriteExcel.new('formula_result.xls')
worksheet = workbook.add_worksheet()
format = workbook.add_format(:color => 'blue')
worksheet.write('A1', '=1+2')
worksheet.write('A2', '=1+2', format, 4)
worksheet.write('A3', '="ABC"', nil, 'DEF')
worksheet.write('A4', '=IF(A1 > 1, TRUE, FALSE)', nil, 'TRUE')
worksheet.write('A5', '=1/0', nil, '#DIV/0!')
workbook.close
|
Radanisk/writeexcel
|
examples/merge2.rb
|
<reponame>Radanisk/writeexcel
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
###############################################################################
#
# Simple example of merging cells using the WriteExcel module
#
# This merges two formatted cells using the "Centre Across Selection" alignment.
# This was the Excel 5 method of achieving a merge. Use the merge_range()
# worksheet method instead. See merge3.pl - merge6.pl.
#
# reverse('©'), August 2002, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
# Create a new workbook and add a worksheet
workbook = WriteExcel.new("merge2.xls")
worksheet = workbook.add_worksheet
# Increase the cell size of the merged cells to highlight the formatting.
worksheet.set_column(1, 2, 30)
worksheet.set_row(2, 40)
# Create a merged format
format = workbook.add_format(
:center_across => 1,
:bold => 1,
:size => 15,
:pattern => 1,
:border => 6,
:color => 'white',
:fg_color => 'green',
:border_color => 'yellow',
:align => 'vcenter'
)
# Only one cell should contain text, the others should be blank.
worksheet.write(2, 1, "Center across selection", format)
worksheet.write_blank(2, 2, format)
workbook.close
|
Radanisk/writeexcel
|
examples/defined_name.rb
|
<filename>examples/defined_name.rb
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
###############################################################################
#
# Example of how to create defined names in a WriteExcel file.
#
# reverse('ゥ'), September 2008, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
workbook = WriteExcel.new('defined_name.xls')
worksheet1 = workbook.add_worksheet
worksheet2 = workbook.add_worksheet
workbook.define_name('Exchange_rate', '=0.96')
workbook.define_name('Sales', '=Sheet1!$G$1:$H$10')
workbook.define_name('Sheet2!Sales', '=Sheet2!$G$1:$G$10')
workbook.sheets.each do |worksheet|
worksheet.set_column('A:A', 45)
worksheet.write('A2', 'This worksheet contains some defined names,')
worksheet.write('A3', 'See the Insert -> Name -> Define dialog.')
end
worksheet1.write('A4', '=Exchange_rate')
workbook.close
|
Radanisk/writeexcel
|
lib/writeexcel/cell_range.rb
|
<reponame>Radanisk/writeexcel
module Writeexcel
class Worksheet < BIFFWriter
class CellRange
attr_accessor :row_min, :row_max, :col_min, :col_max
def initialize(worksheet)
@worksheet = worksheet
end
def increment_row_max
@row_max += 1 if @row_max
end
def increment_col_max
@col_max += 1 if @col_max
end
def row(val)
@row_min = val if !@row_min || (val < row_min)
@row_max = val if !@row_max || (val > row_max)
end
def col(val)
@col_min = val if !@col_min || (val < col_min)
@col_max = val if !@col_max || (val > col_max)
end
#
# assemble the NAME record in the long format that is used for storing the repeat
# rows and columns when both are specified. This share a lot of code with
# name_record_short() but we use a separate method to keep the code clean.
# Code abstraction for reuse can be carried too far, and I should know. ;-)
#
# type
# ext_ref # TODO
#
def name_record_long(type, ext_ref) #:nodoc:
record = 0x0018 # Record identifier
length = 0x002a # Number of bytes to follow
grbit = 0x0020 # Option flags
chkey = 0x00 # Keyboard shortcut
cch = 0x01 # Length of text name
cce = 0x001a # Length of text definition
unknown01 = 0x0000 #
ixals = @worksheet.index + 1 # Sheet index
unknown02 = 0x00 #
cch_cust_menu = 0x00 # Length of cust menu text
cch_description = 0x00 # Length of description text
cch_helptopic = 0x00 # Length of help topic text
cch_statustext = 0x00 # Length of status bar text
rgch = type # Built-in name type
unknown03 = 0x29
unknown04 = 0x0017
unknown05 = 0x3b
header = [record, length].pack("vv")
data = [grbit].pack("v")
data += [chkey].pack("C")
data += [cch].pack("C")
data += [cce].pack("v")
data += [unknown01].pack("v")
data += [ixals].pack("v")
data += [unknown02].pack("C")
data += [cch_cust_menu].pack("C")
data += [cch_description].pack("C")
data += [cch_helptopic].pack("C")
data += [cch_statustext].pack("C")
data += [rgch].pack("C")
# Column definition
data += [unknown03].pack("C")
data += [unknown04].pack("v")
data += [unknown05].pack("C")
data += [ext_ref].pack("v")
data += [0x0000].pack("v")
data += [0xffff].pack("v")
data += [@col_min].pack("v")
data += [@col_max].pack("v")
# Row definition
data += [unknown05].pack("C")
data += [ext_ref].pack("v")
data += [@row_min].pack("v")
data += [@row_max].pack("v")
data += [0x00].pack("v")
data += [0xff].pack("v")
# End of data
data += [0x10].pack("C")
[header, data]
end
#
# assemble the NAME record in the short format that is used for storing the print
# area, repeat rows only and repeat columns only.
#
# type
# ext_ref # TODO
# hidden # Name is hidden
#
def name_record_short(type, ext_ref, hidden = nil) #:nodoc:
record = 0x0018 # Record identifier
length = 0x001b # Number of bytes to follow
grbit = 0x0020 # Option flags
chkey = 0x00 # Keyboard shortcut
cch = 0x01 # Length of text name
cce = 0x000b # Length of text definition
unknown01 = 0x0000 #
ixals = @worksheet.index + 1 # Sheet index
unknown02 = 0x00 #
cch_cust_menu = 0x00 # Length of cust menu text
cch_description = 0x00 # Length of description text
cch_helptopic = 0x00 # Length of help topic text
cch_statustext = 0x00 # Length of status bar text
rgch = type # Built-in name type
unknown03 = 0x3b #
grbit = 0x0021 if hidden
rowmin = row_min
rowmax = row_max
rowmin, rowmax = 0x0000, 0xffff unless row_min
colmin = col_min
colmax = col_max
colmin, colmax = 0x00, 0xff unless col_min
header = [record, length].pack("vv")
data = [grbit].pack("v")
data += [chkey].pack("C")
data += [cch].pack("C")
data += [cce].pack("v")
data += [unknown01].pack("v")
data += [ixals].pack("v")
data += [unknown02].pack("C")
data += [cch_cust_menu].pack("C")
data += [cch_description].pack("C")
data += [cch_helptopic].pack("C")
data += [cch_statustext].pack("C")
data += [rgch].pack("C")
data += [unknown03].pack("C")
data += [ext_ref].pack("v")
data += [rowmin].pack("v")
data += [rowmax].pack("v")
data += [colmin].pack("v")
data += [colmax].pack("v")
[header, data]
end
end
class CellDimension < CellRange
def row_min
@row_min || 0
end
def col_min
@col_min || 0
end
def row_max
@row_max || 0
end
def col_max
@col_max || 0
end
end
class PrintRange < CellRange
def name_record_short(ext_ref, hidden)
super(0x06, ext_ref, hidden) # 0x06 NAME type = Print_Area
end
end
class TitleRange < CellRange
def name_record_long(ext_ref)
super(0x07, ext_ref) # 0x07 NAME type = Print_Titles
end
def name_record_short(ext_ref, hidden)
super(0x07, ext_ref, hidden) # 0x07 NAME type = Print_Titles
end
end
class FilterRange < CellRange
def name_record_short(ext_ref, hidden)
super(0x0D, ext_ref, hidden) # 0x0D NAME type = Filter Database
end
def count
if @col_min && @col_max
1 + @col_max - @col_min
else
0
end
end
def inside?(col)
@col_min <= col && col <= @col_max
end
def store
record = 0x00EC # Record identifier
spid = @worksheet.object_ids.spid
# Number of objects written so far.
num_objects = @worksheet.images_size + @worksheet.charts_size
(0 .. count-1).each do |i|
if i == 0 && num_objects
spid, data = write_parent_msodrawing_record(count, @worksheet.comments_size, spid, vertices(i))
else
spid, data = write_child_msodrawing_record(spid, vertices(i))
end
length = data.bytesize
header = [record, length].pack("vv")
append(header, data)
store_obj_filter(num_objects + i + 1, col_min + i)
end
spid
end
private
def write_parent_msodrawing_record(num_filters, num_comments, spid, vertices)
# Write the parent MSODRAWIING record.
dg_length = 168 + 96 * (num_filters - 1)
spgr_length = 144 + 96 * (num_filters - 1)
dg_length += 128 * num_comments
spgr_length += 128 * num_comments
data = store_parent_mso_record(dg_length, spgr_length, spid)
spid += 1
data += store_child_mso_record(spid, *vertices)
spid += 1
[spid, data]
end
def write_child_msodrawing_record(spid, vertices)
data = store_child_mso_record(spid, *vertices)
spid += 1
[spid, data]
end
def store_parent_mso_record(dg_length, spgr_length, spid)
@worksheet.__send__("store_parent_mso_record", dg_length, spgr_length, spid)
end
def store_child_mso_record(spid, *vertices)
@worksheet.__send__("store_child_mso_record", spid, *vertices)
end
def vertices(i)
[
col_min + i, 0,
row_min, 0,
col_min + i + 1, 0,
row_min + 1, 0
]
end
#
# Write the OBJ record that is part of filter records.
# obj_id # Object ID number.
# col
#
def store_obj_filter(obj_id, col) #:nodoc:
record = 0x005D # Record identifier
length = 0x0046 # Bytes to follow
obj_type = 0x0014 # Object type (combo box).
data = '' # Record data.
sub_record = 0x0000 # Sub-record identifier.
sub_length = 0x0000 # Length of sub-record.
sub_data = '' # Data of sub-record.
options = 0x2101
reserved = 0x0000
# Add ftCmo (common object data) subobject
sub_record = 0x0015 # ftCmo
sub_length = 0x0012
sub_data = [obj_type, obj_id, options, reserved, reserved, reserved].pack('vvvVVV')
data = [sub_record, sub_length].pack('vv') + sub_data
# Add ftSbs Scroll bar subobject
sub_record = 0x000C # ftSbs
sub_length = 0x0014
sub_data = ['0000000000000000640001000A00000010000100'].pack('H*')
data += [sub_record, sub_length].pack('vv') + sub_data
# Add ftLbsData (List box data) subobject
sub_record = 0x0013 # ftLbsData
sub_length = 0x1FEE # Special case (undocumented).
# If the filter is active we set one of the undocumented flags.
if @worksheet.instance_variable_get(:@filter_cols)[col]
sub_data = ['000000000100010300000A0008005700'].pack('H*')
else
sub_data = ['00000000010001030000020008005700'].pack('H*')
end
data += [sub_record, sub_length].pack('vv') + sub_data
# Add ftEnd (end of object) subobject
sub_record = 0x0000 # ftNts
sub_length = 0x0000
data += [sub_record, sub_length].pack('vv')
# Pack the record.
header = [record, length].pack('vv')
append(header, data)
end
def append(*args)
@worksheet.append(*args)
end
end
end
end
|
Radanisk/writeexcel
|
examples/hyperlink2.rb
|
<filename>examples/hyperlink2.rb
#!/usr/bin/ruby
# -*- coding: utf-8 -*-
###############################################################################
#
# Example of how to use the WriteExcel module to write internal and internal
# hyperlinks.
#
# If you wish to run this program and follow the hyperlinks you should create
# the following directory structure:
#
# C:\ -- Temp --+-- Europe
# |
# \-- Asia
#
#
# See also hyperlink1.rb for web URL examples.
#
# reverse('©'), March 2002, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
# Create three workbooks:
# C:\Temp\Europe\Ireland.xls
# C:\Temp\Europe\Italy.xls
# C:\Temp\Asia\China.xls
#
ireland = WriteExcel.new('C:\Temp\Europe\Ireland.xls')
ire_links = ireland.add_worksheet('Links')
ire_sales = ireland.add_worksheet('Sales')
ire_data = ireland.add_worksheet('Product Data')
italy = WriteExcel.new('C:\Temp\Europe\Italy.xls')
ita_links = italy.add_worksheet('Links')
ita_sales = italy.add_worksheet('Sales')
ita_data = italy.add_worksheet('Product Data')
china = WriteExcel.new('C:\Temp\Asia\China.xls')
cha_links = china.add_worksheet('Links')
cha_sales = china.add_worksheet('Sales')
cha_data = china.add_worksheet('Product Data')
# Add a format
format = ireland.add_format(:color => 'green', :bold => 1)
ire_links.set_column('A:B', 25)
###############################################################################
#
# Examples of internal links
#
ire_links.write('A1', 'Internal links', format)
# Internal link
ire_links.write('A2', 'internal:Sales!A2')
# Internal link to a range
ire_links.write('A3', 'internal:Sales!A3:D3')
# Internal link with an alternative string
ire_links.write('A4', 'internal:Sales!A4', 'Link')
# Internal link with a format
ire_links.write('A5', 'internal:Sales!A5', format)
# Internal link with an alternative string and format
ire_links.write('A6', 'internal:Sales!A6', 'Link', format)
# Internal link (spaces in worksheet name)
ire_links.write('A7', "internal:'Product Data'!A7")
###############################################################################
#
# Examples of external links
#
ire_links.write('B1', 'External links', format)
# External link to a local file
ire_links.write('B2', 'external:Italy.xls')
# External link to a local file with worksheet
ire_links.write('B3', 'external:Italy.xls#Sales!B3')
# External link to a local file with worksheet and alternative string
ire_links.write('B4', 'external:Italy.xls#Sales!B4', 'Link')
# External link to a local file with worksheet and format
ire_links.write('B5', 'external:Italy.xls#Sales!B5', format)
# External link to a remote file, absolute path
ire_links.write('B6', 'external:c:/Temp/Asia/China.xls')
# External link to a remote file, relative path
ire_links.write('B7', 'external:../Asia/China.xls')
# External link to a remote file with worksheet
ire_links.write('B8', 'external:c:/Temp/Asia/China.xls#Sales!B8')
# External link to a remote file with worksheet (with spaces in the name)
ire_links.write('B9', "external:c:/Temp/Asia/China.xls#'Product Data'!B9")
###############################################################################
#
# Some utility links to return to the main sheet
#
ire_sales.write('A2', 'internal:Links!A2', 'Back')
ire_sales.write('A3', 'internal:Links!A3', 'Back')
ire_sales.write('A4', 'internal:Links!A4', 'Back')
ire_sales.write('A5', 'internal:Links!A5', 'Back')
ire_sales.write('A6', 'internal:Links!A6', 'Back')
ire_data.write('A7', 'internal:Links!A7', 'Back')
ita_links.write('A1', 'external:Ireland.xls#Links!B2', 'Back')
ita_sales.write('B3', 'external:Ireland.xls#Links!B3', 'Back')
ita_sales.write('B4', 'external:Ireland.xls#Links!B4', 'Back')
ita_sales.write('B5', 'external:Ireland.xls#Links!B5', 'Back')
cha_links.write('A1', 'external:../Europe/Ireland.xls#Links!B6', 'Back')
cha_sales.write('B8', 'external:../Europe/Ireland.xls#Links!B8', 'Back')
cha_data.write('B9', 'external:../Europe/Ireland.xls#Links!B9', 'Back')
ireland.close
italy.close
china.close
|
Radanisk/writeexcel
|
lib/writeexcel/col_info.rb
|
module Writeexcel
class Worksheet < BIFFWriter
require 'writeexcel/helper'
class ColInfo
#
# new(firstcol, lastcol, width, [format, hidden, level, collapsed])
#
# firstcol : First formatted column
# lastcol : Last formatted column
# width : Col width in user units, 8.43 is default
# format : format object
# hidden : hidden flag
# level : outline level
# collapsed : ?
#
def initialize(*args)
@firstcol, @lastcol, @width, @format, @hidden, @level, @collapsed = args
@width ||= 8.43 # default width
@level ||= 0 # default level
end
# Write BIFF record COLINFO to define column widths
#
# Note: The SDK says the record length is 0x0B but Excel writes a 0x0C
# length record.
#
def biff_record
record = 0x007D # Record identifier
length = 0x000B # Number of bytes to follow
coldx = (pixels * 256 / 7).to_i # Col width in internal units
reserved = 0x00 # Reserved
header = [record, length].pack("vv")
data = [@firstcol, @lastcol, coldx,
ixfe, grbit, reserved].pack("vvvvvC")
[header, data]
end
# Excel rounds the column width to the nearest pixel. Therefore we first
# convert to pixels and then to the internal units. The pixel to users-units
# relationship is different for values less than 1.
#
def pixels
if @width < 1
result = @width * 12
else
result = @width * 7 + 5
end
result.to_i
end
def ixfe
if @format && @format.respond_to?(:xf_index)
ixfe = @format.xf_index
else
ixfe = 0x0F
end
end
# Set the limits for the outline levels (0 <= x <= 7).
def level
if @level < 0
0
elsif 7 < @level
7
else
@level
end
end
# Set the options flags. (See set_row() for more details).
def grbit
grbit = 0x0000 # Option flags
grbit |= 0x0001 if @hidden && @hidden != 0
grbit |= level << 8
grbit |= 0x1000 if @collapsed && @collapsed != 0
grbit
end
end
end
end
|
Radanisk/writeexcel
|
test/test_formula.rb
|
<reponame>Radanisk/writeexcel
# -*- coding: utf-8 -*-
require 'helper'
class TC_Formula < Test::Unit::TestCase
def setup
@formula = Writeexcel::Formula.new(0)
end
def test_scan
# scan must return array of token info
string01 = '1 + 2 * LEN("String")'
expected01 = [
[:NUMBER, '1'],
['+', '+'],
[:NUMBER, '2'],
['*', '*'],
[:FUNC, 'LEN'],
['(', '('],
[:STRING, '"String"'],
[')', ')'],
[:EOL, nil]
]
assert_kind_of(Array, @formula.scan(string01))
assert_equal(expected01, @formula.scan(string01))
string02 = 'IF(A1>=0,SIN(0),COS(90))'
expected02 = [
[:FUNC, 'IF'],
['(', '('],
[:REF2D, 'A1'],
[:GE, '>='],
[:NUMBER, '0'],
[',', ','],
[:FUNC, 'SIN'],
['(', '('],
[:NUMBER, '0'],
[')', ')'],
[',', ','],
[:FUNC, 'COS'],
['(', '('],
[:NUMBER, '90'],
[')', ')'],
[')', ')'],
[:EOL, nil]
]
assert_kind_of(Array, @formula.scan(string02))
assert_equal(expected02, @formula.scan(string02))
end
def test_reverse
testcase = [
[ [0,1,2,3,4], [0,[1,[2,3,[4]]]] ],
[ [0,1,2,3,4,5], [[0,1,[2,3]],[4,5]] ]
]
testcase.each do |t|
assert_equal(t[0], @formula.reverse(t[1]))
end
end
end
|
Radanisk/writeexcel
|
test/test_23_note.rb
|
<reponame>Radanisk/writeexcel
# -*- coding: utf-8 -*-
##########################################################################
# test_23_note.rb
#
# Tests for some of the internal method used to write the NOTE record that
# is used in cell comments.
#
# reverse('©'), September 2005, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
#########################################################################
require 'helper'
require 'stringio'
class TC_note < Test::Unit::TestCase
def setup
@workbook = WriteExcel.new(StringIO.new)
@worksheet = @workbook.add_worksheet
end
def teardown
if @workbook.instance_variable_get(:@filehandle)
@workbook.instance_variable_get(:@filehandle).close(true)
end
if @worksheet.instance_variable_get(:@filehandle)
@worksheet.instance_variable_get(:@filehandle).close(true)
end
end
def test_blank_author_name
comment = Writeexcel::Worksheet::Comment.new(@worksheet, 2, 0, 'Test')
obj_id = 1
caption = sprintf(" \tnote_record")
target = %w(
1C 00 0C 00 02 00 00 00 00 00 01 00 00 00 00 00
).join(' ')
result = unpack_record(comment.store_note_record(obj_id))
assert_equal(target, result, caption)
end
def test_defined_author_name
comment = Writeexcel::Worksheet::Comment.new(@worksheet, 2, 0,'Test', :author => 'Username')
obj_id = 1
caption = sprintf(" \tstore_note")
target = %w(
1C 00 14 00 02 00 00 00 00 00 01 00 08 00 00 55
73 65 72 6E 61 6D 65 00
).join(' ')
result = unpack_record(comment.store_note_record(obj_id))
assert_equal(target, result, caption)
end
end
|
Radanisk/writeexcel
|
examples/chart_pie.rb
|
<reponame>Radanisk/writeexcel<gh_stars>10-100
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
#
###############################################################################
#
# A simple demo of Pie chart in Spreadsheet::WriteExcel.
#
# reverse('ゥ'), December 2009, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
# Create a new workbook called simple.xls and add a worksheet
workbook = WriteExcel.new('chart_pie.xls')
worksheet = workbook.add_worksheet
bold = workbook.add_format(:bold => 1)
# Add the worksheet data that the charts will refer to.
headings = ['Category', 'Values']
data = [
[ 'Apple', 'Cherry', 'Pecan' ],
[ 60, 30, 10 ]
]
worksheet.write('A1', headings, bold)
worksheet.write('A2', data)
###############################################################################
#
# Example 1. A minimal chart.
#
chart1 = workbook.add_chart(:type => 'Chart::Pie')
# Add values only. Use the default categories.
chart1.add_series(:values => '=Sheet1!$B$2:$B$4')
###############################################################################
#
# Example 2. A minimal chart with user specified categories and a series name.
#
chart2 = workbook.add_chart(:type => 'Chart::Pie')
# Configure the series.
chart2.add_series(
:categories => '=Sheet1!$A$2:$A$4',
:values => '=Sheet1!$B$2:$B$4',
:name => 'Pie sales data'
)
###############################################################################
#
# Example 3. Same as previous chart but with an added title.
#
chart3 = workbook.add_chart(:type => 'Chart::Pie')
# Configure the series.
chart3.add_series(
:categories => '=Sheet1!$A$2:$A$4',
:values => '=Sheet1!$B$2:$B$4',
:name => 'Pie sales data'
)
# Add a title.
chart3.set_title(:name => 'Popular Pie Types')
###############################################################################
#
# Example 4. Same as previous chart with a user specified chart sheet name.
#
chart4 = workbook.add_chart(:name => 'Results Chart', :type => 'Chart::Pie')
# Configure the series.
chart4.add_series(
:categories => '=Sheet1!$A$2:$A$4',
:values => '=Sheet1!$B$2:$B$4',
:name => 'Pie sales data'
)
# The other chart_*.rb examples add a second series in example 4 but additional
# series aren't plotted in a pie chart.
# Add a title.
chart4.set_title(:name => 'Popular Pie Types')
###############################################################################
#
# Example 5. Same as Example 3 but as an embedded chart.
#
chart5 = workbook.add_chart(:type => 'Chart::Pie', :embedded => 1)
# Configure the series.
chart5.add_series(
:categories => '=Sheet1!$A$2:$A$4',
:values => '=Sheet1!$B$2:$B$4',
:name => 'Pie sales data'
)
# Add a title.
chart5.set_title(:name => 'Popular Pie Types')
# Insert the chart into the main worksheet.
worksheet.insert_chart('D2', chart5)
# File save
workbook.close
|
Radanisk/writeexcel
|
examples/chess.rb
|
<filename>examples/chess.rb
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
########################################################################
#
# Example of formatting using the Spreadsheet::WriteExcel module via
# property hashes.
#
# Setting format properties via hashes of values is useful when you have
# to deal with a large number of similar formats. Consider for example a
# chess board pattern with black squares, white unformatted squares and
# a border.
#
# This relatively simple example requires 14 separate Format
# objects although there are only 5 different properties: black
# background, top border, bottom border, left border and right border.
#
# Using property hashes it is possible to define these 5 sets of
# properties and then add them together to create the 14 Format
# configurations.
#
# reverse('©'), July 2001, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
workbook = WriteExcel.new("chess.xls")
worksheet = workbook.add_worksheet()
# Some row and column formatting
worksheet.set_column('B:I', 10)
(1..8).each { |i| worksheet.set_row(i, 50) }
# Define the property hashes
#
black = {
'fg_color' => 'black',
'pattern' => 1,
}
top = { 'top' => 6 }
bottom = { 'bottom' => 6 }
left = { 'left' => 6 }
right = { 'right' => 6 }
# Define the formats
#
format01 = workbook.add_format(top.merge(left))
format02 = workbook.add_format(top.merge(black))
format03 = workbook.add_format(top)
format04 = workbook.add_format(top.merge(right).merge(black))
format05 = workbook.add_format(left)
format06 = workbook.add_format(black)
format07 = workbook.add_format
format08 = workbook.add_format(right.merge(black))
format09 = workbook.add_format(right)
format10 = workbook.add_format(left.merge(black))
format11 = workbook.add_format(bottom.merge(left).merge(black))
format12 = workbook.add_format(bottom)
format13 = workbook.add_format(bottom.merge(black))
format14 = workbook.add_format(bottom.merge(right))
# Draw the pattern
worksheet.write('B2', '', format01)
worksheet.write('C2', '', format02)
worksheet.write('D2', '', format03)
worksheet.write('E2', '', format02)
worksheet.write('F2', '', format03)
worksheet.write('G2', '', format02)
worksheet.write('H2', '', format03)
worksheet.write('I2', '', format04)
worksheet.write('B3', '', format10)
worksheet.write('C3', '', format07)
worksheet.write('D3', '', format06)
worksheet.write('E3', '', format07)
worksheet.write('F3', '', format06)
worksheet.write('G3', '', format07)
worksheet.write('H3', '', format06)
worksheet.write('I3', '', format09)
worksheet.write('B4', '', format05)
worksheet.write('C4', '', format06)
worksheet.write('D4', '', format07)
worksheet.write('E4', '', format06)
worksheet.write('F4', '', format07)
worksheet.write('G4', '', format06)
worksheet.write('H4', '', format07)
worksheet.write('I4', '', format08)
worksheet.write('B5', '', format10)
worksheet.write('C5', '', format07)
worksheet.write('D5', '', format06)
worksheet.write('E5', '', format07)
worksheet.write('F5', '', format06)
worksheet.write('G5', '', format07)
worksheet.write('H5', '', format06)
worksheet.write('I5', '', format09)
worksheet.write('B6', '', format05)
worksheet.write('C6', '', format06)
worksheet.write('D6', '', format07)
worksheet.write('E6', '', format06)
worksheet.write('F6', '', format07)
worksheet.write('G6', '', format06)
worksheet.write('H6', '', format07)
worksheet.write('I6', '', format08)
worksheet.write('B7', '', format10)
worksheet.write('C7', '', format07)
worksheet.write('D7', '', format06)
worksheet.write('E7', '', format07)
worksheet.write('F7', '', format06)
worksheet.write('G7', '', format07)
worksheet.write('H7', '', format06)
worksheet.write('I7', '', format09)
worksheet.write('B8', '', format05)
worksheet.write('C8', '', format06)
worksheet.write('D8', '', format07)
worksheet.write('E8', '', format06)
worksheet.write('F8', '', format07)
worksheet.write('G8', '', format06)
worksheet.write('H8', '', format07)
worksheet.write('I8', '', format08)
worksheet.write('B9', '', format11)
worksheet.write('C9', '', format12)
worksheet.write('D9', '', format13)
worksheet.write('E9', '', format12)
worksheet.write('F9', '', format13)
worksheet.write('G9', '', format12)
worksheet.write('H9', '', format13)
worksheet.write('I9', '', format14)
workbook.close
|
Radanisk/writeexcel
|
test/test_write_formula_does_not_change_formula_string.rb
|
<filename>test/test_write_formula_does_not_change_formula_string.rb<gh_stars>10-100
# -*- coding: utf-8 -*-
require 'helper'
require 'writeexcel'
require 'stringio'
class TestWriteFormula < Test::Unit::TestCase
def setup
@workbook = WriteExcel.new(StringIO.new)
@worksheet = @workbook.add_worksheet('')
end
def teardown
if @workbook.instance_variable_get(:@filehandle)
@workbook.instance_variable_get(:@filehandle).close(true)
end
if @worksheet.instance_variable_get(:@filehandle)
@worksheet.instance_variable_get(:@filehandle).close(true)
end
end
def test_write_formula_does_not_change_formula_string
formula = '=PI()'
@worksheet.write('A1', formula)
assert_equal('=PI()', formula)
end
end
|
Radanisk/writeexcel
|
test/test_01_add_worksheet.rb
|
# -*- coding: utf-8 -*-
require 'helper'
class TC_add_worksheet < Test::Unit::TestCase
def setup
@workbook = WriteExcel.new(StringIO.new)
end
def test_ascii_worksheet_name
name = "Test"
assert_nothing_raised {
sheet = @workbook.add_worksheet(name)
assert_equal name, sheet.name
}
end
def test_utf_8_worksheet_name
name = "Décembre"
assert_nothing_raised {
sheet = @workbook.add_worksheet(name)
assert_equal utf8_to_16be(name), sheet.name
}
end
def test_utf_16be_worksheet_name
name = utf8_to_16be("Décembre")
assert_nothing_raised {
sheet = @workbook.add_worksheet(name, true)
assert_equal name, sheet.name
}
end
end
|
Radanisk/writeexcel
|
examples/diag_border.rb
|
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
##############################################################################
#
# A simple formatting example using WriteExcel.
#
# This program demonstrates the diagonal border cell format.
#
# reverse('©'), May 2004, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
workbook = WriteExcel.new('diag_border.xls')
worksheet = workbook.add_worksheet
format1 = workbook.add_format(:diag_type => 1)
format2 = workbook.add_format(:diag_type => 2)
format3 = workbook.add_format(:diag_type => 3)
format4 = workbook.add_format(
:diag_type => 3,
:diag_border => 7,
:diag_color => 'red'
)
worksheet.write('B3', 'Text', format1)
worksheet.write('B6', 'Text', format2)
worksheet.write('B9', 'Text', format3)
worksheet.write('B12', 'Text', format4)
workbook.close
|
Radanisk/writeexcel
|
examples/merge5.rb
|
<reponame>Radanisk/writeexcel<filename>examples/merge5.rb
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
###############################################################################
#
# Example of how to use the WriteExcel merge_cells() workbook
# method with complex formatting and rotation.
#
#
# reverse('©'), September 2002, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
# Create a new workbook and add a worksheet
workbook = WriteExcel.new('merge5.xls')
worksheet = workbook.add_worksheet
# Increase the cell size of the merged cells to highlight the formatting.
(3..8).each { |col| worksheet.set_row(col, 36) }
[1, 3, 5].each { |n| worksheet.set_column(n, n, 15) }
###############################################################################
#
# Rotation 1, letters run from top to bottom
#
format1 = workbook.add_format(
:border => 6,
:bold => 1,
:color => 'red',
:valign => 'vcentre',
:align => 'centre',
:rotation => 270
)
worksheet.merge_range('B4:B9', 'Rotation 270', format1)
###############################################################################
#
# Rotation 2, 90° anticlockwise
#
format2 = workbook.add_format(
:border => 6,
:bold => 1,
:color => 'red',
:valign => 'vcentre',
:align => 'centre',
:rotation => 90
)
worksheet.merge_range('D4:D9', 'Rotation 90°', format2)
###############################################################################
#
# Rotation 3, 90° clockwise
#
format3 = workbook.add_format(
:border => 6,
:bold => 1,
:color => 'red',
:valign => 'vcentre',
:align => 'centre',
:rotation => -90
)
worksheet.merge_range('F4:F9', 'Rotation -90°', format3)
workbook.close
|
Radanisk/writeexcel
|
examples/stats.rb
|
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
###############################################################################
#
# This is a simple example of how to use functions with the
# WriteExcel module.
#
# reverse('©'), March 2001, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
xlsfile = 'stats.xls'
workbook = WriteExcel.new(xlsfile)
worksheet = workbook.add_worksheet('Test data')
# Set the column width for columns 1
worksheet.set_column(0, 0, 20)
# Create a format for the headings
format = workbook.add_format
format.set_bold
# Write the sample data
worksheet.write(0, 0, 'Sample', format)
worksheet.write(0, 1, 1)
worksheet.write(0, 2, 2)
worksheet.write(0, 3, 3)
worksheet.write(0, 4, 4)
worksheet.write(0, 5, 5)
worksheet.write(0, 6, 6)
worksheet.write(0, 7, 7)
worksheet.write(0, 8, 8)
worksheet.write(1, 0, 'Length', format)
worksheet.write(1, 1, 25.4)
worksheet.write(1, 2, 25.4)
worksheet.write(1, 3, 24.8)
worksheet.write(1, 4, 25.0)
worksheet.write(1, 5, 25.3)
worksheet.write(1, 6, 24.9)
worksheet.write(1, 7, 25.2)
worksheet.write(1, 8, 24.8)
# Write some statistical functions
worksheet.write(4, 0, 'Count', format)
worksheet.write(4, 1, '=COUNT(B1:I1)')
worksheet.write(5, 0, 'Sum', format)
worksheet.write(5, 1, '=SUM(B2:I2)')
worksheet.write(6, 0, 'Average', format)
worksheet.write(6, 1, '=AVERAGE(B2:I2)')
worksheet.write(7, 0, 'Min', format)
worksheet.write(7, 1, '=MIN(B2:I2)')
worksheet.write(8, 0, 'Max', format)
worksheet.write(8, 1, '=MAX(B2:I2)')
worksheet.write(9, 0, 'Standard Deviation', format)
worksheet.write(9, 1, '=STDEV(B2:I2)')
worksheet.write(10, 0, 'Kurtosis', format)
worksheet.write(10, 1, '=KURT(B2:I2)')
workbook.close
|
Radanisk/writeexcel
|
test/test_25_position_object.rb
|
<filename>test/test_25_position_object.rb
# -*- coding: utf-8 -*-
###############################################################################
#
# A test for Spreadsheet::WriteExcel.
#
# Tests for the _position_object() Worksheet method used to calculate the
# vertices that define the position of a graphical object within a worksheet.
#
# See the the _position_object() comments for a full explanation.
#
# reverse('ゥ'), September 2005, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
#########################################################################
require 'helper'
require 'stringio'
class TC_position_object < Test::Unit::TestCase
def setup
@test_file = StringIO.new
@workbook = WriteExcel.new(@test_file)
@worksheet = @workbook.add_worksheet
end
def teardown
if @workbook.instance_variable_get(:@filehandle)
@workbook.instance_variable_get(:@filehandle).close(true)
end
if @worksheet.instance_variable_get(:@filehandle)
@worksheet.instance_variable_get(:@filehandle).close(true)
end
end
###############################################################################
#
# Tests extracted from images imported into Excel.
#
#
# input = ($col_start, $row_start, $x1, $y1, $width, $height)
# (0, 1, 2, 3, 4, 5 )
#
# expected = ($col_start, $x1, $row_start, $y1, $col_end, $x2, $row_end, $y2)
# (0, 1, 2, 3, 4, 5, 6, 7 )
#
def test_extracted_from_images_imported_into_excel
tests = [
# Input # Expected results
[ [0, 0, 0, 0, 1, 1], [ 0, 0, 0, 0, 0, 16, 0, 15] ],
[ [0, 0, 0, 0, 2, 2], [ 0, 0, 0, 0, 0, 32, 0, 30] ],
[ [0, 0, 0, 0, 3, 3], [ 0, 0, 0, 0, 0, 48, 0, 45] ],
[ [0, 0, 0, 0, 4, 4], [ 0, 0, 0, 0, 0, 64, 0, 60] ],
[ [0, 0, 0, 0, 5, 5], [ 0, 0, 0, 0, 0, 80, 0, 75] ],
[ [0, 0, 0, 0, 6, 6], [ 0, 0, 0, 0, 0, 96, 0, 90] ],
[ [0, 0, 0, 0, 7, 7], [ 0, 0, 0, 0, 0, 112, 0, 105] ],
[ [0, 0, 0, 0, 8, 8], [ 0, 0, 0, 0, 0, 128, 0, 120] ],
[ [0, 0, 0, 0, 9, 9], [ 0, 0, 0, 0, 0, 144, 0, 136] ],
[ [0, 0, 0, 0, 10, 10], [ 0, 0, 0, 0, 0, 160, 0, 151] ],
[ [0, 0, 0, 0, 15, 15], [ 0, 0, 0, 0, 0, 240, 0, 226] ],
[ [0, 0, 0, 0, 16, 16], [ 0, 0, 0, 0, 0, 256, 0, 241] ],
[ [0, 0, 0, 0, 17, 17], [ 0, 0, 0, 0, 0, 272, 1, 0] ],
[ [0, 0, 0, 0, 18, 18], [ 0, 0, 0, 0, 0, 288, 1, 15] ],
[ [0, 0, 0, 0, 19, 19], [ 0, 0, 0, 0, 0, 304, 1, 30] ],
[ [0, 0, 0, 0, 62, 8], [ 0, 0, 0, 0, 0, 992, 0, 120] ],
[ [0, 0, 0, 0, 63, 8], [ 0, 0, 0, 0, 0, 1008, 0, 120] ],
[ [0, 0, 0, 0, 64, 8], [ 0, 0, 0, 0, 1, 0, 0, 120] ],
[ [0, 0, 0, 0, 65, 8], [ 0, 0, 0, 0, 1, 16, 0, 120] ],
[ [0, 0, 0, 0, 66, 8], [ 0, 0, 0, 0, 1, 32, 0, 120] ],
[ [0, 0, 0, 0, 200, 200], [ 0, 0, 0, 0, 3, 128, 11, 196] ],
[ [1, 4, 0, 0, 64, 16], [ 1, 0, 4, 0, 2, 0, 4, 241] ],
[ [1, 4, 1, 0, 64, 16], [ 1, 16, 4, 0, 2, 16, 4, 241] ],
[ [1, 4, 2, 0, 64, 16], [ 1, 32, 4, 0, 2, 32, 4, 241] ],
[ [1, 4, 2, 1, 64, 16], [ 1, 32, 4, 15, 2, 32, 5, 0] ],
[ [1, 4, 2, 2, 64, 16], [ 1, 32, 4, 30, 2, 32, 5, 15] ],
# Test for comment box standard sizes.
[ [2, 1, 15, 7, 128, 74], [ 2, 240, 1, 105, 4, 240, 5, 196] ]
]
tests.each do |testcase|
input = testcase[0]
expected = testcase[1]
results = @worksheet.__send__("position_object", *input)
assert_equal(expected, results)
end
end
end
|
Radanisk/writeexcel
|
lib/writeexcel/olewriter.rb
|
# -*- coding: utf-8 -*-
###############################################################################
#
# BIFFwriter - An abstract base class for Excel workbooks and worksheets.
#
#
# Used in conjunction with WriteExcel
#
# Copyright 2000-2010, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
class MaxSizeError < StandardError; end #:nodoc:
class OLEWriter #:nodoc:
# Not meant for public consumption
MaxSize = 7087104 # Use WriteExcel::Big to exceed this
BlockSize = 4096
BlockDiv = 512
ListBlocks = 127
attr_reader :biff_size, :book_size, :big_blocks, :list_blocks
attr_reader :root_start, :size_allowed
attr_accessor :biff_only, :internal_fh
# Accept an IO or IO-like object or a filename (as a String)
def initialize(arg)
if arg.respond_to?(:to_str)
@io = File.open(arg, "w")
else
@io = arg
end
@io.binmode if @io.respond_to?(:binmode)
@filehandle = ""
@fileclosed = false
@internal_fh = 0
@biff_only = 0
@size_allowed = true
@biff_size = 0
@book_size = 0
@big_blocks = 0
@list_blocks = 0
@root_start = 0
@block_count = 4
end
# Imitate IO.open behavior
###############################################################################
#
# _initialize()
#
# Create a new filehandle or use the provided filehandle.
#
def _initialize
olefile = @olefilename
# If the filename is a reference it is assumed that it is a valid
# filehandle, if not we create a filehandle.
#
# Create a new file, open for writing
fh = open(olefile, "wb")
# Workbook.pm also checks this but something may have happened since
# then.
raise "Can't open olefile. It may be in use or protected.\n" unless fh
@internal_fh = 1
# Store filehandle
@filehandle = fh
end
def self.open(arg)
if block_given?
ole = self.new(arg)
result = yield(ole)
ole.close
result
else
self.new(arg)
end
end
###############################################################################
#
# write($data)
#
# Write BIFF data to OLE file.
#
def write(data)
@io.write(data)
end
###############################################################################
#
# set_size(biffsize)
#
# Set the size of the data to be written to the OLE stream
#
# $big_blocks = (109 depot block x (128 -1 marker word)
# - (1 x end words)) = 13842
# $maxsize = $big_blocks * 512 bytes = 7087104
#
def set_size(size = BlockSize)
if size > MaxSize
return @size_allowed = false
end
@biff_size = size
@book_size = [size, BlockSize].max
@size_allowed = true
end
###############################################################################
#
# _calculate_sizes()
#
# Calculate various sizes needed for the OLE stream
#
def calculate_sizes
@big_blocks = (@book_size.to_f/BlockDiv.to_f).ceil
@list_blocks = (@big_blocks / ListBlocks) + 1
@root_start = @big_blocks
end
###############################################################################
#
# close()
#
# Write root entry, big block list and close the filehandle.
# This routine is used to explicitly close the open filehandle without
# having to wait for DESTROY.
#
def close
if @size_allowed == true
write_padding if @biff_only == 0
write_property_storage if @biff_only == 0
write_big_block_depot if @biff_only == 0
end
@io.close
end
###############################################################################
#
# write_header()
#
# Write OLE header block.
#
def write_header
return if @biff_only == 1
calculate_sizes
root_start = @root_start
num_lists = @list_blocks
id = [0xD0CF11E0, 0xA1B11AE1].pack("NN")
unknown1 = [0x00, 0x00, 0x00, 0x00].pack("VVVV")
unknown2 = [0x3E, 0x03].pack("vv")
unknown3 = [-2].pack("v")
unknown4 = [0x09].pack("v")
unknown5 = [0x06, 0x00, 0x00].pack("VVV")
num_bbd_blocks = [num_lists].pack("V")
root_startblock = [root_start].pack("V")
unknown6 = [0x00, 0x1000].pack("VV")
sbd_startblock = [-2].pack("V")
unknown7 = [0x00, -2 ,0x00].pack("VVV")
write(id)
write(unknown1)
write(unknown2)
write(unknown3)
write(unknown4)
write(unknown5)
write(num_bbd_blocks)
write(root_startblock)
write(unknown6)
write(sbd_startblock)
write(unknown7)
unused = [-1].pack("V")
1.upto(num_lists){
root_start += 1
write([root_start].pack("V"))
}
num_lists.upto(108){
write(unused)
}
end
###############################################################################
#
# _write_big_block_depot()
#
# Write big block depot.
#
def write_big_block_depot
num_blocks = @big_blocks
num_lists = @list_blocks
total_blocks = num_lists * 128
used_blocks = num_blocks + num_lists + 2
marker = [-3].pack("V")
end_of_chain = [-2].pack("V")
unused = [-1].pack("V")
1.upto(num_blocks-1){|n|
write([n].pack("V"))
}
write end_of_chain
write end_of_chain
1.upto(num_lists){ write(marker) }
used_blocks.upto(total_blocks){ write(unused) }
end
###############################################################################
#
# _write_property_storage()
#
# Write property storage. TODO: add summary sheets
#
def write_property_storage
######### name type dir start size
write_pps('Root Entry', 0x05, 1, -2, 0x00)
write_pps('Workbook', 0x02, -1, 0x00, @book_size)
write_pps("", 0x00, -1, 0x00, 0x0000)
write_pps("", 0x00, -1, 0x00, 0x0000)
end
###############################################################################
#
# _write_pps()
#
# Write property sheet in property storage
#
def write_pps(name, type, dir, start, size)
length = 0
ord_name = []
unless name.empty?
name = name + "\0"
ord_name = name.unpack("c*")
length = name.bytesize * 2
end
rawname = ord_name.pack("v*")
zero = [0].pack("C")
pps_sizeofname = [length].pack("v") #0x40
pps_type = [type].pack("v") #0x42
pps_prev = [-1].pack("V") #0x44
pps_next = [-1].pack("V") #0x48
pps_dir = [dir].pack("V") #0x4c
unknown = [0].pack("V")
pps_ts1s = [0].pack("V") #0x64
pps_ts1d = [0].pack("V") #0x68
pps_ts2s = [0].pack("V") #0x6c
pps_ts2d = [0].pack("V") #0x70
pps_sb = [start].pack("V") #0x74
pps_size = [size].pack("V") #0x78
write(rawname)
write(zero * (64 - length)) if 64 - length >= 1
write(pps_sizeofname)
write(pps_type)
write(pps_prev)
write(pps_next)
write(pps_dir)
write(unknown * 5)
write(pps_ts1s)
write(pps_ts1d)
write(pps_ts2s)
write(pps_ts2d)
write(pps_sb)
write(pps_size)
write(unknown)
end
###############################################################################
#
# _write_padding()
#
# Pad the end of the file
#
def write_padding
min_size = 512
min_size = BlockSize if @biff_size < BlockSize
if @biff_size % min_size != 0
padding = min_size - (@biff_size % min_size)
write("\0" * padding)
end
end
end
|
Radanisk/writeexcel
|
examples/header.rb
|
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
######################################################################
#
# This program shows several examples of how to set up headers and
# footers with WriteExcel.
#
# The control characters used in the header/footer strings are:
#
# Control Category Description
# ======= ======== ===========
# &L Justification Left
# &C Center
# &R Right
#
# &P Information Page number
# &N Total number of pages
# &D Date
# &T Time
# &F File name
# &A Worksheet name
#
# &fontsize Font Font size
# &"font,style" Font name and style
# &U Single underline
# &E Double underline
# &S Strikethrough
# &X Superscript
# &Y Subscript
#
# && Miscellaneous Literal ampersand &
#
#
# reverse('©'), March 2002, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
workbook = WriteExcel.new("headers.xls")
preview = "Select Print Preview to see the header and footer"
######################################################################
#
# A simple example to start
#
worksheet1 = workbook.add_worksheet('Simple')
header1 = '&CHere is some centred text.'
footer1 = '&LHere is some left aligned text.'
worksheet1.set_header(header1)
worksheet1.set_footer(footer1)
worksheet1.set_column('A:A', 50)
worksheet1.write('A1', preview)
######################################################################
#
# This is an example of some of the header/footer variables.
#
worksheet2 = workbook.add_worksheet('Variables')
header2 = '&LPage &P of &N'+
'&CFilename: &F' +
'&RSheetname: &A'
footer2 = '&LCurrent date: &D'+
'&RCurrent time: &T'
worksheet2.set_header(header2)
worksheet2.set_footer(footer2)
worksheet2.set_column('A:A', 50)
worksheet2.write('A1', preview)
worksheet2.write('A21', "Next sheet")
worksheet2.set_h_pagebreaks(20)
######################################################################
#
# This example shows how to use more than one font
#
worksheet3 = workbook.add_worksheet('Mixed fonts')
header3 = '&C' +
'&"Courier New,Bold"Hello ' +
'&"Arial,Italic"World'
footer3 = '&C' +
'&"Symbol"e' +
'&"Arial" = mc&X2'
worksheet3.set_header(header3)
worksheet3.set_footer(footer3)
worksheet3.set_column('A:A', 50)
worksheet3.write('A1', preview)
######################################################################
#
# Example of line wrapping
#
worksheet4 = workbook.add_worksheet('Word wrap')
header4 = "&CHeading 1\nHeading 2\nHeading 3"
worksheet4.set_header(header4)
worksheet4.set_column('A:A', 50)
worksheet4.write('A1', preview)
######################################################################
#
# Example of inserting a literal ampersand &
#
worksheet5 = workbook.add_worksheet('Ampersand')
header5 = "&CCuriouser && Curiouser - Attorneys at Law"
worksheet5.set_header(header5)
worksheet5.set_column('A:A', 50)
worksheet5.write('A1', preview)
workbook.close
|
Radanisk/writeexcel
|
examples/store_formula.rb
|
<reponame>Radanisk/writeexcel
#!/usr/bin/env ruby
require 'writeexcel'
# Create a new workbook called simple.xls and add a worksheet
workbook = WriteExcel.new('store_formula.xls')
worksheet = workbook.add_worksheet()
formula = worksheet.store_formula('=A1 * 3 + 50')
(0 .. 999).each do |row|
worksheet.repeat_formula(row, 1, formula, nil, 'A1', "A#{row + 1}")
end
workbook.close
|
Radanisk/writeexcel
|
test/test_21_escher.rb
|
<filename>test/test_21_escher.rb<gh_stars>10-100
# -*- coding: utf-8 -*-
###############################################################################
#
# A test for WriteExcel.
#
#
# all test is commented out because Workbook#add_mso_... was set to private
# method. Before that, all test passed.
#
#
#
#
# Tests for the internal methods used to write the records in an Escher drawing
# object such as images, comments and filters.
#
# reverse('©'), September 2005, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
############################################################################
require 'helper'
require 'stringio'
class TC_escher < Test::Unit::TestCase
def setup
@workbook = WriteExcel.new(StringIO.new)
@worksheet = @workbook.add_worksheet
end
def teardown
if @workbook.instance_variable_get(:@filehandle)
@workbook.instance_variable_get(:@filehandle).close(true)
end
if @worksheet.instance_variable_get(:@filehandle)
@worksheet.instance_variable_get(:@filehandle).close(true)
end
end
def test_for_store_mso_dg_container
caption = sprintf(" \t_store_mso_dg_container()")
data = [0xC8]
target = %w( 0F 00 02 F0 C8 00 00 00 ).join(' ')
result = unpack_record(@worksheet.__send__("store_mso_dg_container", *data))
assert_equal(target, result, caption)
end
def test_for_store_mso_dg
caption = sprintf(" \t_store_mso_dg()")
@worksheet.instance_variable_set(:@object_ids, Writeexcel::Worksheet::ObjectIds.new(nil, 1, 2, 1025))
target = %w( 10 00 08 F0
08 00 00 00 02 00 00 00 01 04 00 00
).join(' ')
result = unpack_record(@worksheet.__send__("store_mso_dg"))
assert_equal(target, result, caption)
end
def test_for_store_mso_dgg
caption = sprintf(" \t_store_mso_dgg()")
data = [ 1026, 2, 2, 1, [[1,2]] ]
target = %w( 00 00 06 F0
18 00 00 00 02 04 00 00 02 00 00 00 02 00 00 00
01 00 00 00 01 00 00 00 02 00 00 00
).join(' ')
result = unpack_record(@workbook.__send__("store_mso_dgg", *data))
assert_equal(target, result, caption)
end
def test_for_store_mso_spgr_container
caption = sprintf(" \t_store_mso_spgr_container()")
data = [0xB0]
target = %w(
0F 00 03 F0 B0 00 00 00
).join(' ')
result = unpack_record(@worksheet.__send__("store_mso_spgr_container", *data))
assert_equal(target, result, caption)
end
def test_for_store_mso_sp_container
caption = sprintf(" \t_store_mso_sp_container()")
data = [0x28]
target = %w(
0F 00 04 F0 28 00 00 00
).join(' ')
result = unpack_record(@worksheet.__send__("store_mso_sp_container", *data))
assert_equal(target, result, caption)
end
def test_for_store_mso_sp
caption = sprintf(" \t_store_mso_sp()")
data = [0, 1024, 0x0005]
target = %w(
02 00 0A F0 08 00 00 00 00 04 00 00 05 00 00 00
).join(' ')
result = unpack_record(@worksheet.__send__("store_mso_sp", *data))
assert_equal(target, result, caption)
data = [202, 1025, 0x0A00]
target = %w(
A2 0C 0A F0 08 00 00 00 01 04 00 00 00 0A 00 00
).join(' ')
result = unpack_record(@worksheet.__send__("store_mso_sp", *data))
assert_equal(target, result, caption)
end
def test_for_store_mso_opt_comment
caption = sprintf(" \t_store_mso_opt_comment()")
comment = Writeexcel::Worksheet::Comment.new(@worksheet, 1, 1, ' ')
data = [0x80]
target = %w(
93 00 0B F0 36 00 00 00
80 00 00 00 00 00 BF 00 08 00 08 00
58 01 00 00 00 00 81 01 50 00 00 08 83 01 50 00
00 08 BF 01 10 00 11 00 01 02 00 00 00 00 3F 02
03 00 03 00 BF 03 02 00 0A 00
).join(' ')
result = unpack_record(comment.store_mso_opt_comment(*data))
assert_equal(target, result, caption)
end
def test_for_store_mso_client_data
caption = sprintf(" \t_store_mso_client_data")
target = %w(
00 00 11 F0 00 00 00 00
).join(' ')
result = unpack_record(@worksheet.__send__("store_mso_client_data"))
assert_equal(target, result, caption)
end
def test_for_obj_comment_record
caption = sprintf(" \t_obj_comment_record")
comment = Writeexcel::Worksheet::Comment.new(@worksheet, 1, 1, ' ')
data = [0x01]
target = %w(
5D 00 34 00 15 00 12 00 19 00 01 00 11 40 00 00
00 00 00 00 00 00 00 00 00 00 0D 00 16 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00
).join(' ')
result = unpack_record(comment.obj_comment_record(*data))
assert_equal(target, result, caption)
end
def test_for_store_mso_client_text_box
caption = sprintf(" \t_store_mso_client_text_box")
comment = Writeexcel::Worksheet::Comment.new(@worksheet, 1, 1, ' ')
target = %w(
00 00 0D F0 00 00 00 00
).join(' ')
result = unpack_record(comment.__send__("store_mso_client_text_box"))
assert_equal(target, result, caption)
end
def test_for_store_mso_client_anchor
# A1
range = 'A1'
caption = sprintf(" \t_store_mso_client_anchor(%s)", range)
row, col = @worksheet.__send__("substitute_cellref", range)
vertices = Writeexcel::Worksheet::Comment.new(@worksheet, row, col, 'Test').vertices
target = %w(
00 00 10 F0 12 00 00 00 03 00 01 00 F0 00 00 00
1E 00 03 00 F0 00 04 00 78 00
).join(' ')
result = unpack_record(@worksheet.__send__("store_mso_client_anchor", 3, *vertices))
assert_equal(target, result, caption)
# A2
range = 'A2'
caption = sprintf(" \t_store_mso_client_anchor(%s)", range)
row, col = @worksheet.__send__("substitute_cellref", range)
vertices = Writeexcel::Worksheet::Comment.new(@worksheet, row, col, 'Test').vertices
target = %w(
00 00 10 F0 12 00 00 00 03 00 01 00 F0 00 00 00
69 00 03 00 F0 00 04 00 C4 00
).join(' ')
result = unpack_record(@worksheet.__send__("store_mso_client_anchor", 3, *vertices))
assert_equal(target, result, caption)
# A3
range = 'A3'
caption = sprintf(" \t_store_mso_client_anchor(%s)", range)
row, col = @worksheet.__send__("substitute_cellref", range)
vertices = Writeexcel::Worksheet::Comment.new(@worksheet, row, col, 'Test').vertices
target = %w(
00 00 10 F0 12 00 00 00 03 00 01 00 F0 00 01 00
69 00 03 00 F0 00 05 00 C4 00
).join(' ')
result = unpack_record(@worksheet.__send__("store_mso_client_anchor", 3, *vertices))
assert_equal(target, result, caption)
# A65534
range = 'A65534'
caption = sprintf(" \t_store_mso_client_anchor(%s)", range)
row, col = @worksheet.__send__("substitute_cellref", range)
vertices = Writeexcel::Worksheet::Comment.new(@worksheet, row, col, 'Test').vertices
target = %w(
00 00 10 F0 12 00 00 00 03 00 01 00 F0 00 F9 FF
3C 00 03 00 F0 00 FD FF 97 00
).join(' ')
result = unpack_record(@worksheet.__send__("store_mso_client_anchor", 3, *vertices))
assert_equal(target, result, caption)
# A65536
range = 'A65536'
caption = sprintf(" \t_store_mso_client_anchor(%s)", range)
row, col = @worksheet.__send__("substitute_cellref", range)
vertices = Writeexcel::Worksheet::Comment.new(@worksheet, row, col, 'Test').vertices
target = %w(
00 00 10 F0 12 00 00 00 03 00 01 00 F0 00 FB FF
1E 00 03 00 F0 00 FF FF 78 00
).join(' ')
result = unpack_record(@worksheet.__send__("store_mso_client_anchor", 3, *vertices))
assert_equal(target, result, caption)
# IT3
range = 'IT3'
caption = sprintf(" \t_store_mso_client_anchor(%s)", range)
row, col = @worksheet.__send__("substitute_cellref", range)
vertices = Writeexcel::Worksheet::Comment.new(@worksheet, row, col, 'Test').vertices
target = %w(
00 00 10 F0 12 00 00 00 03 00 FA 00 10 03 01 00
69 00 FC 00 10 03 05 00 C4 00
).join(' ')
result = unpack_record(@worksheet.__send__("store_mso_client_anchor", 3, *vertices))
assert_equal(target, result, caption)
# IU3
range = 'IU3'
caption = sprintf(" \t_store_mso_client_anchor(%s)", range)
row, col = @worksheet.__send__("substitute_cellref", range)
vertices = Writeexcel::Worksheet::Comment.new(@worksheet, row, col, 'Test').vertices
target = %w(
00 00 10 F0 12 00 00 00 03 00 FB 00 10 03 01 00
69 00 FD 00 10 03 05 00 C4 00
).join(' ')
result = unpack_record(@worksheet.__send__("store_mso_client_anchor", 3, *vertices))
assert_equal(target, result, caption)
#
range = 'IU3'
caption = sprintf(" \t_store_mso_client_anchor(%s)", range)
row, col = @worksheet.__send__("substitute_cellref", range)
vertices = Writeexcel::Worksheet::Comment.new(@worksheet, row, col, 'Test').vertices
target = %w(
00 00 10 F0 12 00 00 00 03 00 FB 00 10 03 01 00
69 00 FD 00 10 03 05 00 C4 00
).join(' ')
result = unpack_record(@worksheet.__send__("store_mso_client_anchor", 3, *vertices))
assert_equal(target, result, caption)
# IV3
range = 'IV3'
caption = sprintf(" \t_store_mso_client_anchor(%s)", range)
row, col = @worksheet.__send__("substitute_cellref", range)
vertices = Writeexcel::Worksheet::Comment.new(@worksheet, row, col, 'Test').vertices
target = %w(
00 00 10 F0 12 00 00 00 03 00 FC 00 10 03 01 00
69 00 FE 00 10 03 05 00 C4 00
).join(' ')
result = unpack_record(@worksheet.__send__("store_mso_client_anchor", 3, *vertices))
assert_equal(target, result, caption)
end
def test_for_store_mso_client_anchor_where_comment_offsets_have_changed
range = 'A3'
caption = sprintf(" \t_store_mso_client_anchor(%s). Cell offsets changes.", range)
row, col = @worksheet.__send__("substitute_cellref", range)
vertices = Writeexcel::Worksheet::Comment.new(@worksheet, row, col, 'Test',
:x_offset => 18, :y_offset => 9).vertices
target = %w(
00 00 10 F0 12 00
00 00 03 00 01 00 20 01 01 00 88 00 03 00 20 01
05 00 E2 00
).join(' ')
result = unpack_record(@worksheet.__send__("store_mso_client_anchor", 3, *vertices))
assert_equal(target, result, caption)
end
def test_for_store_mso_client_anchor_where_comment_dimensions_have_changed
# x_scale, y_scale
range = 'A3'
caption = sprintf(" \t_store_mso_client_anchor(%s). Dimensions changes.", range)
row, col = @worksheet.__send__("substitute_cellref", range)
vertices = Writeexcel::Worksheet::Comment.new(@worksheet, row, col, 'Test',
:x_scale => 3, :y_scale => 2).vertices
target = %w(
00 00 10 F0 12 00 00 00 03 00
01 00 F0 00 01 00 69 00 07 00 F0 00 0A 00 1E 00
).join(' ')
result = unpack_record(@worksheet.__send__("store_mso_client_anchor", 3, *vertices))
assert_equal(target, result, caption)
# width, height
row, col = @worksheet.__send__("substitute_cellref", range)
vertices = Writeexcel::Worksheet::Comment.new(@worksheet, row, col, 'Test',
:width => 384, :height => 148).vertices
target = %w(
00 00 10 F0 12 00 00 00 03 00
01 00 F0 00 01 00 69 00 07 00 F0 00 0A 00 1E 00
).join(' ')
result = unpack_record(@worksheet.__send__("store_mso_client_anchor", 3, *vertices))
assert_equal(target, result, caption)
end
def test_for_store_mso_client_anchor_where_column_widths_have_changed
# set_column G:G
range = 'F3'
@worksheet.set_column('G:G', 20)
caption = sprintf(" \t_store_mso_client_anchor(%s). Col width changes.", range)
row, col = @worksheet.__send__("substitute_cellref", range)
vertices = Writeexcel::Worksheet::Comment.new(@worksheet, row, col, 'Test').vertices
target = %w(
00 00 10 F0 12 00
00 00 03 00 06 00 6A 00 01 00 69 00 06 00 F2 03
05 00 C4 00
).join(' ')
result = unpack_record(@worksheet.__send__("store_mso_client_anchor", 3, *vertices))
assert_equal(target, result, caption)
# set_column L:O
range = 'K3'
@worksheet.set_column('L:O', 4)
row, col = @worksheet.__send__("substitute_cellref", range)
vertices = Writeexcel::Worksheet::Comment.new(@worksheet, row, col, 'Test').vertices
target = %w(
00 00 10 F0 12 00
00 00 03 00 0B 00 D1 01 01 00 69 00 0F 00 B0 00
05 00 C4 00
).join(' ')
result = unpack_record(@worksheet.__send__("store_mso_client_anchor", 3, *vertices))
assert_equal(target, result, caption)
end
def test_for_store_mso_client_anchor_where_row_height_have_changed
# set_row 5 to 8
range = 'A6'
@worksheet.set_row(5, 6)
@worksheet.set_row(6, 6)
@worksheet.set_row(7, 6)
@worksheet.set_row(8, 6)
caption = sprintf(" \t_store_mso_client_anchor(%s). Row height changed.", range)
row, col = @worksheet.__send__("substitute_cellref", range)
vertices = Writeexcel::Worksheet::Comment.new(@worksheet, row, col, 'Test').vertices
target = %w(
00 00 10 F0 12 00
00 00 03 00 01 00 F0 00 04 00 69 00 03 00 F0 00
0A 00 E2 00
).join(' ')
result = unpack_record(@worksheet.__send__("store_mso_client_anchor", 3, *vertices))
assert_equal(target, result, caption)
# set_row 14
range = 'A15'
@worksheet.set_row(14, 60)
caption = sprintf(" \t_store_mso_client_anchor(%s). Row height changed.", range)
row, col = @worksheet.__send__("substitute_cellref", range)
vertices = Writeexcel::Worksheet::Comment.new(@worksheet, row, col, 'Test').vertices
target = %w(
00 00 10 F0 12 00
00 00 03 00 01 00 F0 00 0D 00 69 00 03 00 F0 00
0E 00 CD 00
).join(' ')
result = unpack_record(@worksheet.__send__("store_mso_client_anchor", 3, *vertices))
assert_equal(target, result, caption)
end
=begin
def test_for_the_generic_method
data_for_test.each do |data|
caption = data.shift
target = data.pop
data[3].gsub!(/ /,'')
data[3] = [data[3]].pack('H*')
caption = sprintf(" \t_add_mso_generic(): (0x%04X) %s", data[0], caption)
result = unpack_record(@worksheet.add_mso_generic(*data))
assert_equal(target, result, caption)
end
end
def test_for_store_mso_dgg_container
caption = sprintf(" \t_store_mso_dgg_container()")
target = %w( 0F 00 00 F0 52 00 00 00 ).join(' ')
@workbook.mso_size = 94
result = unpack_record(@workbook.store_mso_dgg_container)
assert_equal(target, result, caption)
end
def test_for_store_mso_opt
caption = sprintf(" \t_store_mso_opt()")
target = %w( 33 00 0B F0
12 00 00 00 BF 00 08 00 08 00 81 01 09 00 00 08
C0 01 40 00 00 08
).join(' ')
result = unpack_record(@workbook.store_mso_opt)
assert_equal(target, result, caption)
end
def test_for_store_mso_split_menu_colors
caption = sprintf(" \t_store_mso_split_menu_colors()")
target = %w( 40 00 1E F1 10 00 00 00 0D 00
00 08 0C 00 00 08 17 00 00 08 F7 00 00 10
).join(' ')
result = unpack_record(@workbook.store_mso_split_menu_colors)
assert_equal(target, result, caption)
end
def data_for_test
return [
[ 'DggContainer', # Caption
0xF000, # Type
15, # Version
0, # Instance
'', # Data
82, # Length
'0F 00 00 F0 52 00 00 00', # Target
],
[ 'DgContainer', # Caption
0xF002, # Type
15, # Version
0, # Instance
'', # Data
328, # Length
'0F 00 02 F0 48 01 00 00', # Target
],
[ 'SpgrContainer', # Caption
0xF003, # Type
15, # Version
0, # Instance
'', # Data
304, # Length
'0F 00 03 F0 30 01 00 00', # Target
],
[ 'SpContainer', # Caption
0xF004, # Type
15, # Version
0, # Instance
'', # Data
40, # Length
'0F 00 04 F0 28 00 00 00', # Target
],
[ 'Dgg', # Caption
0xF006, # Type
0, # Version
0, # Instance
'02 04 00 00 02 00 00 00 ' + # Data
'02 00 00 00 01 00 00 00 ' +
'01 00 00 00 02 00 00 00',
nil, # Length
'00 00 06 F0 18 00 00 00 ' + # Target
'02 04 00 00 02 00 00 00 ' +
'02 00 00 00 01 00 00 00 ' +
'01 00 00 00 02 00 00 00',
],
[ 'Dg', # Caption
0xF008, # Type
0, # Version
1, # Instance
'03 00 00 00 02 04 00 00', # Data
nil, # Length
'10 00 08 F0 08 00 00 00 ' + # Target
'03 00 00 00 02 04 00 00',
],
[ 'Spgr', # Caption
0xF009, # Type
1, # Version
0, # Instance
'00 0E 00 0E 40 41 00 00 ' + # Data
'00 0E 00 0E 40 41 00 00',
nil, # Length
'01 00 09 F0 10 00 00 00 ' + # Target
'00 0E 00 0E 40 41 00 00 ' +
'00 0E 00 0E 40 41 00 00',
],
[ 'ClientTextbox', # Caption
0xF00D, # Type
0, # Version
0, # Instance
'', # Data
nil, # Length
'00 00 0D F0 00 00 00 00', # Target
],
[ 'ClientAnchor', # Caption
0xF010, # Type
0, # Version
0, # Instance
'03 00 01 00 F0 00 01 00 ' + # Data
'69 00 03 00 F0 00 05 00 ' +
'C4 00',
nil, # Length
'00 00 10 F0 12 00 00 00 ' + # Target
'03 00 01 00 F0 00 01 00 ' +
'69 00 03 00 F0 00 05 00 ' +
'C4 00',
],
[ 'ClientData', # Caption
0xF011, # Type
0, # Version
0, # Instance
'', # Data
nil, # Length
'00 00 11 F0 00 00 00 00', # Target
],
[ 'SplitMenuColors', # Caption
0xF11E, # Type
0, # Version
4, # Instance
'0D 00 00 08 0C 00 00 08 ' + # Data
'17 00 00 08 F7 00 00 10',
nil, # Length
'40 00 1E F1 10 00 00 00 ' + # Target
'0D 00 00 08 0C 00 00 08 ' +
'17 00 00 08 F7 00 00 10',
],
[ 'BstoreContainer', # Caption
0xF001, # Type
15, # Version
1, # Instance
'', # Data
163, # Length
'1F 00 01 F0 A3 00 00 00', # Target
],
]
end
=end
end
|
Radanisk/writeexcel
|
examples/set_first_sheet.rb
|
#!/usr/bin/ruby -w
# -*- coding:utf-8 -*-
require 'writeexcel'
workbook = WriteExcel.new('set_first_sheet.xls')
20.times { workbook.add_worksheet }
worksheet21 = workbook.add_worksheet
worksheet22 = workbook.add_worksheet
worksheet21.set_first_sheet
worksheet22.activate
workbook.close
|
Radanisk/writeexcel
|
test/test_60_chart_generic.rb
|
# -*- coding: utf-8 -*-
require 'helper'
require 'stringio'
###############################################################################
#
# A test for Chart.
#
# Tests for the Excel chart.rb methods.
#
# reverse(''), December 2009, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
class TC_ChartGeneric < Test::Unit::TestCase
def setup
io = StringIO.new
workbook = WriteExcel.new(io)
@chart = Writeexcel::Chart.new(workbook, '', 'chart')
end
###############################################################################
#
# Test the _store_fbi method.
#
def test_store_fbi
caption = " \tChart: _store_fbi()"
expected = %w(
60 10 0A 00 B8 38 A1 22 C8 00 00 00 05 00
).join(' ')
got = unpack_record(@chart.__send__("store_fbi", 5, 10, 0x38B8, 0x22A1, 0x0000))
assert_equal(expected, got, caption)
expected = %w(
60 10 0A 00 B8 38 A1 22 C8 00 00 00 06 00
).join(' ')
got = unpack_record(@chart.__send__("store_fbi", 6, 10, 0x38B8, 0x22A1, 0x0000))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_chart method.
#
def test_store_chart
caption = " \tChart: _store_chart()"
expected = %w(
02 10 10 00 00 00 00 00 00 00 00 00 E0 51 DD 02
38 B8 C2 01
).join(' ')
values = [0x0000, 0x0000, 0x02DD51E0, 0x01C2B838]
got = unpack_record(@chart.__send__("store_chart", *values))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_series method.
#
def test_store_series
caption = " \tChart: _store_series()"
expected = %w(
03 10 0C 00 01 00 01 00 08 00 08 00 01 00 00 00
).join(' ')
got = unpack_record(@chart.__send__("store_series", 8, 8))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_begin method.
#
def test_store_begin
caption = " \tChart: _store_begin()"
expected = %w(
33 10 00 00
).join(' ')
got = unpack_record(@chart.__send__("store_begin"))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_end method.
#
def test_store_end
caption = " \tChart: _store_end()"
expected = %w(
34 10 00 00
).join(' ')
got = unpack_record(@chart.__send__("store_end"))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_ai method.
#
def test_store_ai
caption = " \tChart: _store_ai()"
values = [0, 1, '']
expected = %w(
51 10 08 00 00 01 00 00 00 00 00 00
).join(' ')
got = unpack_record(@chart.__send__("store_ai", *values))
assert_equal(expected, got, caption)
values = [1, 2, ['3B00000000070000000000'].pack('H*')]
expected = %w(
51 10 13 00 01 02 00 00 00 00 0B 00 3B 00 00 00
00 07 00 00 00 00 00
).join(' ')
got = unpack_record(@chart.__send__("store_ai", *values))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_dataformat method.
#
def test_store_dataformat
caption = " \tChart: _store_dataformat()"
expected = %w(
06 10 08 00 FF FF 00 00 00 00 00 00
).join(' ')
got = unpack_record(@chart.__send__("store_dataformat", 0, 0, 0xFFFF))
assert_equal(expected, got, caption)
expected = %w(
06 10 08 00 00 00 00 00 FD FF 00 00
).join(' ')
got = unpack_record(@chart.__send__("store_dataformat", 0, 0xFFFD, 0))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_3dbarshape method.
#
def test_store_3dbarshape
caption = " \tChart: _store_3dbarshape()"
expected = %w(
5F 10 02 00 00 00
).join(' ')
got = unpack_record(@chart.__send__("store_3dbarshape"))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_sertocrt method.
#
def test_store_sertocrt
caption = " \tChart: _store_sertocrt()"
expected = %w(
45 10 02 00 00 00
).join(' ')
got = unpack_record(@chart.__send__("store_sertocrt"))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_shtprops method.
#
def test_store_shtprops
caption = " \tChart: _store_shtprops()"
expected = %w(
44 10 04 00 0E 00 00 00
).join(' ')
got = unpack_record(@chart.__send__("store_shtprops"))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_defaulttext method.
#
def test_store_defaulttext
caption = " \tChart: _store_defaulttext()"
expected = %w(
24 10 02 00 02 00
).join(' ')
got = unpack_record(@chart.__send__("store_defaulttext"))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_charttext method.
#
def test_store_charttext
caption = " \tChart: _store_charttext()"
expected = %w(
25 10 20 00 02 02 01 00 00 00 00 00 46 FF FF FF
06 FF FF FF 00 00 00 00 00 00 00 00 B1 00 4D 00
00 00 00 00
).join(' ')
got = unpack_record(@chart.__send__("store_charttext"))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_fontx method.
#
def test_store_fontx
caption = " \tChart: _store_fontx()"
expected = %w(
26 10 02 00 05 00
).join(' ')
got = unpack_record(@chart.__send__("store_fontx", 5))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_axesused method.
#
def test_store_axesused
caption = " \tChart: _store_axesused()"
expected = %w(
46 10 02 00 01 00
).join(' ')
got = unpack_record(@chart.__send__("store_axesused", 1))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_axisparent method.
#
def test_store_axisparent
caption = " \tChart: _store_axisparent()"
expected = %w(
41 10 12 00 00 00 F8 00 00 00 F5 01 00 00 7F 0E
00 00 36 0B 00 00
).join(' ')
values = [0, 0x00F8, 0x01F5, 0x0E7F, 0x0B36]
got = unpack_record(@chart.__send__("store_axisparent", *values))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_axis method.
#
def test_store_axis
caption = " \tChart: _store_axis()"
expected = %w(
1D 10 12 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00
).join(' ')
got = unpack_record(@chart.__send__("store_axis", 0))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_catserrange method.
#
def test_store_catserrange
caption = " \tChart: _store_catserrange()"
expected = %w(
20 10 08 00 01 00 01 00 01 00 01 00
).join(' ')
got = unpack_record(@chart.__send__("store_catserrange"))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_axcext method.
#
def test_store_axcext
caption = " \tChart: _store_axcext()"
expected = %w(
62 10 12 00 00 00 00 00 01 00 00 00 01 00 00 00
00 00 00 00 EF 00
).join(' ')
got = unpack_record(@chart.__send__("store_axcext"))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_tick method.
#
def test_store_tick
caption = " \tChart: _store_tick()"
expected = %w(
1E 10 1E 00 02 00 03 01 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 23 00 4D 00
00 00
).join(' ')
got = unpack_record(@chart.__send__("store_tick"))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_valuerange method.
#
def test_store_valuerange
caption = " \tChart: _store_valuerange()"
expected = %w(
1F 10 2A 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 1F 01
).join(' ')
got = unpack_record(@chart.__send__("store_valuerange"))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_axislineformat method.
#
def test_store_axislineformat
caption = " \tChart: _store_axislineformat()"
expected = %w(
21 10 02 00 01 00
).join(' ')
got = unpack_record(@chart.__send__("store_axislineformat"))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_lineformat method.
#
def test_store_lineformat
caption = " \tChart: _store_lineformat()"
expected = %w(
07 10 0C 00 00 00 00 00 00 00 FF FF 09 00 4D 00
).join(' ')
values = [0x00000000, 0x0000, 0xFFFF, 0x0009, 0x004D]
got = unpack_record(@chart.__send__("store_lineformat", *values))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_frame method.
#
def test_store_frame
caption = " \tChart: _store_frame()"
expected = %w(
32 10 04 00 00 00 03 00
).join(' ')
got = unpack_record(@chart.__send__("store_frame", 0x00, 0x03))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_areaformat method.
#
def test_store_areaformat
caption = " \tChart: _store_areaformat()"
expected = %w(
0A 10 10 00 C0 C0 C0 00 00 00 00 00 01 00 00 00
16 00 4F 00
).join(' ')
values = [0x00C0C0C0, 0x00, 0x01, 0x00, 0x16, 0x4F]
got = unpack_record(@chart.__send__("store_areaformat", *values))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_chartformat method.
#
def test_store_chartformat
caption = " \tChart: _store_chartformat()"
expected = %w(
14 10 14 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00
).join(' ')
got = unpack_record(@chart.__send__("store_chartformat"))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_legend method.
#
def test_store_legend
caption = " \tChart: _store_legend()"
expected = %w(
15 10 14 00 F9 05 00 00 E9 0E 00 00 7D 04 00 00
9C 00 00 00 00 01 0F 00
).join(' ')
values = [0x05F9, 0x0EE9, 0x047D, 0x009C, 0x00, 0x01, 0x000F]
got = unpack_record(@chart.__send__("store_legend", *values))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_pos method.
#
def test_store_pos
caption = " \tChart: _store_pos()"
expected = %w(
4F 10 14 00 05 00 02 00 83 0E 00 00 F9 06 00 00
00 00 00 00 00 00 00 00
).join(' ')
values = [5, 2, 0x0E83, 0x06F9, 0, 0]
got = unpack_record(@chart.__send__("store_pos", *values))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_text method.
#
def test_store_text
caption = " \tChart: _store_text()"
expected = %w(
25 10 20 00 02 02 01 00 00 00 00 00 46 FF FF FF
06 FF FF FF 00 00 00 00 00 00 00 00 B1 00 4D 00
20 10 00 00
).join(' ')
values = [0xFFFFFF46, 0xFFFFFF06, 0, 0, 0x00B1, 0x1020]
got = unpack_record(@chart.__send__("store_text", *values))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_plotgrowth method.
#
def test_store_plotgrowth
caption = " \tChart: _store_plotgrowth()"
expected = %w(
64 10 08 00 00 00 01 00 00 00 01 00
).join(' ')
got = unpack_record(@chart.__send__("store_plotgrowth"))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_seriestext method.
#
def test_store_seriestext
caption = " \tChart: _store_seriestext()"
expected = %w(
0D 10 14 00 00 00 10 00 4E 61 6D 65
20 66 6F 72 20 53 65 72
69 65 73 31
).join(' ')
str = 'Name for Series1'
got = unpack_record(@chart.__send__("store_seriestext", str, 0))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_seriestext method.
#
def test_store_seriestext_utf16
caption = " \tChart: _store_seriestext()"
expected = %w(
0D 10 24 00 00 00 10 01 4E 00 61 00 6D 00 65 00
20 00 66 00 6F 00 72 00 20 00 53 00 65 00 72 00
69 00 65 00 73 00 31 00
).join(' ')
str = 'Name for Series1'.unpack('C*').pack('n*')
got = unpack_record(@chart.__send__("store_seriestext", str, 1))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_objectlink method.
#
def test_store_objectlink
caption = " \tChart: _store_objectlink()"
expected = %w(
27 10 06 00 01 00 00 00 00 00
).join(' ')
got = unpack_record(@chart.__send__("store_objectlink", 1))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_pieformat method.
#
def test_store_pieformat
caption = " \tChart: _store_pieformat()"
expected = %w(
0B 10 02 00 00 00
).join(' ')
got = unpack_record(@chart.__send__("store_pieformat"))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_markerformat method.
#
def test_store_markerformat
caption = " \tChart: _store_markerformat()"
expected = %w(
09 10 14 00 00 00 00 00 00 00 00 00 02 00 01 00
4D 00 4D 00 3C 00 00 00
).join(' ')
values = [0x00, 0x00, 0x02, 0x01, 0x4D, 0x4D, 0x3C]
got = unpack_record(@chart.__send__("store_markerformat", *values))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_dropbar method.
#
def test_store_dropbar
caption = " \tChart: _store_dropbar()"
expected = %w(
3D 10 02 00 96 00
).join(' ')
got = unpack_record(@chart.__send__("store_dropbar"))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_chartline method.
#
def test_store_chartline
caption = " \tChart: _store_chartline()"
expected = %w(
1C 10 02 00 01 00
).join(' ')
got = unpack_record(@chart.__send__("store_chartline"))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_serparent method.
#
def test_store_serparent
caption = " \tChart: _store_serparent()"
expected = %w(
4A 10 02 00 01 00
).join(' ')
got = unpack_record(@chart.__send__("store_serparent", 1))
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test the _store_serauxtrend method.
#
def test_store_serauxtrend
caption = " \tChart: _store_serauxtrend()"
expected = %w(
4B 10 1C 00 00 01 FF FF FF FF 00 01 FF FF 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
).join(' ')
values = [0x00, 0x01, 0x00, 0x00]
got = unpack_record(@chart.__send__("store_serauxtrend", *values))
assert_equal(expected, got, caption)
end
end
|
Radanisk/writeexcel
|
test/test_51_name_print_area.rb
|
# -*- coding: utf-8 -*-
##########################################################################
# test_51_name_print_area.rb
#
# Tests for the Excel EXTERNSHEET and NAME records created by print_are()..
#
# reverse('ゥ'), September 2008, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
#########################################################################
require 'helper'
require 'stringio'
class TC_Name_Print_Area < Test::Unit::TestCase
def setup
@test_file = StringIO.new
@workbook = WriteExcel.new(@test_file)
@workbook.not_using_tmpfile
end
def test_print_area_name_for_a_simple_range
worksheet1 = @workbook.add_worksheet
area = 'A1:B12'
worksheet1.print_area(area)
# Test the EXTERNSHEET record.
@workbook.__send__("calculate_extern_sizes")
@workbook.__send__("store_externsheet")
target = [%w(
17 00 08 00 01 00 00 00 00 00 00 00
).join('')].pack('H*')
caption = " \tExternsheet"
result = _unpack_externsheet(@workbook.data)
target = _unpack_externsheet(target)
assert_equal(target, result)
# Test the NAME record.
@workbook.clear_data_for_test
@workbook.__send__("store_names")
target = [%w(
18 00 1B 00 20 00 00 01 0B 00 00 00 01 00 00 00
00 00 00 06 3B 00 00 00 00 0B 00 00 00 01 00
).join('')].pack('H*')
caption = " \t+ Name ( Sheet1!#{area} )";
result = _unpack_name(@workbook.data)
target = _unpack_name(target)
assert_equal(target, result)
end
def test_print_area_name_for_a_simple_row
worksheet1 = @workbook.add_worksheet
area = 'A1:IV1'
worksheet1.print_area(area)
# Test the EXTERNSHEET record.
@workbook.__send__("calculate_extern_sizes")
@workbook.__send__("store_externsheet")
target = [%w(
17 00 08 00 01 00 00 00 00 00 00 00
).join('')].pack('H*')
caption = " \tExternsheet"
result = _unpack_externsheet(@workbook.data)
target = _unpack_externsheet(target)
assert_equal(target, result, caption)
# Test the NAME record.
@workbook.clear_data_for_test
@workbook.__send__("store_names")
target = [%w(
18 00 1B 00 20 00 00 01 0B 00 00 00 01 00 00 00
00 00 00 06 3B 00 00 00 00 00 00 00 00 FF 00
).join('')].pack('H*')
caption = " \t+ Name ( Sheet1!#{area} )";
result = _unpack_name(@workbook.data)
target = _unpack_name(target)
assert_equal(target, result, caption)
end
def test_print_area_name_for_a_simple_column
worksheet1 = @workbook.add_worksheet
area = 'A1:A65536'
worksheet1.print_area(area)
# Test the EXTERNSHEET record.
@workbook.__send__("calculate_extern_sizes")
@workbook.__send__("store_externsheet")
target = [%w(
17 00 08 00 01 00 00 00 00 00 00 00
).join('')].pack('H*')
caption = " \tExternsheet"
result = _unpack_externsheet(@workbook.data)
target = _unpack_externsheet(target)
assert_equal(target, result)
# Test the NAME record.
@workbook.clear_data_for_test
@workbook.__send__("store_names")
target = [%w(
18 00 1B 00 20 00 00 01 0B 00 00 00 01 00 00 00
00 00 00 06 3B 00 00 00 00 FF FF 00 00 00 00
).join('')].pack('H*')
caption = " \t+ Name ( Sheet1!#{area} )";
result = _unpack_name(@workbook.data)
target = _unpack_name(target)
assert_equal(target, result)
end
def test_print_area_name_for_a_multiple_column
worksheet1 = @workbook.add_worksheet
area = 'A:H'
worksheet1.print_area(area)
# Test the EXTERNSHEET record.
@workbook.__send__("calculate_extern_sizes")
@workbook.__send__("store_externsheet")
target = [%w(
17 00 08 00 01 00 00 00 00 00 00 00
).join('')].pack('H*')
caption = " \tExternsheet"
result = _unpack_externsheet(@workbook.data)
target = _unpack_externsheet(target)
assert_equal(target, result)
# Test the NAME record.
@workbook.clear_data_for_test
@workbook.__send__("store_names")
target = [%w(
18 00 1B 00 20 00 00 01 0B 00 00 00 01 00 00 00
00 00 00 06 3B 00 00 00 00 FF FF 00 00 07 00
).join('')].pack('H*')
caption = " \t+ Name ( Sheet1!#{area} )";
result = _unpack_name(@workbook.data)
target = _unpack_name(target)
assert_equal(target, result)
end
def test_ranges_on_multiple_sheets
worksheet1 = @workbook.add_worksheet
worksheet2 = @workbook.add_worksheet
worksheet3 = @workbook.add_worksheet
worksheet1.print_area('A1:B2')
worksheet2.print_area('D4:E5')
worksheet3.print_area('G7:H8')
# Test the EXTERNSHEET record.
@workbook.__send__("calculate_extern_sizes")
@workbook.__send__("store_externsheet")
target = [%w(
17 00 14 00 03 00 00 00 00 00 00 00 00 00 01 00
01 00 00 00 02 00 02 00
).join('')].pack('H*')
caption = " \tExternsheet"
result = _unpack_externsheet(@workbook.data)
target = _unpack_externsheet(target)
assert_equal(target, result)
# Test the NAME record.
@workbook.clear_data_for_test
@workbook.__send__("store_names")
target = [%w(
18 00 1B 00 20 00 00 01 0B 00 00 00 01 00 00 00
00 00 00 06 3B 00 00 00 00 01 00 00 00 01 00
18 00 1B 00 20 00 00 01 0B 00 00 00 02 00 00 00
00 00 00 06 3B 01 00 03 00 04 00 03 00 04 00
18 00 1B 00 20 00 00 01 0B 00 00 00 03 00 00 00
00 00 00 06 3B 02 00 06 00 07 00 06 00 07 00
).join('')].pack('H*')
caption = " \t+ Name ( Sheet1!A1:B2, Sheet2!D4:E5, Sheet3!G7:H8 )";
result = _unpack_name(@workbook.data)
target = _unpack_name(target)
assert_equal(target, result)
end
def test_ranges_on_multiple_sheets_with_sheets_spaced_out
worksheet1 = @workbook.add_worksheet
worksheet2 = @workbook.add_worksheet
worksheet3 = @workbook.add_worksheet
worksheet4 = @workbook.add_worksheet
worksheet5 = @workbook.add_worksheet
worksheet1.print_area('A1:B2')
worksheet3.print_area('D4:E5')
worksheet5.print_area('G7:H8')
# Test the EXTERNSHEET record.
@workbook.__send__("calculate_extern_sizes")
@workbook.__send__("store_externsheet")
target = [%w(
17 00 14 00 03 00 00 00 00 00 00 00 00 00 02 00
02 00 00 00 04 00 04 00
).join('')].pack('H*')
caption = " \tExternsheet"
result = _unpack_externsheet(@workbook.data)
target = _unpack_externsheet(target)
assert_equal(target, result)
# Test the NAME record.
@workbook.clear_data_for_test
@workbook.__send__("store_names")
target = [%w(
18 00 1B 00 20 00 00 01 0B 00 00 00 01 00 00 00
00 00 00 06 3B 00 00 00 00 01 00 00 00 01 00
18 00 1B 00 20 00 00 01 0B 00 00 00 03 00 00 00
00 00 00 06 3B 01 00 03 00 04 00 03 00 04 00
18 00 1B 00 20 00 00 01 0B 00 00 00 05 00 00 00
00 00 00 06 3B 02 00 06 00 07 00 06 00 07 00
).join('')].pack('H*')
caption = " \t+ Name ( Sheet1!A1:B2, Sheet3!D4:E5, Sheet5!G7:H8 )";
result = _unpack_name(@workbook.data)
target = _unpack_name(target)
assert_equal(target, result)
end
###############################################################################
#
# _unpack_externsheet()
#
# Unpack the EXTERNSHEET recordfor easier comparison.
#
def _unpack_externsheet(data)
externsheet = Hash.new
externsheet['record'] = data[0, 2].unpack('v')[0]
data[0, 2] = ''
externsheet['length'] = data[0, 2].unpack('v')[0]
data[0, 2] = ''
externsheet['count'] = data[0, 2].unpack('v')[0]
data[0, 2] = ''
externsheet['array'] = [];
externsheet['count'].times do
externsheet['array'] << data[0, 6].unpack('vvv')
data[0, 6] = ''
end
externsheet
end
###############################################################################
#
# _unpack_name()
#
# Unpack 1 or more NAME structures into a AoH for easier comparison.
#
def _unpack_name(data)
names = Array.new
while data.length > 0
name = Hash.new
name['record'] = data[0, 2].unpack('v')[0]
data[0, 2] = ''
name['length'] = data[0, 2].unpack('v')[0]
data[0, 2] = ''
name['flags'] = data[0, 2].unpack('v')[0]
data[0, 2] = ''
name['shortcut'] = data[0, 1].unpack('C')[0]
data[0, 1] = ''
name['str_len'] = data[0, 1].unpack('C')[0]
data[0, 1] = ''
name['formula_len'] = data[0, 2].unpack('v')[0]
data[0, 2] = ''
name['itals'] = data[0, 2].unpack('v')[0]
data[0, 2] = ''
name['sheet_index'] = data[0, 2].unpack('v')[0]
data[0, 2] = ''
name['menu_len'] = data[0, 1].unpack('C')[0]
data[0, 1] = ''
name['desc_len'] = data[0, 1].unpack('C')[0]
data[0, 1] = ''
name['help_len'] = data[0, 1].unpack('C')[0]
data[0, 1] = ''
name['status_len'] = data[0, 1].unpack('C')[0]
data[0, 1] = ''
name['encoding'] = data[0, 1].unpack('C')[0]
data[0, 1] = ''
# Decode the individual flag fields.
flag = Hash.new
flag['hidden'] = name['flags'] & 0x0001
flag['function'] = name['flags'] & 0x0002
flag['vb'] = name['flags'] & 0x0004
flag['macro'] = name['flags'] & 0x0008
flag['complex'] = name['flags'] & 0x0010
flag['builtin'] = name['flags'] & 0x0020
flag['group'] = name['flags'] & 0x0FC0
flag['binary'] = name['flags'] & 0x1000
name['flags'] = flag
# Decode the string part of the NAME structure.
if name['encoding'] == 1
# UTF-16 name. Leave in hex.
name['string'] = data[0, 2 * name['str_len']].unpack('H*')[0].upcase
data[0, 2 * name['str_len']] = ''
elsif flag['builtin'] != 0
# 1 digit builtin name. Leave in hex.
name['string'] = data[0, name['str_len']].unpack('H*')[0].upcase
data[0, name['str_len']] = ''
else
# ASCII name.
name['string'] = data[0, name['str_len']].unpack('C*').pack('C*')
data[0, name['str_len']] = ''
end
# Keep the formula as a hex string.
name['formula'] = data[0, name['formula_len']].unpack('H*')[0].upcase
data[0, name['formula_len']] = ''
names << name
end
names
end
def assert_hash_equal?(result, target)
assert_equal(result.keys.sort, target.keys.sort)
result.each_key do |key|
assert_equal(result[key], target[key])
end
end
end
|
Radanisk/writeexcel
|
test/test_41_properties.rb
|
# -*- coding: utf-8 -*-
##########################################################################
# test_41_properties.rb
#
# Tests for OLE property sets.
#
# reverse('©'), September 2005, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
#########################################################################
require 'helper'
class TC_properties < Test::Unit::TestCase
def setup
@smiley = '☺' # chr 0x263A; in perl
end
def test_codepage_only
properties = [[0x0001, 'VT_I2', 0x04E4]]
caption = " \tDoc properties: _create_property_set('Code page')"
target = %w(
FE FF 00 00 05 01 02 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 01 00 00 00 E0 85 9F F2
F9 4F 68 10 AB 91 08 00 2B 27 B3 D9 30 00 00 00
18 00 00 00 01 00 00 00 01 00 00 00 10 00 00 00
02 00 00 00 E4 04 00 00
).join(' ')
result = unpack_record( create_summary_property_set(properties))
assert_equal(target, result, caption)
end
def test_same_as_previous_plus_title
properties = [
[0x0001, 'VT_I2', 0x04E4 ],
[0x0002, 'VT_LPSTR', 'Title'],
]
caption = " \tDoc properties: _create_property_set('+ Title')"
target = %w(
FE FF 00 00 05 01 02 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 01 00 00 00 E0 85 9F F2
F9 4F 68 10 AB 91 08 00 2B 27 B3 D9 30 00 00 00
30 00 00 00 02 00 00 00 01 00 00 00 18 00 00 00
02 00 00 00 20 00 00 00 02 00 00 00 E4 04 00 00
1E 00 00 00 06 00 00 00 54 69 74 6C 65 00 00 00
).join(' ')
result = unpack_record( create_summary_property_set(properties))
assert_equal(target, result, caption)
end
def test_same_as_previous_plus_subject
properties = [
[0x0001, 'VT_I2', 0x04E4 ],
[0x0002, 'VT_LPSTR', 'Title'],
[0x0003, 'VT_LPSTR', 'Subject'],
]
caption = " \tDoc properties: _create_property_set('+ Subject')"
target = %w(
FE FF 00 00 05 01 02 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 01 00 00 00 E0 85 9F F2
F9 4F 68 10 AB 91 08 00 2B 27 B3 D9 30 00 00 00
48 00 00 00 03 00 00 00 01 00 00 00 20 00 00 00
02 00 00 00 28 00 00 00 03 00 00 00 38 00 00 00
02 00 00 00 E4 04 00 00 1E 00 00 00 06 00 00 00
54 69 74 6C 65 00 00 00 1E 00 00 00 08 00 00 00
53 75 62 6A 65 63 74 00
).join(' ')
result = unpack_record( create_summary_property_set(properties))
assert_equal(target, result, caption)
end
def test_same_as_previous_plus_author
properties = [
[0x0001, 'VT_I2', 0x04E4 ],
[0x0002, 'VT_LPSTR', 'Title'],
[0x0003, 'VT_LPSTR', 'Subject'],
[0x0004, 'VT_LPSTR', 'Author' ],
]
caption = " \tDoc properties: _create_property_set('+ Keywords')"
target = %w(
FE FF 00 00 05 01 02 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 01 00 00 00 E0 85 9F F2
F9 4F 68 10 AB 91 08 00 2B 27 B3 D9 30 00 00 00
60 00 00 00 04 00 00 00 01 00 00 00 28 00 00 00
02 00 00 00 30 00 00 00 03 00 00 00 40 00 00 00
04 00 00 00 50 00 00 00 02 00 00 00 E4 04 00 00
1E 00 00 00 06 00 00 00 54 69 74 6C 65 00 00 00
1E 00 00 00 08 00 00 00 53 75 62 6A 65 63 74 00
1E 00 00 00 07 00 00 00 41 75 74 68 6F 72 00 00
).join(' ')
result = unpack_record( create_summary_property_set(properties))
assert_equal(target, result, caption)
end
def test_same_as_previous_plus_keywords
properties = [
[0x0001, 'VT_I2', 0x04E4 ],
[0x0002, 'VT_LPSTR', 'Title'],
[0x0003, 'VT_LPSTR', 'Subject'],
[0x0004, 'VT_LPSTR', 'Author' ],
[0x0005, 'VT_LPSTR', 'Keywords'],
]
caption = " \tDoc properties: _create_property_set('+ Keywords')"
target = %w(
FE FF 00 00 05 01 02 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 01 00 00 00 E0 85 9F F2
F9 4F 68 10 AB 91 08 00 2B 27 B3 D9 30 00 00 00
7C 00 00 00 05 00 00 00 01 00 00 00 30 00 00 00
02 00 00 00 38 00 00 00 03 00 00 00 48 00 00 00
04 00 00 00 58 00 00 00 05 00 00 00 68 00 00 00
02 00 00 00 E4 04 00 00 1E 00 00 00 06 00 00 00
54 69 74 6C 65 00 00 00 1E 00 00 00 08 00 00 00
53 75 62 6A 65 63 74 00 1E 00 00 00 07 00 00 00
41 75 74 68 6F 72 00 00 1E 00 00 00 09 00 00 00
4B 65 79 77 6F 72 64 73 00 00 00 00
).join(' ')
result = unpack_record( create_summary_property_set(properties))
assert_equal(target, result, caption)
end
def test_same_as_previous_plus_comments
properties = [
[0x0001, 'VT_I2', 0x04E4 ],
[0x0002, 'VT_LPSTR', 'Title'],
[0x0003, 'VT_LPSTR', 'Subject'],
[0x0004, 'VT_LPSTR', 'Author' ],
[0x0005, 'VT_LPSTR', 'Keywords'],
[0x0006, 'VT_LPSTR', 'Comments'],
]
caption = " \tDoc properties: _create_property_set('+ Comments')"
target = %w(
FE FF 00 00 05 01 02 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 01 00 00 00 E0 85 9F F2
F9 4F 68 10 AB 91 08 00 2B 27 B3 D9 30 00 00 00
98 00 00 00 06 00 00 00 01 00 00 00 38 00 00 00
02 00 00 00 40 00 00 00 03 00 00 00 50 00 00 00
04 00 00 00 60 00 00 00 05 00 00 00 70 00 00 00
06 00 00 00 84 00 00 00 02 00 00 00 E4 04 00 00
1E 00 00 00 06 00 00 00 54 69 74 6C 65 00 00 00
1E 00 00 00 08 00 00 00 53 75 62 6A 65 63 74 00
1E 00 00 00 07 00 00 00 41 75 74 68 6F 72 00 00
1E 00 00 00 09 00 00 00 4B 65 79 77 6F 72 64 73
00 00 00 00 1E 00 00 00 09 00 00 00 43 6F 6D 6D
65 6E 74 73 00 00 00 00
).join(' ')
result = unpack_record( create_summary_property_set(properties))
assert_equal(target, result, caption)
end
def test_same_as_previous_plus_last_author
properties = [
[0x0001, 'VT_I2', 0x04E4 ],
[0x0002, 'VT_LPSTR', 'Title'],
[0x0003, 'VT_LPSTR', 'Subject'],
[0x0004, 'VT_LPSTR', 'Author' ],
[0x0005, 'VT_LPSTR', 'Keywords'],
[0x0006, 'VT_LPSTR', 'Comments'],
[0x0008, 'VT_LPSTR', 'Username'],
]
caption = " \tDoc properties: _create_property_set('+ Comments')"
target = %w(
FE FF 00 00 05 01 02 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 01 00 00 00 E0 85 9F F2
F9 4F 68 10 AB 91 08 00 2B 27 B3 D9 30 00 00 00
B4 00 00 00 07 00 00 00 01 00 00 00 40 00 00 00
02 00 00 00 48 00 00 00 03 00 00 00 58 00 00 00
04 00 00 00 68 00 00 00 05 00 00 00 78 00 00 00
06 00 00 00 8C 00 00 00 08 00 00 00 A0 00 00 00
02 00 00 00 E4 04 00 00 1E 00 00 00 06 00 00 00
54 69 74 6C 65 00 00 00 1E 00 00 00 08 00 00 00
53 75 62 6A 65 63 74 00 1E 00 00 00 07 00 00 00
41 75 74 68 6F 72 00 00 1E 00 00 00 09 00 00 00
4B 65 79 77 6F 72 64 73 00 00 00 00 1E 00 00 00
09 00 00 00 43 6F 6D 6D 65 6E 74 73 00 00 00 00
1E 00 00 00 09 00 00 00 55 73 65 72 6E 61 6D 65
00 00 00 00
).join(' ')
result = unpack_record( create_summary_property_set(properties))
assert_equal(target, result, caption)
end
def test_same_as_previous_plus_creation_date
filetime = Time.gm(2008,8,19,23,20,13)
properties = [
[0x0001, 'VT_I2', 0x04E4 ],
[0x0002, 'VT_LPSTR', 'Title'],
[0x0003, 'VT_LPSTR', 'Subject'],
[0x0004, 'VT_LPSTR', 'Author' ],
[0x0005, 'VT_LPSTR', 'Keywords'],
[0x0006, 'VT_LPSTR', 'Comments'],
[0x0008, 'VT_LPSTR', 'Username'],
[0x000C, 'VT_FILETIME', filetime ],
]
caption = " \tDoc properties: _create_property_set('+ Comments')"
target = %w(
FE FF 00 00 05 01 02 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 01 00 00 00 E0 85 9F F2
F9 4F 68 10 AB 91 08 00 2B 27 B3 D9 30 00 00 00
C8 00 00 00 08 00 00 00 01 00 00 00 48 00 00 00
02 00 00 00 50 00 00 00 03 00 00 00 60 00 00 00
04 00 00 00 70 00 00 00 05 00 00 00 80 00 00 00
06 00 00 00 94 00 00 00 08 00 00 00 A8 00 00 00
0C 00 00 00 BC 00 00 00 02 00 00 00 E4 04 00 00
1E 00 00 00 06 00 00 00 54 69 74 6C 65 00 00 00
1E 00 00 00 08 00 00 00 53 75 62 6A 65 63 74 00
1E 00 00 00 07 00 00 00 41 75 74 68 6F 72 00 00
1E 00 00 00 09 00 00 00 4B 65 79 77 6F 72 64 73
00 00 00 00 1E 00 00 00 09 00 00 00 43 6F 6D 6D
65 6E 74 73 00 00 00 00 1E 00 00 00 09 00 00 00
55 73 65 72 6E 61 6D 65 00 00 00 00 40 00 00 00
80 74 89 21 52 02 C9 01
).join(' ')
result = unpack_record( create_summary_property_set(properties))
assert_equal(target, result, caption)
end
end
|
Radanisk/writeexcel
|
examples/comments2.rb
|
<reponame>Radanisk/writeexcel
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
###############################################################################
#
# This example demonstrates writing cell comments.
#
# A cell comment is indicated in Excel by a small red triangle in the upper
# right-hand corner of the cell.
#
# Each of the worksheets demonstrates different features of cell comments.
#
# reverse('©'), November 2005, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
workbook = WriteExcel.new("comments2.xls")
text_wrap = workbook.add_format(:text_wrap => 1, :valign => 'top')
worksheet1 = workbook.add_worksheet
worksheet2 = workbook.add_worksheet
worksheet3 = workbook.add_worksheet
worksheet4 = workbook.add_worksheet
worksheet5 = workbook.add_worksheet
worksheet6 = workbook.add_worksheet
worksheet7 = workbook.add_worksheet
worksheet8 = workbook.add_worksheet
# Variables that we will use in each example.
cell_text = ''
comment = ''
###############################################################################
#
# Example 1. Demonstrates a simple cell comment without formatting and Unicode
# comments encoded as UTF-16 and as UTF-8.
#
# Set up some formatting.
worksheet1.set_column('C:C', 25)
worksheet1.set_row(2, 50)
worksheet1.set_row(5, 50)
# Simple ascii string.
cell_text = 'Hold the mouse over this cell to see the comment.'
comment = 'This is a comment.'
worksheet1.write('C3', cell_text, text_wrap)
worksheet1.write_comment('C3', comment)
# UTF-16 string.
cell_text = 'This is a UTF-16 comment.'
comment = [0x263a].pack("n")
worksheet1.write('C6', cell_text, text_wrap)
worksheet1.write_comment('C6', comment, :encoding => 1)
# UTF-8 string.
worksheet1.set_row(8, 50)
cell_text = 'This is a UTF-8 string.'
comment = '☺' # chr 0x263a in perl.
worksheet1.write('C9', cell_text, text_wrap)
worksheet1.write_comment('C9', comment)
###############################################################################
#
# Example 2. Demonstrates visible and hidden comments.
#
# Set up some formatting.
worksheet2.set_column('C:C', 25)
worksheet2.set_row(2, 50)
worksheet2.set_row(5, 50)
cell_text = 'This cell comment is visible.'
comment = 'Hello.'
worksheet2.write('C3', cell_text, text_wrap)
worksheet2.write_comment('C3', comment, :visible => 1)
cell_text = "This cell comment isn't visible (the default)."
comment = 'Hello.'
worksheet2.write('C6', cell_text, text_wrap)
worksheet2.write_comment('C6', comment)
###############################################################################
#
# Example 3. Demonstrates visible and hidden comments set at the worksheet
# level.
#
# Set up some formatting.
worksheet3.set_column('C:C', 25)
worksheet3.set_row(2, 50)
worksheet3.set_row(5, 50)
worksheet3.set_row(8, 50)
# Make all comments on the worksheet visible.
worksheet3.show_comments
cell_text = 'This cell comment is visible, explicitly.'
comment = 'Hello.'
worksheet3.write('C3', cell_text, text_wrap)
worksheet3.write_comment('C3', comment, :visible => 1)
cell_text = 'This cell comment is also visible because ' +
'we used show_comments().'
comment = 'Hello.'
worksheet3.write('C6', cell_text, text_wrap)
worksheet3.write_comment('C6', comment)
cell_text = 'However, we can still override it locally.'
comment = 'Hello.'
worksheet3.write('C9', cell_text, text_wrap)
worksheet3.write_comment('C9', comment, :visible => 0)
###############################################################################
#
# Example 4. Demonstrates changes to the comment box dimensions.
#
# Set up some formatting.
worksheet4.set_column('C:C', 25)
worksheet4.set_row(2, 50)
worksheet4.set_row(5, 50)
worksheet4.set_row(8, 50)
worksheet4.set_row(15, 50)
worksheet4.show_comments
cell_text = 'This cell comment is default size.'
comment = 'Hello.'
worksheet4.write('C3', cell_text, text_wrap)
worksheet4.write_comment('C3', comment)
cell_text = 'This cell comment is twice as wide.'
comment = 'Hello.'
worksheet4.write('C6', cell_text, text_wrap)
worksheet4.write_comment('C6', comment, :x_scale => 2)
cell_text = 'This cell comment is twice as high.'
comment = 'Hello.'
worksheet4.write('C9', cell_text, text_wrap)
worksheet4.write_comment('C9', comment, :y_scale => 2)
cell_text = 'This cell comment is scaled in both directions.'
comment = 'Hello.'
worksheet4.write('C16', cell_text, text_wrap)
worksheet4.write_comment('C16', comment, :x_scale => 1.2, :y_scale => 0.8)
cell_text = 'This cell comment has width and height specified in pixels.'
comment = 'Hello.'
worksheet4.write('C19', cell_text, text_wrap)
worksheet4.write_comment('C19', comment, :width => 200, :height => 20)
###############################################################################
#
# Example 5. Demonstrates changes to the cell comment position.
#
worksheet5.set_column('C:C', 25)
worksheet5.set_row(2, 50)
worksheet5.set_row(5, 50)
worksheet5.set_row(8, 50)
worksheet5.set_row(11, 50)
worksheet5.show_comments
cell_text = 'This cell comment is in the default position.'
comment = 'Hello.'
worksheet5.write('C3', cell_text, text_wrap)
worksheet5.write_comment('C3', comment)
cell_text = 'This cell comment has been moved to another cell.'
comment = 'Hello.'
worksheet5.write('C6', cell_text, text_wrap)
worksheet5.write_comment('C6', comment, :start_cell => 'E4')
cell_text = 'This cell comment has been moved to another cell.'
comment = 'Hello.'
worksheet5.write('C9', cell_text, text_wrap)
worksheet5.write_comment('C9', comment, :start_row => 8, :start_col => 4)
cell_text = 'This cell comment has been shifted within its default cell.'
comment = 'Hello.'
worksheet5.write('C12', cell_text, text_wrap)
worksheet5.write_comment('C12', comment, :x_offset => 30, :y_offset => 12)
###############################################################################
#
# Example 6. Demonstrates changes to the comment background colour.
#
worksheet6.set_column('C:C', 25)
worksheet6.set_row(2, 50)
worksheet6.set_row(5, 50)
worksheet6.set_row(8, 50)
worksheet6.show_comments
cell_text = 'This cell comment has a different colour.'
comment = 'Hello.'
worksheet6.write('C3', cell_text, text_wrap)
worksheet6.write_comment('C3', comment, :color => 'green')
cell_text = 'This cell comment has the default colour.'
comment = 'Hello.'
worksheet6.write('C6', cell_text, text_wrap)
worksheet6.write_comment('C6', comment)
cell_text = 'This cell comment has a different colour.'
comment = 'Hello.'
worksheet6.write('C9', cell_text, text_wrap)
worksheet6.write_comment('C9', comment, :color => 0x35)
###############################################################################
#
# Example 7. Demonstrates how to set the cell comment author.
#
worksheet7.set_column('C:C', 30)
worksheet7.set_row(2, 50)
worksheet7.set_row(5, 50)
worksheet7.set_row(8, 50)
worksheet7.set_row(11, 50)
author = ''
cell = 'C3'
cell_text = "Move the mouse over this cell and you will see 'Cell commented "+
"by #{author}' (blank) in the status bar at the bottom"
comment = 'Hello.'
worksheet7.write(cell, cell_text, text_wrap)
worksheet7.write_comment(cell, comment)
author = 'Perl'
cell = 'C6'
cell_text = "Move the mouse over this cell and you will see 'Cell commented " +
"by #{author}' in the status bar at the bottom"
comment = 'Hello.'
worksheet7.write(cell, cell_text, text_wrap)
worksheet7.write_comment(cell, comment, :author => author)
author = [0x20AC].pack("n") # UTF-16 Euro
cell = 'C9'
cell_text = "Move the mouse over this cell and you will see 'Cell commented " +
"by Euro' in the status bar at the bottom"
comment = 'Hello.'
worksheet7.write(cell, cell_text, text_wrap)
worksheet7.write_comment(cell, comment, :author => author,
:author_encoding => 1)
# UTF-8 string.
author = '☺' # smiley
cell = 'C12'
cell_text = "Move the mouse over this cell and you will see 'Cell commented " +
"by #{author}' in the status bar at the bottom"
comment = 'Hello.'
worksheet7.write(cell, cell_text, text_wrap)
worksheet7.write_comment(cell, comment, :author => author)
###############################################################################
#
# Example 8. Demonstrates the need to explicitly set the row height.
#
# Set up some formatting.
worksheet8.set_column('C:C', 25)
worksheet8.set_row(2, 80)
worksheet8.show_comments
cell_text = 'The height of this row has been adjusted explicitly using ' +
'set_row(). The size of the comment box is adjusted ' +
'accordingly by WriteExcel.'
comment = 'Hello.'
worksheet8.write('C3', cell_text, text_wrap)
worksheet8.write_comment('C3', comment)
cell_text = 'The height of this row has been adjusted by Excel due to the ' +
'text wrap property being set. Unfortunately this means that ' +
'the height of the row is unknown to WriteExcel at run time ' +
"and thus the comment box is stretched as well.\n\n" +
'Use set_row() to specify the row height explicitly to avoid ' +
'this problem.'
comment = 'Hello.'
worksheet8.write('C6', cell_text, text_wrap)
worksheet8.write_comment('C6', comment)
workbook.close
|
Radanisk/writeexcel
|
test/test_storage_lite.rb
|
# -*- coding: utf-8 -*-
require 'helper'
require 'stringio'
class TC_OLEStorageLite < Test::Unit::TestCase
TEST_DIR = File.expand_path(File.dirname(__FILE__))
PERL_OUTDIR = File.join(TEST_DIR, 'perl_output')
EXCEL_OUTDIR = File.join(TEST_DIR, 'excelfile')
def setup
@ole = OLEStorageLite.new
end
def test_olestoragelite_new
ole = OLEStorageLite.new
assert_nil(ole.file)
io = StringIO.new
ole = OLEStorageLite.new(io)
assert_equal(io, ole.file)
file = 'test.ole'
ole = OLEStorageLite.new(file)
assert_equal(file, ole.file)
end
def test_asc2ucs
result = @ole.asc2ucs('Root Entry')
target = %w(
52 00 6F 00 6F 00 74 00 20 00 45 00 6E 00 74 00 72 00 79 00
).join(" ")
assert_equal(target, unpack_record(result))
end
def test_ucs2asc
strings = [
'Root Entry',
''
]
strings.each do |str|
result = @ole.ucs2asc(@ole.asc2ucs(str))
assert_equal(str, result)
end
end
end
class TC_OLEStorageLitePPSFile < Test::Unit::TestCase
def test_constructor
data = [
{ :name => 'name', :data => 'data' },
{ :name => '', :data => 'data' },
{ :name => 'name', :data => '' },
{ :name => '', :data => '' },
]
data.each do |d|
olefile = OLEStorageLitePPSFile.new(d[:name])
assert_equal(d[:name], olefile.name)
end
data.each do |d|
olefile = OLEStorageLitePPSFile.new(d[:name], d[:data])
assert_equal(d[:name], olefile.name)
assert_equal(d[:data], olefile.data)
end
end
def test_append_no_file
olefile = OLEStorageLitePPSFile.new('name')
assert_equal('', olefile.data)
data = [ "data", "\r\n", "\r", "\n" ]
data.each do |d|
olefile = OLEStorageLitePPSFile.new('name')
olefile.append(d)
assert_equal(d, olefile.data)
end
end
def test_append_tempfile
data = [ "data", "\r\n", "\r", "\n" ]
data.each do |d|
olefile = OLEStorageLitePPSFile.new('name')
olefile.set_file
pps_file = olefile.pps_file
olefile.append(d)
pps_file.open
pps_file.binmode
assert_equal(d, pps_file.read)
end
end
def test_append_stringio
data = [ "data", "\r\n", "\r", "\n" ]
data.each do |d|
sio = StringIO.new
olefile = OLEStorageLitePPSFile.new('name')
olefile.set_file(sio)
pps_file = olefile.pps_file
olefile.append(d)
pps_file.rewind
assert_equal(d, pps_file.read)
end
end
end
|
Radanisk/writeexcel
|
lib/writeexcel/storage_lite.rb
|
<reponame>Radanisk/writeexcel
# -*- coding: utf-8 -*-
#
# OLE::Storage_Lite
# by <NAME> (Hippo2000) 2000.11.4, 8, 14
# This Program is Still ALPHA version.
#//////////////////////////////////////////////////////////////////////////////
#
# converted from CPAN's OLE::Storage_Lite.
# converted to Ruby by <NAME>, <EMAIL>
#
require 'tempfile'
require 'stringio'
class OLEStorageLite #:nodoc:
PPS_TYPE_ROOT = 5
PPS_TYPE_DIR = 1
PPS_TYPE_FILE = 2
DATA_SIZE_SMALL = 0x1000
LONG_INT_SIZE = 4
PPS_SIZE = 0x80
attr_reader :file
def initialize(file = nil)
@file = file
end
def getPpsTree(data)
info = _initParse(file)
info ? _getPpsTree(0, info, data) : nil
end
def getPpsSearch(name, data, icase)
info = _initParse(file)
info ? _getPpsSearch(0, info, name, data, icase) : nil
end
def getNthPps(no, data)
info = _initParse(file)
info ? _getNthPps(no, info, data) : nil
end
def _initParse(file)
io = file.respond_to?(:to_str) ? open(file, 'rb') : file
_getHeaderInfo(io)
end
private :_initParse
def _getPpsTree(no, info, data, done)
if done
return [] if done.include?(no)
else
done = []
end
done << no
rootblock = info[:root_start]
#1. Get Information about itself
pps = _getNthPps(no, info, data)
#2. Child
if pps.dir_pps != 0xFFFFFFFF
pps.child = _getPpsTree(pps.dir_pps, info, data, done)
else
pps.child = nil
end
#3. Previous,Next PPSs
list = []
list << _getPpsTree(pps.prev_pps, info, data, done) if pps.prev_pps != 0xFFFFFFFF
list << pps
list << _getPpsTree(pps.next_pps, info, data, done) if pps.next_pps != 0xFFFFFFFF
end
private :_getPpsTree
def _getPpsSearch(no, info, name, data, icase, done = nil)
rootblock = info[:root_start]
#1. Check it self
if done
return [] if done.include?(no)
else
done = []
end
done << no
pps = _getNthPps(no, info, nil)
re = Regexp.new("^\Q#{pps.name}\E$", Regexp::IGNORECASE)
if (icase && !name.select { |v| v =~ re }.empty?) || name.include?(pps.name)
pps = _getNthPps(no, info, data) if data
res = [pps]
else
res = []
end
#2. Check Child, Previous, Next PPSs
res +=
_getPpsSearch(pps.dir_pps, info, name, data, icase, done) if pps.dir_pps != 0xFFFFFFFF
res +=
_getPpsSearch(pps.prev_pps, info, name, data, icase, done) if pps.prev_pps != 0xFFFFFFFF
res +=
_getPpsSearch(pps.next_pps, info, name, data, icase, done) if pps.next_pps != 0xFFFFFFFF
res
end
private :_getPpsSearch
def _getHeaderInfo(io)
info = { :fileh => io }
#0. Check ID
info[:fileh].seek(0, 0)
return nil unless info[:fileh].read(8) == "\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1"
# BIG BLOCK SIZE
val = _getInfoFromFile(info[:fileh], 0x1E, 2, "v")
return nil if val.nil?
info[:big_block_size] = 2 ** val
# SMALL BLOCK SIZE
val = _getInfoFromFile(info[:fileh], 0x20, 2, "v")
return nil if val.nil?
info[:small_block_size] = 2 ** val
# BDB Count
val = _getInfoFromFile(info[:fileh], 0x2C, 4, "V")
return nil if val.nil?
info[:bdb_count] = val
# START BLOCK
val = _getInfoFromFile(info[:fileh], 0x30, 4, "V")
return nil if val.nil?
info[:root_start] = val
# SMALL BD START
val = _getInfoFromFile(info[:fileh], 0x3C, 4, "V")
return nil if val.nil?
info[:sbd_start] = val
# SMALL BD COUNT
val = _getInfoFromFile(info[:fileh], 0x40, 4, "V")
return nil if val.nil?
info[:sbd_count] = val
# EXTRA BBD START
val = _getInfoFromFile(info[:fileh], 0x44, 4, "V")
return nil if val.nil?
info[:extra_bbd_start] = val
# EXTRA BBD COUNT
val = _getInfoFromFile(info[:fileh], 0x48, 4, "V")
return nil if val.nil?
info[:extra_bbd_count] = val
#GET BBD INFO
info[:bbd_info] = _getBbdInfo(info)
# GET ROOT PPS
root = _getNthPps(0, info, nil)
info[:sb_start] = root.start_block
info[:sb_size] = root.size
info
end
private :_getHeaderInfo
def _getInfoFromFile(io, pos, len, fmt)
io.seek(pos, 0)
str = io.read(len)
if str.bytesize != len
nil
else
str.unpack(fmt)[0]
end
end
private :_getInfoFromFile
def _getBbdInfo(info)
bdlist = []
iBdbCnt = info[:bdb_count]
i1stCnt = (info[:big_block_size] - 0x4C) / LONG_INT_SIZE
iBdlCnt = info[:big_block_size] / LONG_INT_SIZE - 1
#1. 1st BDlist
info[:fileh].seek(0x4C, 0)
iGetCnt = iBdbCnt < i1stCnt ? iBdbCnt : i1stCnt
str = info[:fileh].read(LONG_INT_SIZE * iGetCnt)
bdlist += str.unpack("V#{iGetCnt}")
iBdbCnt -= iGetCnt
#2. Extra BDList
iBlock = info[:extra_bbd_start]
while iBdbCnt> 0 && _isNormalBlock(iBlock)
_setFilePos(iBlock, 0, info)
iGetCnt = iBdbCnt < iBdlCnt ? iBdbCnt : iBdlCnt
str = info[:fileh].read(LONG_INT_SIZE * iGetCnt)
bdlist += str.unpack("V#{iGetCnt}")
iBdbCnt -= iGetCnt
str = info[:fileh].read(LONG_INT_SIZE)
iBlock = str.unpack("V")
end
#3.Get BDs
hBd = Hash.new
iBlkNo = 0
iBdCnt = info[:big_block_size] / LONG_INT_SIZE
bdlist.each do |iBdL|
_setFilePos(iBdL, 0, info)
str = info[:fileh].read(info[:big_block_size])
arr = str.unpack("V#{iBdCnt}")
(0...iBdCnt).each do |i|
hBd[iBlkNo] = arr[i] if arr[i] != iBlkNo + 1
iBlkNo += 1
end
end
hBd
end
private :_getBbdInfo
def _getNthPps(pos, info, data)
ppsstart = info[:root_start]
basecnt = info[:big_block_size] / PPS_SIZE
ppsblock = pos / basecnt
ppspos = pos % basecnt
block = _getNthBlockNo(ppsstart, ppsblock, info)
return nil if block.nil?
_setFilePos(block, PPS_SIZE * ppspos, info)
str = info[:fileh].read(PPS_SIZE)
return nil if str.nil? || str == ''
nmsize = str[0x40, 2].unpack('v')[0]
nmsize -= 2 if nmsize > 2
nm = str[0, nmsize]
type = str[0x42, 2].unpack('C')[0]
ppsprev = str[0x44, LONG_INT_SIZE].unpack('V')[0]
ppsnext = str[0x48, LONG_INT_SIZE].unpack('V')[0]
dirpps = str[0x4C, LONG_INT_SIZE].unpack('V')[0]
time1st =
(type == PPS_TYPE_ROOT || type == PPS_TYPE_DIR) ? oleData2Local(str[0x64, 8]) : nil
time2nd =
(type == PPS_TYPE_ROOT || type == PPS_TYPE_DIR) ? oleData2Local(str[0x6C, 8]) : nil
start, size = str[0x74, 8].unpack('VV')
if data
sdata = _getData(type, start, size, info)
OLEStorageLitePPS.new(pos, nm, type, ppsprev, ppsnext, dirpps,
time1st, time2nd, start, size, sdata, nil)
else
OLEStorageLitePPS.new(pos, nm, type, ppsprev, ppsnext, dirpps,
time1st, time2nd, start, size, nil, nil)
end
end
private :_getNthPps
def _setFilePos(iBlock, iPos, info)
info[:fileh].seek((iBlock + 1) * info[:big_block_size] + iPos, 0)
end
private :_setFilePos
def _getNthBlockNo(stblock, nth, info)
inext = stblock
(0...nth).each do |i|
sv = inext
inext = _getNextBlockNo(sv, info)
return nil unless _isNormalBlock(inext)
end
inext
end
private :_getNthBlockNo
def _getData(iType, iBlock, iSize, info)
if iType == PPS_TYPE_FILE
if iSize < DATA_SIZE_SMALL
return _getSmallData(iBlock, iSize, info)
else
return _getBigData(iBlock, iSize, info)
end
elsif iType == PPS_TYPE_ROOT # Root
return _getBigData(iBlock, iSize, info)
elsif iType == PPS_TYPE_DIR # Directory
return nil
end
end
private :_getData
def _getBigData(iBlock, iSize, info)
return '' unless _isNormalBlock(iBlock)
iRest = iSize
sRes = ''
aKeys = info[:bbd_info].keys.sort
while iRest > 0
aRes = aKeys.select { |key| key >= iBlock }
iNKey = aRes[0]
i = iNKey - iBlock
iNext = info[:bbd_info][iNKey]
_setFilePos(iBlock, 0, info)
iGetSize = info[:big_block_size] * (i + 1)
iGetSize = iRest if iRest < iGetSize
sRes += info[:fileh].read(iGetSize)
iRest -= iGetSize
iBlock = iNext
end
sRes
end
private :_getBigData
def _getNextBlockNo(iBlockNo, info)
iRes = info[:bbd_info][iBlockNo]
iRes ? iRes : iBlockNo + 1
end
private :_getNextBlockNo
def _isNormalBlock(iBlock)
iBlock < 0xFFFFFFFC ? 1 : nil
end
private :_isNormalBlock
def _getSmallData(iSmBlock, iSize, info)
iRest = iSize
sRes = ''
while iRest > 0
_setFilePosSmall(iSmBlock, info)
sRes += info[:fileh].read(
iRest >= info[:small_block_size] ? info[:small_block_size] : iRest)
iRest -= info[:small_block_size]
iSmBlock = _getNextSmallBlockNo(iSmBlock, info)
end
sRes
end
private :_getSmallData
def _setFilePosSmall(iSmBlock, info)
iSmStart = info[:sb_start]
iBaseCnt = info[:big_block_size] / info[:small_block_size]
iNth = iSmBlock / iBaseCnt
iPos = iSmBlock % iBaseCnt
iBlk = _getNthBlockNo(iSmStart, iNth, info)
_setFilePos(iBlk, iPos * info[:small_block_size], info)
end
private :_setFilePosSmall
def _getNextSmallBlockNo(iSmBlock, info)
iBaseCnt = info[:big_block_size] / LONG_INT_SIZE
iNth = iSmBlock / iBaseCnt
iPos = iSmBlock % iBaseCnt
iBlk = _getNthBlockNo(info[:sbd_start], iNth, info)
_setFilePos(iBlk, iPos * LONG_INT_SIZE, info)
info[:fileh].read(LONG_INT_SIZE).unpack('V')
end
private :_getNextSmallBlockNo
def asc2ucs(str)
str.split(//).join("\0") + "\0"
end
def ucs2asc(str)
ary = str.unpack('v*').map { |s| [s].pack('c')}
ary.join('')
end
#------------------------------------------------------------------------------
# OLEDate2Local()
#
# Convert from a Window FILETIME structure to a localtime array. FILETIME is
# a 64-bit value representing the number of 100-nanosecond intervals since
# January 1 1601.
#
# We first convert the FILETIME to seconds and then subtract the difference
# between the 1601 epoch and the 1970 Unix epoch.
#
def oleData2Local(oletime)
# Unpack the FILETIME into high and low longs.
lo, hi = oletime.unpack('V2')
# Convert the longs to a double.
nanoseconds = hi * 2 ** 32 + lo
# Convert the 100 nanosecond units into seconds.
time = nanoseconds / 1e7
# Subtract the number of seconds between the 1601 and 1970 epochs.
time -= 11644473600
# Convert to a localtime (actually gmtime) structure.
if time >= 1
ltime = Time.at(time).getgm.to_a[0, 9]
ltime[4] -= 1 # month
ltime[5] -= 1900 # year
ltime[7] -= 1 # past from 1, Jan
ltime[8] = ltime[8] ? 1 : 0
ltime
else
[]
end
end
#------------------------------------------------------------------------------
# LocalDate2OLE()
#
# Convert from a a localtime array to a Window FILETIME structure. FILETIME is
# a 64-bit value representing the number of 100-nanosecond intervals since
# January 1 1601.
#
# We first convert the localtime (actually gmtime) to seconds and then add the
# difference between the 1601 epoch and the 1970 Unix epoch. We convert that to
# 100 nanosecond units, divide it into high and low longs and return it as a
# packed 64bit structure.
#
def localDate2OLE(localtime)
return "\x00" * 8 unless localtime
# Convert from localtime (actually gmtime) to seconds.
args = localtime.reverse
args[0] += 1900 # year
args[1] += 1 # month
time = Time.gm(*args)
# Add the number of seconds between the 1601 and 1970 epochs.
time = time.to_i + 11644473600
# The FILETIME seconds are in units of 100 nanoseconds.
nanoseconds = time * 10000000
# Pack the total nanoseconds into 64 bits...
hi, lo = nanoseconds.divmod 1 << 32
[lo, hi].pack("VV") # oletime
end
end
class OLEStorageLitePPS < OLEStorageLite #:nodoc:
attr_accessor :no, :name, :type, :prev_pps, :next_pps, :dir_pps
attr_accessor :time_1st, :time_2nd, :start_block, :size, :data, :child
attr_reader :pps_file
def initialize(iNo, sNm, iType, iPrev, iNext, iDir,
raTime1st, raTime2nd, iStart, iSize, sData, raChild)
@no = iNo
@name = sNm
@type = iType
@prev_pps = iPrev
@next_pps = iNext
@dir_pps = iDir
@time_1st = raTime1st
@time_2nd = raTime2nd
@start_block = iStart
@size = iSize
@data = sData
@child = raChild
@pps_file = nil
end
def _datalen
return 0 if @data.nil?
if @pps_file
return @pps_file.lstat.size
else
return @data.bytesize
end
end
protected :_datalen
def _makeSmallData(aList, rh_info)
file = rh_info[:fileh]
iSmBlk = 0
sRes = ''
aList.each do |pps|
#1. Make SBD, small data string
if pps.type == PPS_TYPE_FILE
next if pps.size <= 0
if pps.size < rh_info[:small_size]
iSmbCnt = pps.size / rh_info[:small_block_size]
iSmbCnt += 1 if pps.size % rh_info[:small_block_size] > 0
#1.1 Add to SBD
0.upto(iSmbCnt-1-1) do |i|
file.write([i + iSmBlk+1].pack("V"))
end
file.write([-2].pack("V"))
#1.2 Add to Data String(this will be written for RootEntry)
#Check for update
if pps.pps_file
pps.pps_file.seek(0) #To The Top
while sBuff = pps.pps_file.read(4096)
sRes << sBuff
end
else
sRes << pps.data
end
if pps.size % rh_info[:small_block_size] > 0
cnt = rh_info[:small_block_size] - (pps.size % rh_info[:small_block_size])
sRes << "\0" * cnt
end
#1.3 Set for PPS
pps.start_block = iSmBlk
iSmBlk += iSmbCnt
end
end
end
iSbCnt = rh_info[:big_block_size] / LONG_INT_SIZE
file.write([-1].pack("V") * (iSbCnt - (iSmBlk % iSbCnt))) if iSmBlk % iSbCnt > 0
#2. Write SBD with adjusting length for block
sRes
end
private :_makeSmallData
def _savePpsWk(rh_info)
#1. Write PPS
file = rh_info[:fileh]
data = [
@name,
("\x00" * (64 - @name.bytesize)), #64
[@name.bytesize + 2].pack("v"), #66
[@type].pack("c"), #67
[0x00].pack("c"), #UK #68
[@prev_pps].pack("V"), #Prev #72
[@next_pps].pack("V"), #Next #76
[@dir_pps].pack("V"), #Dir #80
"\x00\x09\x02\x00", #84
"\x00\x00\x00\x00", #88
"\xc0\x00\x00\x00", #92
"\x00\x00\x00\x46", #96
"\x00\x00\x00\x00", #100
localDate2OLE(@time_1st), #108
localDate2OLE(@time_2nd) #116
]
file.write(
ruby_18 { data.join('') } ||
ruby_19 { data.collect { |d| d.force_encoding(Encoding::BINARY) }.join('') }
)
if @start_block != 0
file.write([@start_block].pack('V'))
else
file.write([0].pack('V'))
end
if @size != 0 #124
file.write([@size].pack('V'))
else
file.write([0].pack('V'))
end
file.write([0].pack('V')) #128
end
protected :_savePpsWk
end
class OLEStorageLitePPSRoot < OLEStorageLitePPS #:nodoc:
def initialize(raTime1st, raTime2nd, raChild)
super(
nil,
asc2ucs('Root Entry'),
PPS_TYPE_ROOT,
nil,
nil,
nil,
raTime1st,
raTime2nd,
nil,
nil,
nil,
raChild)
end
def save(sFile, bNoAs = nil, rh_info = nil)
#0.Initial Setting for saving
rh_info = Hash.new unless rh_info
if rh_info[:big_block_size]
rh_info[:big_block_size] = 2 ** adjust2(rh_info[:big_block_size])
else
rh_info[:big_block_size] = 2 ** 9
end
if rh_info[:small_block_size]
rh_info[:small_block_size] = 2 ** adjust2(rh_info[:small_block_size])
else
rh_info[:small_block_size] = 2 ** 6
end
rh_info[:small_size] = 0x1000
rh_info[:pps_size] = 0x80
close_file = true
#1.Open File
#1.1 sFile is Ref of scalar
if sFile.respond_to?(:to_str)
rh_info[:fileh] = open(sFile, "wb")
else
rh_info[:fileh] = sFile.binmode
end
iBlk = 0
#1. Make an array of PPS (for Save)
aList=[]
if bNoAs
_savePpsSetPnt2([self], aList, rh_info)
else
_savePpsSetPnt([self], aList, rh_info)
end
iSBDcnt, iBBcnt, iPPScnt = _calcSize(aList, rh_info)
#2.Save Header
_saveHeader(rh_info, iSBDcnt, iBBcnt, iPPScnt)
#3.Make Small Data string (write SBD)
# Small Datas become RootEntry Data
@data = _makeSmallData(aList, rh_info)
#4. Write BB
iBBlk = iSBDcnt
_saveBigData(iBBlk, aList, rh_info)
#5. Write PPS
_savePps(aList, rh_info)
#6. Write BD and BDList and Adding Header informations
_saveBbd(iSBDcnt, iBBcnt, iPPScnt, rh_info)
#7.Close File
rh_info[:fileh].close if close_file
end
def _calcSize(aList, rh_info)
#0. Calculate Basic Setting
iSBDcnt, iBBcnt, iPPScnt = [0,0,0]
iSmallLen = 0
iSBcnt = 0
aList.each do |pps|
if pps.type == PPS_TYPE_FILE
pps.size = pps._datalen #Mod
if pps.size < rh_info[:small_size]
iSBcnt += pps.size / rh_info[:small_block_size]
iSBcnt += 1 if pps.size % rh_info[:small_block_size] > 0
else
iBBcnt += pps.size / rh_info[:big_block_size]
iBBcnt += 1 if pps.size % rh_info[:big_block_size] > 0
end
end
end
iSmallLen = iSBcnt * rh_info[:small_block_size]
iSlCnt = rh_info[:big_block_size] / LONG_INT_SIZE
iSBDcnt = iSBcnt / iSlCnt
iSBDcnt += 1 if iSBcnt % iSlCnt > 0
iBBcnt += iSmallLen / rh_info[:big_block_size]
iBBcnt += 1 if iSmallLen % rh_info[:big_block_size] > 0
iCnt = aList.size
iBdCnt = rh_info[:big_block_size] / PPS_SIZE
iPPScnt = iCnt / iBdCnt
iPPScnt += 1 if iCnt % iBdCnt > 0
[iSBDcnt, iBBcnt, iPPScnt]
end
private :_calcSize
def _adjust2(i2)
iWk = Math.log(i2)/Math.log(2)
iWk > Integer(iWk) ? Integer(iWk) + 1 : iWk
end
private :_adjust2
def _saveHeader(rh_info, iSBDcnt, iBBcnt, iPPScnt)
file = rh_info[:fileh]
#0. Calculate Basic Setting
iBlCnt = rh_info[:big_block_size] / LONG_INT_SIZE
i1stBdL = (rh_info[:big_block_size] - 0x4C) / LONG_INT_SIZE
i1stBdMax = i1stBdL * iBlCnt - i1stBdL
iBdExL = 0
iAll = iBBcnt + iPPScnt + iSBDcnt
iAllW = iAll
iBdCntW = iAllW / iBlCnt
iBdCntW += 1 if iAllW % iBlCnt > 0
iBdCnt = ((iAll + iBdCntW) / iBlCnt).to_i
iBdCnt += ((iAllW + iBdCntW) % iBlCnt) == 0 ? 0 : 1
if iBdCnt > i1stBdL
#0.1 Calculate BD count
iBlCnt -= 1 #the BlCnt is reduced in the count of the last sect is used for a pointer the next Bl
iBBleftover = iAll - i1stBdMax
if iAll >i1stBdMax
iBdCnt, iBdExL, iBBleftover = calc_idbcnt_idbexl_ibbleftover(iBBleftover, iBlCnt, iBdCnt, iBdExL)
end
iBdCnt += i1stBdL
#print "iBdCnt = iBdCnt \n"
end
#1.Save Header
data = [
"\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1",
"\x00\x00\x00\x00" * 4,
[0x3b].pack("v"),
[0x03].pack("v"),
[-2].pack("v"),
[9].pack("v"),
[6].pack("v"),
[0].pack("v"),
"\x00\x00\x00\x00" * 2,
[iBdCnt].pack("V"),
[iBBcnt+iSBDcnt].pack("V"), #ROOT START
[0].pack("V"),
[0x1000].pack("V"),
[iSBDcnt == 0 ? -2 : 0].pack("V"), #Small Block Depot
[iSBDcnt].pack("V")
]
file.write(
ruby_18 { data.join('') } ||
ruby_19 { data.collect { |d| d.force_encoding(Encoding::BINARY) }.join('') }
)
#2. Extra BDList Start, Count
if iAll <= i1stBdMax
file.write(
[-2].pack("V") + #Extra BDList Start
[0].pack("V") #Extra BDList Count
)
else
file.write(
[iAll + iBdCnt].pack("V") +
[iBdExL].pack("V")
)
end
#3. BDList
cnt = i1stBdL
cnt = iBdCnt if iBdCnt < i1stBdL
0.upto(cnt-1) do |i|
file.write([iAll + i].pack("V"))
end
file.write([-1].pack("V") * (i1stBdL - cnt)) if cnt < i1stBdL
end
private :_saveHeader
def _saveBigData(iStBlk, aList, rh_info)
iRes = 0
file = rh_info[:fileh]
#1.Write Big (ge 0x1000) Data into Block
aList.each do |pps|
if pps.type != PPS_TYPE_DIR
#print "PPS: pps DEF:", defined(pps->{Data}), "\n"
pps.size = pps._datalen #Mod
if (pps.size >= rh_info[:small_size]) ||
((pps.type == PPS_TYPE_ROOT) && !pps.data.nil?)
#1.1 Write Data
#Check for update
if pps.pps_file
iLen = 0
pps.pps_file.seek(0, 0) #To The Top
while sBuff = pps.pps_file.read(4096)
iLen += sBuff.bytesize
file.write(sBuff) #Check for update
end
else
file.write(pps.data)
end
if pps.size % rh_info[:big_block_size] > 0
file.write(
"\x00" *
(rh_info[:big_block_size] -
(pps.size % rh_info[:big_block_size]))
)
end
#1.2 Set For PPS
pps.start_block = iStBlk
iStBlk += pps.size / rh_info[:big_block_size]
iStBlk += 1 if pps.size % rh_info[:big_block_size] > 0
end
end
end
end
def _savePps(aList, rh_info)
#0. Initial
file = rh_info[:fileh]
#2. Save PPS
aList.each do |oItem|
oItem._savePpsWk(rh_info)
end
#3. Adjust for Block
iCnt = aList.size
iBCnt = rh_info[:big_block_size] / rh_info[:pps_size]
if iCnt % iBCnt > 0
file.write("\x00" * ((iBCnt - (iCnt % iBCnt)) * rh_info[:pps_size]))
end
(iCnt / iBCnt) + ((iCnt % iBCnt) > 0 ? 1: 0)
end
private :_savePps
def _savePpsSetPnt(pps_array, aList, rh_info)
#1. make Array as Children-Relations
#1.1 if No Children
if pps_array.nil? || pps_array.size == 0
return 0xFFFFFFFF
#1.2 Just Only one
elsif pps_array.size == 1
aList << pps_array[0]
pps_array[0].no = aList.size - 1
pps_array[0].prev_pps = 0xFFFFFFFF
pps_array[0].next_pps = 0xFFFFFFFF
pps_array[0].dir_pps = _savePpsSetPnt(pps_array[0].child, aList, rh_info)
return pps_array[0].no
#1.3 Array
else
iCnt = pps_array.size
#1.3.1 Define Center
iPos = Integer(iCnt / 2.0) #$iCnt
aList.push(pps_array[iPos])
pps_array[iPos].no = aList.size - 1
aWk = pps_array.dup
#1.3.2 Devide a array into Previous,Next
aPrev = aWk[0, iPos]
aWk[0..iPos-1] = []
aNext = aWk[1, iCnt - iPos - 1]
aWk[1..(1 + iCnt - iPos -1 -1)] = []
pps_array[iPos].prev_pps = _savePpsSetPnt(aPrev, aList, rh_info)
pps_array[iPos].next_pps = _savePpsSetPnt(aNext, aList, rh_info)
pps_array[iPos].dir_pps = _savePpsSetPnt(pps_array[iPos].child, aList, rh_info)
return pps_array[iPos].no
end
end
private :_savePpsSetPnt
def _savePpsSetPnt2(pps_array, aList, rh_info)
#1. make Array as Children-Relations
#1.1 if No Children
if pps_array.nil? || pps_array.size == 0
return 0xFFFFFFFF
#1.2 Just Only one
elsif pps_array.size == 1
aList << pps_array[0]
pps_array[0].no = aList.size - 1
pps_array[0].prev_pps = 0xFFFFFFFF
pps_array[0].next_pps = 0xFFFFFFFF
pps_array[0].dir_pps = _savePpsSetPnt2(pps_array[0].child, aList, rh_info)
return pps_array[0].no
#1.3 Array
else
iCnt = pps_array.size
#1.3.1 Define Center
iPos = 0 #int($iCnt/ 2); #$iCnt
aWk = pps_array.dup
aPrev = aWk[1, 1]
aWk[1..1] = []
aNext = aWk[1..aWk.size] #, $iCnt - $iPos -1);
pps_array[iPos].prev_pps = _savePpsSetPnt2(pps_array, aList, rh_info)
aList.push(pps_array[iPos])
pps_array[iPos].no = aList.size
#1.3.2 Devide a array into Previous,Next
pps_array[iPos].next_pps = _savePpsSetPnt2(aNext, aList, rh_info)
pps_array[iPos].dir_pps = _savePpsSetPnt2(pps_array[iPos].child, aList, rh_info)
return pps_array[iPos].no
end
end
private :_savePpsSetPnt2
def _saveBbd(iSbdSize, iBsize, iPpsCnt, rh_info)
file = rh_info[:fileh]
#0. Calculate Basic Setting
iBbCnt = rh_info[:big_block_size] / LONG_INT_SIZE
iBlCnt = iBbCnt - 1
i1stBdL = (rh_info[:big_block_size] - 0x4C) / LONG_INT_SIZE
i1stBdMax = i1stBdL * iBbCnt - i1stBdL
iBdExL = 0
iAll = iBsize + iPpsCnt + iSbdSize
iAllW = iAll
iBdCntW = iAllW / iBbCnt
iBdCntW += 1 if iAllW % iBbCnt > 0
iBdCnt = 0
#0.1 Calculate BD count
iBBleftover = iAll - i1stBdMax
if iAll >i1stBdMax
iBdCnt, iBdExL, iBBleftover = calc_idbcnt_idbexl_ibbleftover(iBBleftover, iBlCnt, iBdCnt, iBdExL)
end
iAllW += iBdExL
iBdCnt += i1stBdL
#print "iBdCnt = iBdCnt \n"
#1. Making BD
#1.1 Set for SBD
if iSbdSize > 0
0.upto(iSbdSize-1-1) do |i|
file.write([i + 1].pack('V'))
end
file.write([-2].pack('V'))
end
#1.2 Set for B
0.upto(iBsize-1-1) do |i|
file.write([i + iSbdSize + 1].pack('V'))
end
file.write([-2].pack('V'))
#1.3 Set for PPS
0.upto(iPpsCnt-1-1) do |i|
file.write([i+iSbdSize+iBsize+1].pack("V"))
end
file.write([-2].pack('V'))
#1.4 Set for BBD itself ( 0xFFFFFFFD : BBD)
0.upto(iBdCnt-1) do |i|
file.write([0xFFFFFFFD].pack("V"))
end
#1.5 Set for ExtraBDList
0.upto(iBdExL-1) do |i|
file.write([0xFFFFFFFC].pack("V"))
end
#1.6 Adjust for Block
if (iAllW + iBdCnt) % iBbCnt > 0
file.write([-1].pack('V') * (iBbCnt - ((iAllW + iBdCnt) % iBbCnt)))
end
#2.Extra BDList
if iBdCnt > i1stBdL
iN = 0
iNb = 0
i1stBdL.upto(iBdCnt-1) do |i|
if iN >= iBbCnt-1
iN = 0
iNb += 1
file.write([iAll+iBdCnt+iNb].pack("V"))
end
file.write([iBsize+iSbdSize+iPpsCnt+i].pack("V"))
iN += 1
end
if (iBdCnt-i1stBdL) % (iBbCnt-1) > 0
file.write([-1].pack("V") * ((iBbCnt-1) - ((iBdCnt-i1stBdL) % (iBbCnt-1))))
end
file.write([-2].pack('V'))
end
end
def calc_idbcnt_idbexl_ibbleftover(iBBleftover, iBlCnt, iBdCnt, iBdExL)
while true
iBdCnt = iBBleftover / iBlCnt
iBdCnt += 1 if iBBleftover % iBlCnt > 0
iBdExL = iBdCnt / iBlCnt
iBdExL += 1 if iBdCnt % iBlCnt > 0
iBBleftover += iBdExL
break if iBdCnt == iBBleftover / iBlCnt + (iBBleftover % iBlCnt > 0 ? 1 : 0)
end
[iBdCnt, iBdExL, iBBleftover]
end
private :calc_idbcnt_idbexl_ibbleftover
end
class OLEStorageLitePPSFile < OLEStorageLitePPS #:nodoc:
def initialize(sNm, data = '')
super(
nil,
sNm || '',
PPS_TYPE_FILE,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
data || '',
nil
)
end
def set_file(sFile = '')
if sFile.nil? or sFile == ''
@pps_file = Tempfile.new('OLEStorageLitePPSFile')
elsif sFile.respond_to?(:write)
@pps_file = sFile
elsif sFile.respond_to?(:to_str)
#File Name
@pps_file = open(sFile, "r+")
return nil unless @pps_file
else
return nil
end
@pps_file.seek(0, IO::SEEK_END)
@pps_file.binmode
end
def append (data)
return if data.nil?
if @pps_file
@pps_file << data
@pps_file.flush
else
@data << data
end
end
end
|
Radanisk/writeexcel
|
test/test_format.rb
|
# -*- coding: utf-8 -*-
require 'helper'
require 'stringio'
class TC_Format < Test::Unit::TestCase
TEST_DIR = File.expand_path(File.dirname(__FILE__))
PERL_OUTDIR = File.join(TEST_DIR, 'perl_output')
def setup
@ruby_file = StringIO.new
@format = Writeexcel::Format.new
end
def test_set_format_properties
end
def test_format_properties_with_valid_value
# set_format_properties( propty => val )
valid_properties = get_valid_format_properties
valid_properties.each do |k,v|
fmt = Writeexcel::Format.new
before = get_format_property(fmt)
fmt.set_format_properties(k => v)
after = get_format_property(fmt)
after.delete_if {|key, val| before[key] == val }
assert_equal(1, after.size, "change 1 property[:#{k}] but #{after.size} was changed.#{after.inspect}")
assert_equal(v, after[k], "[:#{k}] doesn't match.")
end
# set_format_properties( propty_1 => val1, propty_2 => val2)
valid_properties.each do |k,v|
fmt = Writeexcel::Format.new
before = get_format_property(fmt)
fmt.set_format_properties(k => v, :bold => 1)
after = get_format_property(fmt)
after.delete_if {|key, val| before[key] == val }
assert_equal(2, after.size, "change 1 property[:#{k}] but #{after.size} was changed.#{after.inspect}")
assert_equal(v, after[k], "[:#{k}] doesn't match.")
assert_equal(700, after[:bold])
end
# set_format_properties( hash_variable )
valid_properties = get_valid_format_properties
valid_properties.each do |k,v|
arg = {k => v}
fmt = Writeexcel::Format.new
before = get_format_property(fmt)
fmt.set_format_properties(arg)
after = get_format_property(fmt)
after.delete_if {|key, val| before[key] == val }
assert_equal(1, after.size, "change 1 property[:#{k}] but #{after.size} was changed.#{after.inspect}")
assert_equal(v, after[k], "[:#{k}] doesn't match.")
end
# set_format_properties( hash_variable, hash_variable... )
valid_properties = get_valid_format_properties
valid_properties.each do |k,v|
arg = {k => v}
arg2 = {:bold => 1}
fmt = Writeexcel::Format.new
before = get_format_property(fmt)
fmt.set_format_properties(arg, arg2)
after = get_format_property(fmt)
after.delete_if {|key, val| before[key] == val }
assert_equal(2, after.size, "change 1 property[:#{k}] but #{after.size} was changed.#{after.inspect}")
assert_equal(v, after[k], "[:#{k}] doesn't match.")
assert_equal(700, after[:bold])
end
# set_color by string
valid_color_string_number = get_valid_color_string_number
[:color , :bg_color, :fg_color].each do |coltype|
valid_color_string_number.each do |str, num|
fmt = Writeexcel::Format.new
before = get_format_property(fmt)
fmt.set_format_properties(coltype => str)
after = get_format_property(fmt)
after.delete_if {|key, val| before[key] == val }
assert_equal(1, after.size, "change 1 property[:#{coltype}:#{str}] but #{after.size} was changed.#{after.inspect}")
assert_equal(num, after[:"#{coltype}"], "[:#{coltype}:#{str}] doesn't match.")
end
end
end
def test_format_properties_with_invalid_value
end
def test_set_font
end
=begin
set_size()
Default state: Font size is 10
Default action: Set font size to 1
Valid args: Integer values from 1 to as big as your screen.
Set the font size. Excel adjusts the height of a row to accommodate the largest font size in the row. You can also explicitly specify the height of a row using the set_row() worksheet method.
=end
def test_set_size
# default state
assert_equal(10, @format.size)
# valid size from low to high
[1, 100, 100**10].each do |size|
fmt = Writeexcel::Format.new
fmt.set_size(size)
assert_equal(size, fmt.size, "valid size:#{size} - doesn't match.")
end
# invalid size -- size doesn't change
[-1, 0, 1/2.0, 'hello', true, false, nil, [0,0], {:invalid => "val"}].each do |size|
fmt = Writeexcel::Format.new
default = fmt.size
fmt.set_size(size)
assert_equal(default, fmt.size, "size:#{size.inspect} doesn't match.")
end
end
=begin
set_color()
Default state: Excels default color, usually black
Default action: Set the default color
Valid args: Integers from 8..63 or the following strings:
'black'
'blue'
'brown'
'cyan'
'gray'
'green'
'lime'
'magenta'
'navy'
'orange'
'pink'
'purple'
'red'
'silver'
'white'
'yellow'
Set the font colour. The set_color() method is used as follows:
format = workbook.add_format()
format.set_color('red')
worksheet.write(0, 0, 'wheelbarrow', format)
Note: The set_color() method is used to set the colour of the font in a cell.
To set the colour of a cell use the set_bg_color() and set_pattern() methods.
=end
def test_set_color
# default state
default_col = 0x7FFF
assert_equal(default_col, @format.color)
# valid color
# set by string
str_num = get_valid_color_string_number
str_num.each do |str,num|
fmt = Writeexcel::Format.new
fmt.set_color(str)
assert_equal(num, fmt.color)
end
# valid color
# set by number
[8, 36, 63].each do |color|
fmt = Writeexcel::Format.new
fmt.set_color(color)
assert_equal(color, fmt.color)
end
# invalid color
['color', :col, -1, 63.5, 10*10].each do |color|
fmt = Writeexcel::Format.new
fmt.set_color(color)
assert_equal(default_col, fmt.color, "color : #{color}")
end
# invalid color ...but...
# 0 <= color < 8 then color += 8 in order to valid value
[0, 7.5].each do |color|
fmt = Writeexcel::Format.new
fmt.set_color(color)
assert_equal((color + 8).to_i, fmt.color, "color : #{color}")
end
end
=begin
set_bold()
Default state: bold is off (internal value = 400)
Default action: Turn bold on
Valid args: 0, 1 [1]
Set the bold property of the font:
$format->set_bold(); # Turn bold on
[1] Actually, values in the range 100..1000 are also valid.
400 is normal, 700 is bold and 1000 is very bold indeed.
It is probably best to set the value to 1 and use normal bold.
=end
def test_set_bold
# default state
assert_equal(400, @format.bold)
# valid weight
fmt = Writeexcel::Format.new
fmt.set_bold
assert_equal(700, fmt.bold)
{0 => 400, 1 => 700, 100 => 100, 1000 => 1000}.each do |weight, value|
fmt = Writeexcel::Format.new
fmt.set_bold(weight)
assert_equal(value, fmt.bold)
end
# invalid weight
[-1, 99, 1001, 'bold'].each do |weight|
fmt = Writeexcel::Format.new
fmt.set_bold(weight)
assert_equal(400, fmt.bold, "weight : #{weight}")
end
end
=begin
set_italic()
Default state: Italic is off
Default action: Turn italic on
Valid args: 0, 1
Set the italic property of the font:
format.set_italic() # Turn italic on
=end
def test_set_italic
# default state
assert_equal(0, @format.italic)
# valid arg
fmt = Writeexcel::Format.new
fmt.set_italic
assert_equal(1, fmt.italic)
{0=>0, 1=>1}.each do |arg,value|
fmt = Writeexcel::Format.new
fmt.set_italic(arg)
assert_equal(value, fmt.italic, "arg : #{arg}")
end
# invalid arg
[-1, 0.2, 100, 'italic', true, false, nil].each do |arg|
assert_raise(ArgumentError,
"set_italic(#{arg}) : invalid arg. arg must be 0, 1 or none."){
fmt = Writeexcel::Format.new
fmt.set_italic(arg)
}
end
end
=begin
set_underline()
Default state: Underline is off
Default action: Turn on single underline
Valid args: 0 = No underline
1 = Single underline
2 = Double underline
33 = Single accounting underline
34 = Double accounting underline
Set the underline property of the font.
format.set_underline() # Single underline
=end
def test_set_underline
# default state
assert_equal(0, @format.underline, "default state")
# valid args
fmt = Writeexcel::Format.new
fmt.set_underline
assert_equal(1, fmt.underline, "No arg")
[0, 1, 2, 33, 34].each do |arg|
fmt = Writeexcel::Format.new
fmt.set_underline(arg)
assert_equal(arg, fmt.underline, "arg : #{arg}")
end
# invalid args
[-1, 0.2, 100, 'under', true, false, nil].each do |arg|
assert_raise(ArgumentError,
"set_underline(#{arg}) : arg must be 0, 1 or none, 2, 33, 34."){
fmt = Writeexcel::Format.new
fmt.set_underline(arg)
}
end
end
=begin
set_font_strikeout()
Default state: Strikeout is off
Default action: Turn strikeout on
Valid args: 0, 1
Set the strikeout property of the font.
=end
def test_set_font_strikeout
# default state
assert_equal(0, @format.font_strikeout, "default state")
# valid args
fmt = Writeexcel::Format.new
fmt.set_font_strikeout
assert_equal(1, fmt.font_strikeout, "No arg")
[0, 1].each do |arg|
fmt = Writeexcel::Format.new
fmt.set_font_strikeout(arg)
assert_equal(arg, fmt.font_strikeout, "arg : #{arg}")
end
# invalid args
[-1, 0.2, 100, 'strikeout', true, false, nil].each do |arg|
assert_raise(ArgumentError,
"set_font_strikeout(#{arg}) : arg must be 0, 1 or none."){
fmt = Writeexcel::Format.new
fmt.set_font_strikeout(arg)
}
end
end
=begin
set_font_script()
Default state: Super/Subscript is off
Default action: Turn Superscript on
Valid args: 0 = Normal
1 = Superscript
2 = Subscript
Set the superscript/subscript property of the font. This format is currently not very useful.
=end
def test_set_font_script
# default state
assert_equal(0, @format.font_script, "default state")
# valid args
fmt = Writeexcel::Format.new
fmt.set_font_script
assert_equal(1, fmt.font_script, "No arg")
[0, 1, 2].each do |arg|
fmt = Writeexcel::Format.new
fmt.set_font_script(arg)
assert_equal(arg, fmt.font_script, "arg : #{arg}")
end
# invalid args
[-1, 0.2, 100, 'script', true, false, nil].each do |arg|
assert_raise(ArgumentError,
"set_font_script(#{arg}) : arg must be 0, 1 or none, or 2."){
fmt = Writeexcel::Format.new
fmt.set_font_script(arg)
}
end
end
=begin
set_font_outline()
Default state: Outline is off
Default action: Turn outline on
Valid args: 0, 1
Macintosh only.
=end
def test_set_font_outline
# default state
assert_equal(0, @format.font_outline, "default state")
# valid args
fmt = Writeexcel::Format.new
fmt.set_font_outline
assert_equal(1, fmt.font_outline, "No arg")
[0, 1].each do |arg|
fmt = Writeexcel::Format.new
fmt.set_font_outline(arg)
assert_equal(arg, fmt.font_outline, "arg : #{arg}")
end
# invalid args
[-1, 0.2, 100, 'outline', true, false, nil].each do |arg|
assert_raise(ArgumentError,
"set_font_outline(#{arg}) : arg must be 0, 1 or none."){
fmt = Writeexcel::Format.new
fmt.set_font_outline(arg)
}
end
end
=begin
set_font_shadow()
Default state: Shadow is off
Default action: Turn shadow on
Valid args: 0, 1
Macintosh only.
=end
def test_set_font_shadow
# default state
assert_equal(0, @format.font_shadow, "default state")
# valid args
fmt = Writeexcel::Format.new
fmt.set_font_shadow
assert_equal(1, fmt.font_shadow, "No arg")
[0, 1].each do |arg|
fmt = Writeexcel::Format.new
fmt.set_font_shadow(arg)
assert_equal(arg, fmt.font_shadow, "arg : #{arg}")
end
# invalid args
[-1, 0.2, 100, 'shadow', true, false, nil].each do |arg|
assert_raise(ArgumentError,
"set_font_shadow(#{arg}) : arg must be 0, 1 or none."){
fmt = Writeexcel::Format.new
fmt.set_font_shadow(arg)
}
end
end
=begin
set_num_format()
Default state: General format
Default action: Format index 1
Valid args: See the following table
This method is used to define the numerical format of a number in Excel. It controls whether a number is displayed as an integer, a floating point number, a date, a currency value or some other user defined format.
=end
def test_set_num_format
# default state
assert_equal(0, @format.num_format)
# Excel built in Format Index (0 .. 49)
[0, 49].each do |n|
fmt = Writeexcel::Format.new
fmt.set_num_format(n)
assert_equal(n, fmt.num_format, "n: #{n}")
end
# Format string
["#,##0", "m/d/yy", "hh:mm:ss"].each do |string|
fmt = Writeexcel::Format.new
fmt.set_num_format(string)
assert_equal(string, fmt.num_format, "string: #{string}")
end
end
=begin
set_locked()
Default state: Cell locking is on
Default action: Turn locking on
Valid args: 0, 1
This property can be used to prevent modification of a cells
contents. Following Excel's convention, cell locking is
turned on by default. However, it only has an effect if
the worksheet has been protected, see the worksheet protect()
method.
locked = workbook.add_format()
locked.set_locked(1) # A non-op
unlocked = workbook.add_format()
locked.set_locked(0)
# Enable worksheet protection
worksheet.protect()
# This cell cannot be edited.
worksheet.write('A1', '=1+2', locked)
# This cell can be edited.
worksheet->write('A2', '=1+2', unlocked)
Note: This offers weak protection even with a password,
see the note in relation to the protect() method.
=end
def test_set_locked
# default state
assert_equal(1, @format.locked, "default state")
# valid args
fmt = Writeexcel::Format.new
fmt.set_locked
assert_equal(1, fmt.locked, "No arg")
[0, 1].each do |arg|
fmt = Writeexcel::Format.new
fmt.set_locked(arg)
assert_equal(arg, fmt.locked, "arg : #{arg}")
end
# invalid args
[-1, 0.2, 100, 'locked', true, false, nil].each do |arg|
assert_raise(ArgumentError,
"set_font_shadow(#{arg}) : arg must be 0, 1 or none."){
fmt = Writeexcel::Format.new
fmt.set_locked(arg)
}
end
end
=begin
set_hidden()
Default state: Formula hiding is off
Default action: Turn hiding on
Valid args: 0, 1
This property is used to hide a formula while still displaying
its result. This is generally used to hide complex calculations
from end users who are only interested in the result.
It only has an effect if the worksheet has been protected,
see the worksheet protect() method.
my hidden = workbook.add_format()
hidden.set_hidden()
# Enable worksheet protection
worksheet.protect()
# The formula in this cell isn't visible
worksheet.write('A1', '=1+2', hidden)
Note: This offers weak protection even with a password,
see the note in relation to the protect() method.
=end
def test_set_hidden
# default state
assert_equal(0, @format.hidden, "default state")
# valid args
fmt = Writeexcel::Format.new
fmt.set_hidden
assert_equal(1, fmt.hidden, "No arg")
[0, 1].each do |arg|
fmt = Writeexcel::Format.new
fmt.set_hidden(arg)
assert_equal(arg, fmt.hidden, "arg : #{arg}")
end
# invalid args
[-1, 0.2, 100, 'hidden', true, false, nil].each do |arg|
assert_raise(ArgumentError,
"set_font_shadow(#{arg}) : arg must be 0, 1 or none."){
fmt = Writeexcel::Format.new
fmt.set_hidden(arg)
}
end
end
=begin
set_align()
Default state: Alignment is off
Default action: Left alignment
Valid args: 'left' Horizontal
'center'
'right'
'fill'
'justify'
'center_across'
'top' Vertical
'vcenter'
'bottom'
'vjustify'
This method is used to set the horizontal and vertical text alignment
within a cell. Vertical and horizontal alignments can be combined.
The method is used as follows:
my $format = $workbook->add_format();
$format->set_align('center');
$format->set_align('vcenter');
$worksheet->set_row(0, 30);
$worksheet->write(0, 0, 'X', $format);
Text can be aligned across two or more adjacent cells using
the center_across property. However, for genuine merged cells
it is better to use the merge_range() worksheet method.
The vjustify (vertical justify) option can be used to provide
automatic text wrapping in a cell. The height of the cell will be
adjusted to accommodate the wrapped text. To specify where the text
wraps use the set_text_wrap() method.
=end
def test_set_align
# default state
assert_equal(0, @format.text_h_align)
assert_equal(2, @format.text_v_align)
# valid arg
valid_args = {'left'=>1, 'center'=>2, 'centre'=>2, 'right'=>3,
'fill'=>4, 'justify'=>5, 'center_across'=>6,
'centre_across'=>6, 'merge'=>6,
'top'=>0, 'vcenter'=>1, 'vcentre'=>1, 'bottom'=>2,
'vjustify'=>3 }
valid_args.each do |arg, value|
fmt = Writeexcel::Format.new
fmt.set_align(arg)
case arg
when 'left', 'center', 'centre', 'right', 'fill', 'justify',
'center_across', 'centre_across', 'merge'
assert_equal(value, fmt.text_h_align, "arg: #{arg}")
when 'top', 'vcenter', 'vcentre', 'bottom', 'vjustify'
assert_equal(value, fmt.text_v_align, "arg: #{arg}")
end
end
# invalid arg
[-1, 0, 1.5, nil, true, false, ['left','top'], {'top'=>0}].each do |arg|
fmt = Writeexcel::Format.new
val = get_format_property(fmt)
#print val.inspect
#exit
fmt.set_align(arg)
assert_equal(val[:align], fmt.text_h_align, "arg: #{arg} - text_h_align changed.")
assert_equal(val[:valign], fmt.text_v_align, "arg: #{arg} - text_v_align changed.")
end
end
=begin
set_center_across()
Default state: Center across selection is off
Default action: Turn center across on
Valid args: 1
Text can be aligned across two or more adjacent cells
using the set_center_across() method. This is an alias
for the set_align('center_across') method call.
Only one cell should contain the text,
the other cells should be blank:
format = workbook.add_format()
format.set_center_across()
worksheet.write(1, 1, 'Center across selection', format)
worksheet.write_blank(1, 2, format)
=end
def test_set_center_across
# default state
assert_equal(0, @format.text_h_align)
# method call then center_across is set. if arg is none, numeric, string, whatever.
@format.set_center_across
assert_equal(6, @format.text_h_align)
end
=begin
set_text_wrap()
Default state: Text wrap is off
Default action: Turn text wrap on
Valid args: 0, 1
Here is an example using the text wrap property, the escape
character \n is used to indicate the end of line:
format = workbook.add_format()
format.set_text_wrap()
worksheet.write(0, 0, "It's\na bum\nwrap", format)
=end
def test_set_text_wrap
# default state
assert_equal(0, @format.text_wrap, "default state")
# valid args
fmt = Writeexcel::Format.new
fmt.set_text_wrap
assert_equal(1, fmt.text_wrap, "No arg")
[0, 1].each do |arg|
fmt = Writeexcel::Format.new
fmt.set_text_wrap(arg)
assert_equal(arg, fmt.text_wrap, "arg : #{arg}")
end
# invalid args
[-1, 0.2, 100, 'text_wrap', true, false, nil].each do |arg|
assert_raise(ArgumentError,
"set_text_wrap(#{arg}) : arg must be 0, 1 or none."){
fmt = Writeexcel::Format.new
fmt.set_text_wrap(arg)
}
end
end
=begin
set_rotation()
Default state: Text rotation is off
Default action: None
Valid args: Integers in the range -90 to 90 and 270
Set the rotation of the text in a cell. The rotation can be
any angle in the range -90 to 90 degrees.
format = workbook.add_format()
format.set_rotation(30)
worksheet.write(0, 0, 'This text is rotated', format)
The angle 270 is also supported. This indicates text where
the letters run from top to bottom.
=end
def test_set_rotation
# default state
assert_equal(0, @format.rotation)
# # valid args -90 <= angle <= 90, 270 angle can be float or double
# [-90.0, 89, 0, 89, 90, 270].each do |angle|
# fmt = Writeexcel::Format.new
# fmt.set_rotation(angle)
# assert_equal(angle, fmt.rotation, "angle: #{angle}")
# end
end
=begin
set_indent()
Default state: Text indentation is off
Default action: Indent text 1 level
Valid args: Positive integers
This method can be used to indent text. The argument, which should
be an integer, is taken as the level of indentation:
format = workbook.add_format()
format.set_indent(2)
worksheet.write(0, 0, 'This text is indented', format)
Indentation is a horizontal alignment property. It will override
any other horizontal properties but it can be used in conjunction
with vertical properties.
=end
def test_set_indent
# default state
assert_equal(0, @format.indent)
# valid arg -- Positive integers
[1, 10000000].each do |indent|
fmt = Writeexcel::Format.new
fmt.set_indent(indent)
assert_equal(indent, fmt.indent, "indent: #{indent}")
end
# invalid arg
[].each do |indent|
end
end
=begin
set_shrink()
Default state: Text shrinking is off
Default action: Turn "shrink to fit" on
Valid args: 1
This method can be used to shrink text so that it fits in a cell.
format = workbook.add_format()
format.set_shrink()
worksheet.write(0, 0, 'Honey, I shrunk the text!', format)
=end
def test_set_shrink
# default state
assert_equal(0, @format.shrink)
end
=begin
set_text_justlast()
Default state: Justify last is off
Default action: Turn justify last on
Valid args: 0, 1
Only applies to Far Eastern versions of Excel.
=end
def test_set_text_justlast
# default state
assert_equal(0, @format.text_justlast)
end
=begin
set_pattern()
Default state: Pattern is off
Default action: Solid fill is on
Valid args: 0 .. 18
Set the background pattern of a cell.
=end
def test_set_pattern
# default state
assert_equal(0, @format.pattern)
end
=begin
set_bg_color()
Default state: Color is off
Default action: Solid fill.
Valid args: See set_color()
The set_bg_color() method can be used to set the background
colour of a pattern. Patterns are defined via the set_pattern()
method. If a pattern hasn't been defined then a solid fill
pattern is used as the default.
Here is an example of how to set up a solid fill in a cell:
format = workbook.add_format()
format.set_pattern() # This is optional when using a solid fill
format.set_bg_color('green')
worksheet.write('A1', 'Ray', format)
=end
def test_set_bg_color
end
=begin
set_fg_color()
Default state: Color is off
Default action: Solid fill.
Valid args: See set_color()
The set_fg_color() method can be used to set
the foreground colour of a pattern.
=end
def test_set_fg_color
end
=begin
set_border()
Also applies to: set_bottom()
set_top()
set_left()
set_right()
Default state: Border is off
Default action: Set border type 1
Valid args: 0-13, See below.
A cell border is comprised of a border on the bottom, top,
left and right. These can be set to the same value using
set_border() or individually using the relevant method
calls shown above.
The following shows the border styles sorted
by WriteExcel index number:
Index Name Weight Style
===== ============= ====== ===========
0 None 0
1 Continuous 1 -----------
2 Continuous 2 -----------
3 Dash 1 - - - - - -
4 Dot 1 . . . . . .
5 Continuous 3 -----------
6 Double 3 ===========
7 Continuous 0 -----------
8 Dash 2 - - - - - -
9 Dash Dot 1 - . - . - .
10 Dash Dot 2 - . - . - .
11 Dash Dot Dot 1 - . . - . .
12 Dash Dot Dot 2 - . . - . .
13 SlantDash Dot 2 / - . / - .
The following shows the borders sorted by style:
Name Weight Style Index
============= ====== =========== =====
Continuous 0 ----------- 7
Continuous 1 ----------- 1
Continuous 2 ----------- 2
Continuous 3 ----------- 5
Dash 1 - - - - - - 3
Dash 2 - - - - - - 8
Dash Dot 1 - . - . - . 9
Dash Dot 2 - . - . - . 10
Dash Dot Dot 1 - . . - . . 11
Dash Dot Dot 2 - . . - . . 12
Dot 1 . . . . . . 4
Double 3 =========== 6
None 0 0
SlantDash Dot 2 / - . / - . 13
The following shows the borders in the order shown in the Excel Dialog.
Index Style Index Style
===== ===== ===== =====
0 None 12 - . . - . .
7 ----------- 13 / - . / - .
4 . . . . . . 10 - . - . - .
11 - . . - . . 8 - - - - - -
9 - . - . - . 2 -----------
3 - - - - - - 5 -----------
1 ----------- 6 ===========
=end
def test_set_border
end
=begin
set_border_color()
Also applies to: set_bottom_color()
set_top_color()
set_left_color()
set_right_color()
Default state: Color is off
Default action: Undefined
Valid args: See set_color()
Set the colour of the cell borders. A cell border is comprised of a border
on the bottom, top, left and right. These can be set to the same colour
using set_border_color() or individually using the relevant method
calls shown above.
=end
def test_set_border_color
end
=begin
copy($format)
This method is used to copy all of the properties
from one Format object to another:
lorry1 = workbook.add_format()
lorry1.set_bold()
lorry1.set_italic()
lorry1.set_color('red') # lorry1 is bold, italic and red
my lorry2 = workbook.add_format()
lorry2.copy(lorry1)
lorry2.set_color('yellow') # lorry2 is bold, italic and yellow
The copy() method is only useful if you are using the method interface
to Format properties. It generally isn't required if you are setting
Format properties directly using hashes.
Note: this is not a copy constructor, both objects must exist prior to copying.
=end
def test_xf_biff_size
perl_file = "#{PERL_OUTDIR}/file_xf_biff"
size = File.size(perl_file)
@ruby_file.print(@format.get_xf)
rsize = @ruby_file.size
assert_equal(size, rsize, "File sizes not the same")
end
# Because of the modifications to bg_color and fg_color, I know this
# test will fail. This is ok.
#def test_xf_biff_contents
# perl_file = "perl_output/f_xf_biff"
# @fh = File.new(@ruby_file,"w+")
# @fh.print(@format.xf_biff)
# @fh.close
# contents = IO.readlines(perl_file)
# rcontents = IO.readlines(@ruby_file)
# assert_equal(contents,rcontents,"Contents not the same")
#end
def test_font_biff_size
perl_file = "#{PERL_OUTDIR}/file_font_biff"
@ruby_file.print(@format.get_font)
contents = IO.readlines(perl_file)
@ruby_file.rewind
rcontents = @ruby_file.readlines
assert_equal(contents, rcontents, "Contents not the same")
end
def test_font_biff_contents
perl_file = "#{PERL_OUTDIR}/file_font_biff"
@ruby_file.print(@format.get_font)
contents = IO.readlines(perl_file)
@ruby_file.rewind
rcontents = @ruby_file.readlines
assert_equal(contents, rcontents, "Contents not the same")
end
def test_get_font_key_size
perl_file = "#{PERL_OUTDIR}/file_font_key"
@ruby_file.print(@format.get_font_key)
assert_equal(File.size(perl_file), @ruby_file.size, "Bad file size")
end
def test_get_font_key_contents
perl_file = "#{PERL_OUTDIR}/file_font_key"
@ruby_file.print(@format.get_font_key)
contents = IO.readlines(perl_file)
@ruby_file.rewind
rcontents = @ruby_file.readlines
assert_equal(contents, rcontents, "Contents not the same")
end
def test_initialize
assert_nothing_raised {
Writeexcel::Format.new(
:bold => true,
:size => 10,
:color => 'black',
:fg_color => 43,
:align => 'top',
:text_wrap => true,
:border => 1
)
}
end
# added by Nakamura
def test_get_xf
perl_file = "#{PERL_OUTDIR}/file_xf_biff"
size = File.size(perl_file)
@ruby_file.print(@format.get_xf)
rsize = @ruby_file.size
assert_equal(size, rsize, "File sizes not the same")
compare_file(perl_file, @ruby_file)
end
def test_get_font
perl_file = "#{PERL_OUTDIR}/file_font_biff"
size = File.size(perl_file)
@ruby_file.print(@format.get_font)
rsize = @ruby_file.size
assert_equal(size, rsize, "File sizes not the same")
compare_file(perl_file, @ruby_file)
end
def test_get_font_key
perl_file = "#{PERL_OUTDIR}/file_font_key"
size = File.size(perl_file)
@ruby_file.print(@format.get_font_key)
rsize = @ruby_file.size
assert_equal(size, rsize, "File sizes not the same")
compare_file(perl_file, @ruby_file)
end
def test_copy
format1 = Writeexcel::Format.new
format2 = Writeexcel::Format.new
format1.set_size(12)
format2.copy(format1)
assert_equal(format1.size, format2.size)
end
# -----------------------------------------------------------------------------
def get_valid_format_properties
{
:font => 'Times New Roman',
:size => 30,
:color => 8,
:italic => 1,
:underline => 1,
:font_strikeout => 1,
:font_script => 1,
:font_outline => 1,
:font_shadow => 1,
:locked => 0,
:hidden => 1,
:text_wrap => 1,
:text_justlast => 1,
:indent => 2,
:shrink => 1,
:pattern => 18,
:bg_color => 30,
:fg_color => 63
}
end
def get_valid_color_string_number
{
:black => 8,
:blue => 12,
:brown => 16,
:cyan => 15,
:gray => 23,
:green => 17,
:lime => 11,
:magenta => 14,
:navy => 18,
:orange => 53,
:pink => 33,
:purple => 20,
:red => 10,
:silver => 22,
:white => 9,
:yellow => 13
}
end
# :rotation => -90,
# :center_across => 1,
# :align => 'left',
def get_format_property(format)
text_h_align = {
1 => 'left',
2 => 'center/centre',
3 => 'right',
4 => 'fill',
5 => 'justiry',
6 => 'center_across/centre_across/merge',
7 => 'distributed/equal_space'
}
text_v_align = {
0 => 'top',
1 => 'vcenter/vcentre',
2 => 'bottom',
3 => 'vjustify',
4 => 'vdistributed/vequal_space'
}
return {
:font => format.font,
:size => format.size,
:color => format.color,
:bold => format.bold,
:italic => format.italic,
:underline => format.underline,
:font_strikeout => format.font_strikeout,
:font_script => format.font_script,
:font_outline => format.font_outline,
:font_shadow => format.font_shadow,
:num_format => format.num_format,
:locked => format.locked,
:hidden => format.hidden,
:align => format.text_h_align,
:valign => format.text_v_align,
:rotation => format.rotation,
:text_wrap => format.text_wrap,
:text_justlast => format.text_justlast,
:center_across => format.text_h_align,
:indent => format.indent,
:shrink => format.shrink,
:pattern => format.pattern,
:bg_color => format.bg_color,
:fg_color => format.fg_color,
:bottom => format.bottom,
:top => format.top,
:left => format.left,
:right => format.right,
:bottom_color => format.bottom_color,
:top_color => format.top_color,
:left_color => format.left_color,
:right_color => format.right_color
}
end
end
|
Radanisk/writeexcel
|
examples/chart_bar.rb
|
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
#
###############################################################################
#
# A simple demo of Bar chart in Spreadsheet::WriteExcel.
#
# reverse('・ゥ'), December 2009, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
# Create a new workbook called simple.xls and add a worksheet
workbook = WriteExcel.new('chart_bar.xls')
worksheet = workbook.add_worksheet
bold = workbook.add_format(:bold => 1)
# Add the worksheet data that the charts will refer to.
headings = [ 'Category', 'Values 1', 'Values 2' ]
data = [
[ 2, 3, 4, 5, 6, 7 ],
[ 1, 4, 5, 2, 1, 5 ],
[ 3, 6, 7, 5, 4, 3 ]
]
worksheet.write('A1', headings, bold)
worksheet.write('A2', data)
###############################################################################
#
# Example 1. A minimal chart.
#
chart1 = workbook.add_chart(:type => 'Chart::Bar')
# Add values only. Use the default categories.
chart1.add_series( :values => '=Sheet1!$B$2:$B$7' )
###############################################################################
#
# Example 2. A minimal chart with user specified categories (X axis)
# and a series name.
#
chart2 = workbook.add_chart(:type => 'Chart::Bar')
# Configure the series.
chart2.add_series(
:categories => '=Sheet1!$A$2:$A$7',
:values => '=Sheet1!$B$2:$B$7',
:name => 'Test data series 1'
)
###############################################################################
#
# Example 3. Same as previous chart but with added title and axes labels.
#
chart3 = workbook.add_chart(:type => 'Chart::Bar')
# Configure the series.
chart3.add_series(
:categories => '=Sheet1!$A$2:$A$7',
:values => '=Sheet1!$B$2:$B$7',
:name => 'Test data series 1'
)
# Add some labels.
chart3.set_title( :name => 'Results of sample analysis' )
chart3.set_x_axis( :name => 'Sample number' )
chart3.set_y_axis( :name => 'Sample length (cm)' )
###############################################################################
#
# Example 4. Same as previous chart but with an added series
#
chart4 = workbook.add_chart(:name => 'Results Chart', :type => 'Chart::Bar')
# Configure the series.
chart4.add_series(
:categories => '=Sheet1!$A$2:$A$7',
:values => '=Sheet1!$B$2:$B$7',
:name => 'Test data series 1'
)
# Add another series.
chart4.add_series(
:categories => '=Sheet1!$A$2:$A$7',
:values => '=Sheet1!$C$2:$C$7',
:name => 'Test data series 2'
)
# Add some labels.
chart4.set_title( :name => 'Results of sample analysis' )
chart4.set_x_axis( :name => 'Sample number' )
chart4.set_y_axis( :name => 'Sample length (cm)' )
###############################################################################
#
# Example 5. Same as Example 3 but as an embedded chart.
#
chart5 = workbook.add_chart(:type => 'Chart::Bar', :embedded => 1)
# Configure the series.
chart5.add_series(
:categories => '=Sheet1!$A$2:$A$7',
:values => '=Sheet1!$B$2:$B$7',
:name => 'Test data series 1'
)
# Add some labels.
chart5.set_title(:name => 'Results of sample analysis' )
chart5.set_x_axis(:name => 'Sample number')
chart5.set_y_axis(:name => 'Sample length (cm)')
# Insert the chart into the main worksheet.
worksheet.insert_chart('E2', chart5)
# File save
workbook.close
|
Radanisk/writeexcel
|
test/test_50_name_stored.rb
|
<gh_stars>10-100
# -*- coding: utf-8 -*-
##########################################################################
# test_50_name_stored.rb
#
# Tests for the Excel EXTERNSHEET and NAME records created by print_are()..
#
# reverse('ゥ'), September 2008, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
#########################################################################
require 'helper'
require 'stringio'
class TC_Name_Stored < Test::Unit::TestCase
def setup
@test_file = StringIO.new
@workbook = WriteExcel.new(@test_file)
@worksheet = @workbook.add_worksheet
end
def test_print_area_name_with_simple_range
caption = " \tNAME for worksheet1.print_area('A1:B12')"
name = [0x06].pack('C')
encoding = 0
sheet_index = 1
formula = ['3B000000000B0000000100'].pack('H*')
result = @workbook.__send__("store_name",
name,
encoding,
sheet_index,
formula
)
target = [%w(
18 00 1B 00 20 00 00 01 0B 00 00 00 01 00 00 00
00 00 00 06 3B 00 00 00 00 0B 00 00 00 01 00
).join('')].pack('H*')
# result = _unpack_name(result)
# target = _unpack_name(target)
assert_equal(unpack_record(target), unpack_record(result))
end
def test_print_area_name_with_simple_range_in_sheet_3
caption = " \tNAME for worksheet3.print_area('G7:H8')"
name = [0x06].pack('C')
encoding = 0
sheet_index = 3
formula = ['3B02000600070006000700'].pack('H*')
result = @workbook.__send__("store_name",
name,
encoding,
sheet_index,
formula
)
target = [%w(
18 00 1B 00 20 00 00 01 0B 00 00 00 03 00 00 00
00 00 00 06 3B 02 00 06 00 07 00 06 00 07 00
).join('')].pack('H*')
# result = _unpack_name(result)
# target = _unpack_name(target)
assert_equal(unpack_record(target), unpack_record(result))
end
def test_for_repeat_rows_name
caption = " \tNAME for worksheet1.repeat_rows(0, 9)"
name = [0x07].pack('C')
encoding = 0
sheet_index = 1
formula = ['3B0000000009000000FF00'].pack('H*')
result = @workbook.__send__("store_name",
name,
encoding,
sheet_index,
formula
)
target = [%w(
18 00 1B 00 20 00 00 01 0B 00 00 00 01 00 00 00
00 00 00 07 3B 00 00 00 00 09 00 00 00 FF 00
).join('')].pack('H*')
# result = _unpack_name(result)
# target = _unpack_name(target)
assert_equal(unpack_record(target), unpack_record(result))
end
def test_for_repeat_rows_name_on_sheet_3
caption = " \tNAME for worksheet3.repeat_rows(6, 7)"
name = [0x07].pack('C')
encoding = 0
sheet_index = 1
formula = ['3B0000000009000000FF00'].pack('H*')
result = @workbook.__send__("store_name",
name,
encoding,
sheet_index,
formula
)
target = [%w(
18 00 1B 00 20 00 00 01 0B 00 00 00 01 00 00 00
00 00 00 07 3B 00 00 00 00 09 00 00 00 FF 00
).join('')].pack('H*')
# result = _unpack_name(result)
# target = _unpack_name(target)
assert_equal(unpack_record(target), unpack_record(result))
end
def test_for_repeat_columns_name
caption = " \tNAME for worksheet1.repeat_columns('A:J')"
name = [0x07].pack('C')
encoding = 0
sheet_index = 1
formula = ['3B00000000FFFF00000900'].pack('H*')
result = @workbook.__send__("store_name",
name,
encoding,
sheet_index,
formula
)
target = [%w(
18 00 1B 00 20 00 00 01 0B 00 00 00 01 00 00 00
00 00 00 07 3B 00 00 00 00 FF FF 00 00 09 00
).join('')].pack('H*')
# result = _unpack_name(result)
# target = _unpack_name(target)
assert_equal(unpack_record(target), unpack_record(result))
end
def test_for_repeat_rows_and_repeat_columns_together_name
caption = " \tNAME for repeat_rows(1, 2) repeat_columns(3, 4)"
name = [0x07].pack('C')
encoding = 0
sheet_index = 1
formula = ['2917003B00000000FFFF030004003B0000010002000000FF0010'].pack('H*')
result = @workbook.__send__("store_name",
name,
encoding,
sheet_index,
formula
)
target = [%w(
18 00 2A 00 20 00 00 01 1A 00 00 00 01 00 00 00
00 00 00 07 29 17 00 3B 00 00 00 00 FF FF 03 00
04 00 3B 00 00 01 00 02 00 00 00 FF 00 10
).join('')].pack('H*')
# result = _unpack_name(result)
# target = _unpack_name(target)
assert_equal(unpack_record(target), unpack_record(result))
end
def test_for_print_area_name_with_simple_range
caption = " \tNAME for worksheet1.autofilter('A1:C5')"
name = [0x0D].pack('C')
encoding = 0
sheet_index = 1
formula = ['3B00000000040000000200'].pack('H*')
result = @workbook.__send__("store_name",
name,
encoding,
sheet_index,
formula
)
target = [%w(
18 00 1B 00 21 00 00 01 0B 00 00 00 01 00 00 00
00 00 00 0D 3B 00 00 00 00 04 00 00 00 02 00
).join('')].pack('H*')
# result = _unpack_name(result)
# target = _unpack_name(target)
assert_equal(unpack_record(target), unpack_record(result))
end
def test_for_define_name_global_name
caption = " \tNAME for worksheet1.define_name('Foo', ...)"
name = 'Foo'
encoding = 0
sheet_index = 0
formula = ['3A000007000100'].pack('H*')
result = @workbook.__send__("store_name",
name,
encoding,
sheet_index,
formula
)
target = [%w(
18 00 19 00 00 00 00 03 07 00 00 00 00 00 00 00
00 00 00 46 6F 6F 3A 00 00 07 00 01 00
).join('')].pack('H*')
# result = _unpack_name(result)
# target = _unpack_name(target)
assert_equal(unpack_record(target), unpack_record(result))
end
###############################################################################
#
# _unpack_name()
#
# Unpack 1 or more NAME structures into a AoH for easier comparison.
#
def _unpack_name(data)
names = Array.new
while data.length > 0
name = Hash.new
name['record'] = data[0, 2].unpack('v')[0]
data[0, 2] = ''
name['length'] = data[0, 2].unpack('v')[0]
data[0, 2] = ''
name['flags'] = data[0, 2].unpack('v')[0]
data[0, 2] = ''
name['shortcut'] = data[0, 1].unpack('C')[0]
data[0, 1] = ''
name['str_len'] = data[0, 1].unpack('C')[0]
data[0, 1] = ''
name['formula_len'] = data[0, 2].unpack('v')[0]
data[0, 2] = ''
name['itals'] = data[0, 2].unpack('v')[0]
data[0, 2] = ''
name['sheet_index'] = data[0, 2].unpack('v')[0]
data[0, 2] = ''
name['menu_len'] = data[0, 1].unpack('C')[0]
data[0, 1] = ''
name['desc_len'] = data[0, 1].unpack('C')[0]
data[0, 1] = ''
name['help_len'] = data[0, 1].unpack('C')[0]
data[0, 1] = ''
name['status_len'] = data[0, 1].unpack('C')[0]
data[0, 1] = ''
name['encoding'] = data[0, 1].unpack('C')[0]
data[0, 1] = ''
# Decode the individual flag fields.
flag = Hash.new
flag['hidden'] = name['flags'] & 0x0001
flag['function'] = name['flags'] & 0x0002
flag['vb'] = name['flags'] & 0x0004
flag['macro'] = name['flags'] & 0x0008
flag['complex'] = name['flags'] & 0x0010
flag['builtin'] = name['flags'] & 0x0020
flag['group'] = name['flags'] & 0x0FC0
flag['binary'] = name['flags'] & 0x1000
name['flags'] = flag
# Decode the string part of the NAME structure.
if name['encoding'] == 1
# UTF-16 name. Leave in hex.
name['string'] = data[0, 2 * name['str_len']].unpack('H*')[0].upcase
data[0, 2 * name['str_len']] = ''
elsif flag['builtin'] != 0
# 1 digit builtin name. Leave in hex.
name['string'] = data[0, name['str_len']].unpack('H*')[0].upcase
data[0, name['str_len']] = ''
else
# ASCII name.
name['string'] = data[0, name['str_len']].unpack('C*').pack('C*')
data[0, name['str_len']] = ''
end
# Keep the formula as a hex string.
name['formula'] = data[0, name['formula_len']].unpack('H*')[0].upcase
data[0, name['formula_len']] = ''
names << name
end
names
end
def assert_hash_equal?(result, target)
assert_equal(result.keys.sort, target.keys.sort)
result.each_key do |key|
assert_equal(result[key], target[key])
end
end
end
|
Radanisk/writeexcel
|
utils/add_magic_comment.rb
|
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
require 'stringio'
#
# magic commentを付与する
#
# カレントディレクトリ以下の.rbファイルパスの配列を返す
def rb_files
Dir.glob("./**/*\.rb")
end
# カレントディレクトリ以下の.orgファイルパスの配列を返す
def org_files
Dir.glob("./**/*\.org")
end
# ファイル名を*.orgに変更し、変更後のファイル名を返す
def rename_to_org(file)
orgfile = change_ext_name(file, 'org')
File.rename(file, orgfile)
orgfile
end
# ファイル名の拡張子を変更した際のフルパスを返す(実際の変更はしない)
def change_ext_name(file, new_ext)
File.join(File.dirname(file), File.basename(file, ".*")) + ".#{new_ext}"
end
# shebang か
def shebang?(line)
line =~ /^#!.*ruby/ ? true : false
end
# magic_comment か
def magic_comment?(line)
line =~ /coding[:=]\s*[\w.-]+/ ? true : false
end
def add_magic_comment(input = nil, output = nil)
input ||= STDIN
output ||= STDOUT
magic_comment = "# -*- coding: utf-8 -*-\n"
if shebang?(line = input.gets)
output.write(line)
if magic_comment?(line = input.gets)
output.write(line)
else
output.write(magic_comment)
output.write(line)
end
elsif magic_comment?(line)
output.write(line)
else
output.write(magic_comment)
output.write(line)
end
while(line = input.gets)
output.write(line)
end
end
if $0 == __FILE__
rb_files.each do |file|
orgfile = rename_to_org(file)
print("#{file}: renamed to #{orgfile}.\n")
io = StringIO.new
File.open(orgfile) do |fin|
File.open(file, 'w') { |fout| add_magic_comment(fin, fout) }
end
print("#{file}: contains magic comment.\n")
end
#
# orgファイルをすべて消すには、以下を有効に。
#
org_files.each { |f| File.unlink(f) }
end
|
Radanisk/writeexcel
|
examples/copyformat.rb
|
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
###############################################################################
#
# Example of how to use the format copying method with WriteExcel #
# reverse('©'), March 2001, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
# Create workbook1
workbook1 = WriteExcel.new("workbook1.xls")
worksheet1 = workbook1.add_worksheet
format1a = workbook1.add_format
format1b = workbook1.add_format
# Create workbook2
workbook2 = WriteExcel.new("workbook2.xls")
worksheet2 = workbook2.add_worksheet
format2a = workbook2.add_format
format2b = workbook2.add_format
# Create a global format object that isn't tied to a workbook
global_format = Format.new
# Set the formatting
global_format.set_color('blue')
global_format.set_bold
global_format.set_italic
# Create another example format
format1b.set_color('red')
# Copy the global format properties to the worksheet formats
format1a.copy(global_format)
format2a.copy(global_format)
# Copy a format from worksheet1 to worksheet2
format2b.copy(format1b)
# Write some output
worksheet1.write(0, 0, "Ciao", format1a)
worksheet1.write(1, 0, "Ciao", format1b)
worksheet2.write(0, 0, "Hello", format2a)
worksheet2.write(1, 0, "Hello", format2b)
workbook1.close
workbook2.close
|
Radanisk/writeexcel
|
test/test_02_merge_formats.rb
|
<reponame>Radanisk/writeexcel
# -*- coding: utf-8 -*-
require 'helper'
require 'stringio'
class TC_merge_formats < Test::Unit::TestCase
def setup
@workbook = WriteExcel.new(StringIO.new)
@worksheet = @workbook.add_worksheet
@merged_format = @workbook.add_format(:bold => 1)
@non_merged_format = @workbook.add_format(:bold => 1)
@worksheet.set_row( 5, nil, @merged_format)
@worksheet.set_column('G:G', nil, @merged_format)
end
def test_some
# Test 1 Normal usage.
assert_nothing_raised { @worksheet.write('A1', 'Test', @non_merged_format) }
assert_nothing_raised { @worksheet.write('A3:B4', 'Test', @merged_format) }
# Test 2 Non merge format in merged cells.
assert_nothing_raised {
@worksheet.merge_range('D3:E4', 'Test', @non_merged_format)
}
# Test 3 Merge format in column.
assert_nothing_raised { @worksheet.write('G1', 'Test') }
# Test 4 Merge format in row.
assert_nothing_raised { @worksheet.write('A6', 'Test') }
# Test 5 Merge format in column and row.
assert_nothing_raised { @worksheet.write('G6', 'Test') }
# Test 6 No merge format in column and row.
assert_nothing_raised { @worksheet.write('H7', 'Test') }
# Test 7 Normal usage again.
assert_nothing_raised {
@worksheet.write('A1', 'Test', @non_merged_format)
}
assert_nothing_raised {
@worksheet.merge_range('A3:B4', 'Test', @merged_format)
}
end
end
|
Radanisk/writeexcel
|
test/test_22_mso_drawing_group.rb
|
<gh_stars>10-100
# -*- coding: utf-8 -*-
##########################################################################
# test_22_mso_drawing_group.rb
#
# Tests for the internal methods used to write the MSODRAWINGGROUP record.
#
# all test is commented out because related method was set to
# private method. Before that, all test passed.
#
#
#
#
# reverse('©'), September 2005, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
#########################################################################
require 'helper'
require 'stringio'
class TC_mso_drawing_group < Test::Unit::TestCase
def test_dummy
assert(true)
end
def setup
@workbook = WriteExcel.new(StringIO.new)
@worksheet1 = @workbook.add_worksheet
@worksheet2 = @workbook.add_worksheet
@worksheet3 = @workbook.add_worksheet
end
def teardown
if @workbook.instance_variable_get(:@filehandle)
@workbook.instance_variable_get(:@filehandle).close(true)
end
if @worksheet.instance_variable_get(:@filehandle)
@worksheet.instance_variable_get(:@filehandle).close(true)
end
end
=begin
def test_1_time
count = 1
for i in 1 .. count
@worksheet1.write_comment(i -1, 0, 'aaa')
end
@workbook.calc_mso_sizes
caption = sprintf(" \tSheet1: %4d comments.", count)
target = %w(
EB 00 5A 00 0F 00 00 F0 52 00 00 00 00 00 06 F0
18 00 00 00 02 04 00 00 02 00 00 00 02 00 00 00
01 00 00 00 01 00 00 00 02 00 00 00 33 00 0B F0
12 00 00 00 BF 00 08 00 08 00 81 01 09 00 00 08
C0 01 40 00 00 08 40 00 1E F1 10 00 00 00 0D 00
00 08 0C 00 00 08 17 00 00 08 F7 00 00 10
).join(' ')
result = unpack_record(@workbook.add_mso_drawing_group)
assert_equal(target, result, caption)
# Test the parameters pass to the worksheets
caption += ' (params)'
result_ids = []
target_ids = [
1024, 1, 2, 1025,
]
@workbook.sheets.each do |sheet|
sheet.object_ids.each {|id| result_ids.push(id) }
end
assert_equal(target_ids, result_ids, caption)
end
def test_2_times
count = 2
for i in 1 .. count
@worksheet1.write_comment(i -1, 0, 'aaa')
end
@workbook.calc_mso_sizes
target = %w(
EB 00 5A 00 0F 00 00 F0 52 00 00 00 00 00 06 F0
18 00 00 00 03 04 00 00 02 00 00 00 03 00 00 00
01 00 00 00 01 00 00 00 03 00 00 00 33 00 0B F0
12 00 00 00 BF 00 08 00 08 00 81 01 09 00 00 08
C0 01 40 00 00 08 40 00 1E F1 10 00 00 00 0D 00
00 08 0C 00 00 08 17 00 00 08 F7 00 00 10
).join(' ')
caption = sprintf( " \tSheet1: %4d comments.", count)
result = unpack_record(@workbook.add_mso_drawing_group)
assert_equal(target, result, caption)
# Test the parameters pass to the worksheets
caption += ' (params)'
result_ids = []
target_ids = [
1024, 1, 3, 1026,
]
@workbook.sheets.each do |sheet|
sheet.object_ids.each {|id| result_ids.push(id) }
end
assert_equal(target_ids, result_ids, caption)
end
def test_3_times
count = 3
for i in 1 .. count
@worksheet1.write_comment(i -1, 0, 'aaa')
end
@workbook.calc_mso_sizes
target = %w(
EB 00 5A 00 0F 00 00 F0 52 00 00 00 00 00 06 F0
18 00 00 00 04 04 00 00 02 00 00 00 04 00 00 00
01 00 00 00 01 00 00 00 04 00 00 00 33 00 0B F0
12 00 00 00 BF 00 08 00 08 00 81 01 09 00 00 08
C0 01 40 00 00 08 40 00 1E F1 10 00 00 00 0D 00
00 08 0C 00 00 08 17 00 00 08 F7 00 00 10
).join(' ')
caption = sprintf( " \tSheet1: %4d comments.", count)
result = unpack_record(@workbook.add_mso_drawing_group)
assert_equal(target, result, caption)
# Test the parameters pass to the worksheets
caption += ' (params)'
result_ids = []
target_ids = [
1024, 1, 4, 1027
]
@workbook.sheets.each do |sheet|
sheet.object_ids.each {|id| result_ids.push(id) }
end
assert_equal(target_ids, result_ids, caption)
end
def test_1023_times
count = 1023
for i in 1 .. count
@worksheet1.write_comment(i -1, 0, 'aaa')
end
@workbook.calc_mso_sizes
target = %w(
EB 00 5A 00 0F 00 00 F0 52 00 00 00 00 00 06 F0
18 00 00 00 00 08 00 00 02 00 00 00 00 04 00 00
01 00 00 00 01 00 00 00 00 04 00 00 33 00 0B F0
12 00 00 00 BF 00 08 00 08 00 81 01 09 00 00 08
C0 01 40 00 00 08 40 00 1E F1 10 00 00 00 0D 00
00 08 0C 00 00 08 17 00 00 08 F7 00 00 10
).join(' ')
caption = sprintf( " \tSheet1: %4d comments.", count)
result = unpack_record(@workbook.add_mso_drawing_group)
assert_equal(target, result, caption)
# Test the parameters pass to the worksheets
caption += ' (params)'
result_ids = []
target_ids = [
1024, 1, 1024, 2047
]
@workbook.sheets.each do |sheet|
sheet.object_ids.each {|id| result_ids.push(id) }
end
assert_equal(target_ids, result_ids, caption)
end
def test_1024_times
count = 1024
for i in 1 .. count
@worksheet1.write_comment(i -1, 0, 'aaa')
end
@workbook.calc_mso_sizes
target = %w(
EB 00 62 00 0F 00 00 F0 5A 00 00 00 00 00 06 F0
20 00 00 00 01 08 00 00 03 00 00 00 01 04 00 00
01 00 00 00 01 00 00 00 00 04 00 00 01 00 00 00
01 00 00 00 33 00 0B F0 12 00 00 00 BF 00 08 00
08 00 81 01 09 00 00 08 C0 01 40 00 00 08 40 00
1E F1 10 00 00 00 0D 00 00 08 0C 00 00 08 17 00
00 08 F7 00 00 10
).join(' ')
caption = sprintf( " \tSheet1: %4d comments.", count)
result = unpack_record(@workbook.add_mso_drawing_group)
assert_equal(target, result, caption)
# Test the parameters pass to the worksheets
caption += ' (params)'
result_ids = []
target_ids = [
1024, 1, 1025, 2048
]
@workbook.sheets.each do |sheet|
sheet.object_ids.each {|id| result_ids.push(id) }
end
assert_equal(target_ids, result_ids, caption)
end
def test_2048_times
count = 2048
for i in 1 .. count
@worksheet1.write_comment(i -1, 0, 'aaa')
end
@workbook.calc_mso_sizes
target = %w(
EB 00 6A 00 0F 00 00 F0 62 00 00 00 00 00 06 F0
28 00 00 00 01 0C 00 00 04 00 00 00 01 08 00 00
01 00 00 00 01 00 00 00 00 04 00 00 01 00 00 00
00 04 00 00 01 00 00 00 01 00 00 00 33 00 0B F0
12 00 00 00 BF 00 08 00 08 00 81 01 09 00 00 08
C0 01 40 00 00 08 40 00 1E F1 10 00 00 00 0D 00
00 08 0C 00 00 08 17 00 00 08 F7 00 00 10
).join(' ')
caption = sprintf( " \tSheet1: %4d comments.", count)
result = unpack_record(@workbook.add_mso_drawing_group)
assert_equal(target, result, caption)
# Test the parameters pass to the worksheets
caption += ' (params)'
result_ids = []
target_ids = [
1024, 1, 2049, 3072
]
@workbook.sheets.each do |sheet|
sheet.object_ids.each {|id| result_ids.push(id) }
end
assert_equal(target_ids, result_ids, caption)
end
def test_2_sheets_1_and_1_times
count1 = 1
count2 = 1
for i in 1 .. count1
@worksheet1.write_comment(i -1, 0, 'aaa')
end
for i in 1 .. count2
@worksheet2.write_comment(i -1, 0, 'aaa')
end
@workbook.calc_mso_sizes
target = %w(
EB 00 62 00 0F 00 00 F0 5A 00 00 00 00 00 06 F0
20 00 00 00 02 08 00 00 03 00 00 00 04 00 00 00
02 00 00 00 01 00 00 00 02 00 00 00 02 00 00 00
02 00 00 00 33 00 0B F0 12 00 00 00 BF 00 08 00
08 00 81 01 09 00 00 08 C0 01 40 00 00 08 40 00
1E F1 10 00 00 00 0D 00 00 08 0C 00 00 08 17 00
00 08 F7 00 00 10
).join(' ')
caption = sprintf( " \tSheet1: %4d comments, Sheet2: %4d comments..",
count1, count2)
result = unpack_record(@workbook.add_mso_drawing_group)
assert_equal(target, result, caption)
# Test the parameters pass to the worksheets
caption += ' (params)'
result_ids = []
target_ids = [
1024, 1, 2, 1025,
2048, 2, 2, 2049
]
@workbook.sheets.each do |sheet|
sheet.object_ids.each {|id| result_ids.push(id) }
end
assert_equal(target_ids, result_ids, caption)
end
def test_2_sheets_2_and_2_times
count1 = 2
count2 = 2
for i in 1 .. count1
@worksheet1.write_comment(i -1, 0, 'aaa')
end
for i in 1 .. count2
@worksheet2.write_comment(i -1, 0, 'aaa')
end
@workbook.calc_mso_sizes
target = %w(
EB 00 62 00 0F 00 00 F0 5A 00 00 00 00 00 06 F0
20 00 00 00 03 08 00 00 03 00 00 00 06 00 00 00
02 00 00 00 01 00 00 00 03 00 00 00 02 00 00 00
03 00 00 00 33 00 0B F0 12 00 00 00 BF 00 08 00
08 00 81 01 09 00 00 08 C0 01 40 00 00 08 40 00
1E F1 10 00 00 00 0D 00 00 08 0C 00 00 08 17 00
00 08 F7 00 00 10
).join(' ')
caption = sprintf( " \tSheet1: %4d comments, Sheet2: %4d comments..",
count1, count2)
result = unpack_record(@workbook.add_mso_drawing_group)
assert_equal(target, result, caption)
# Test the parameters pass to the worksheets
caption += ' (params)'
result_ids = []
target_ids = [
1024, 1, 3, 1026,
2048, 2, 3, 2050
]
@workbook.sheets.each do |sheet|
sheet.object_ids.each {|id| result_ids.push(id) }
end
assert_equal(target_ids, result_ids, caption)
end
def test_2_sheets_1023_and_1_times
count1 = 1023
count2 = 1
for i in 1 .. count1
@worksheet1.write_comment(i -1, 0, 'aaa')
end
for i in 1 .. count2
@worksheet2.write_comment(i -1, 0, 'aaa')
end
@workbook.calc_mso_sizes
target = %w(
EB 00 62 00 0F 00 00 F0 5A 00 00 00 00 00 06 F0
20 00 00 00 02 08 00 00 03 00 00 00 02 04 00 00
02 00 00 00 01 00 00 00 00 04 00 00 02 00 00 00
02 00 00 00 33 00 0B F0 12 00 00 00 BF 00 08 00
08 00 81 01 09 00 00 08 C0 01 40 00 00 08 40 00
1E F1 10 00 00 00 0D 00 00 08 0C 00 00 08 17 00
00 08 F7 00 00 10
).join(' ')
caption = sprintf( " \tSheet1: %4d comments, Sheet2: %4d comments..",
count1, count2)
result = unpack_record(@workbook.add_mso_drawing_group)
assert_equal(target, result, caption)
# Test the parameters pass to the worksheets
caption += ' (params)'
result_ids = []
target_ids = [
1024, 1, 1024, 2047,
2048, 2, 2, 2049
]
@workbook.sheets.each do |sheet|
sheet.object_ids.each {|id| result_ids.push(id) }
end
assert_equal(target_ids, result_ids, caption)
end
def test_2_sheets_1023_and_1023_times
count1 = 1023
count2 = 1023
for i in 1 .. count1
@worksheet1.write_comment(i -1, 0, 'aaa')
end
for i in 1 .. count2
@worksheet2.write_comment(i -1, 0, 'aaa')
end
@workbook.calc_mso_sizes
target = %w(
EB 00 62 00 0F 00 00 F0 5A 00 00 00 00 00 06 F0
20 00 00 00 00 0C 00 00 03 00 00 00 00 08 00 00
02 00 00 00 01 00 00 00 00 04 00 00 02 00 00 00
00 04 00 00 33 00 0B F0 12 00 00 00 BF 00 08 00
08 00 81 01 09 00 00 08 C0 01 40 00 00 08 40 00
1E F1 10 00 00 00 0D 00 00 08 0C 00 00 08 17 00
00 08 F7 00 00 10
).join(' ')
caption = sprintf( " \tSheet1: %4d comments, Sheet2: %4d comments..",
count1, count2)
result = unpack_record(@workbook.add_mso_drawing_group)
assert_equal(target, result, caption)
# Test the parameters pass to the worksheets
caption += ' (params)'
result_ids = []
target_ids = [
1024, 1, 1024, 2047,
2048, 2, 1024, 3071
]
@workbook.sheets.each do |sheet|
sheet.object_ids.each {|id| result_ids.push(id) }
end
assert_equal(target_ids, result_ids, caption)
end
def test_2_sheets_1024_and_1024_times
count1 = 1024
count2 = 1024
for i in 1 .. count1
@worksheet1.write_comment(i -1, 0, 'aaa')
end
for i in 1 .. count2
@worksheet2.write_comment(i -1, 0, 'aaa')
end
@workbook.calc_mso_sizes
target = %w(
EB 00 72 00 0F 00 00 F0 6A 00 00 00 00 00 06 F0
30 00 00 00 01 10 00 00 05 00 00 00 02 08 00 00
02 00 00 00 01 00 00 00 00 04 00 00 01 00 00 00
01 00 00 00 02 00 00 00 00 04 00 00 02 00 00 00
01 00 00 00 33 00 0B F0 12 00 00 00 BF 00 08 00
08 00 81 01 09 00 00 08 C0 01 40 00 00 08 40 00
1E F1 10 00 00 00 0D 00 00 08 0C 00 00 08 17 00
00 08 F7 00 00 10
).join(' ')
caption = sprintf( " \tSheet1: %4d comments, Sheet2: %4d comments..",
count1, count2)
result = unpack_record(@workbook.add_mso_drawing_group)
assert_equal(target, result, caption)
# Test the parameters pass to the worksheets
caption += ' (params)'
result_ids = []
target_ids = [
1024, 1, 1025, 2048,
3072, 2, 1025, 4096
]
@workbook.sheets.each do |sheet|
sheet.object_ids.each {|id| result_ids.push(id) }
end
assert_equal(target_ids, result_ids, caption)
end
def test_2_sheets_1024_and_1_times
count1 = 1024
count2 = 1
for i in 1 .. count1
@worksheet1.write_comment(i -1, 0, 'aaa')
end
for i in 1 .. count2
@worksheet2.write_comment(i -1, 0, 'aaa')
end
@workbook.calc_mso_sizes
target = %w(
EB 00 6A 00 0F 00 00 F0 62 00 00 00 00 00 06 F0
28 00 00 00 02 0C 00 00 04 00 00 00 03 04 00 00
02 00 00 00 01 00 00 00 00 04 00 00 01 00 00 00
01 00 00 00 02 00 00 00 02 00 00 00 33 00 0B F0
12 00 00 00 BF 00 08 00 08 00 81 01 09 00 00 08
C0 01 40 00 00 08 40 00 1E F1 10 00 00 00 0D 00
00 08 0C 00 00 08 17 00 00 08 F7 00 00 10
).join(' ')
caption = sprintf( " \tSheet1: %4d comments, Sheet2: %4d comments..",
count1, count2)
result = unpack_record(@workbook.add_mso_drawing_group)
assert_equal(target, result, caption)
# Test the parameters pass to the worksheets
caption += ' (params)'
result_ids = []
target_ids = [
1024, 1, 1025, 2048,
3072, 2, 2, 3073
]
@workbook.sheets.each do |sheet|
sheet.object_ids.each {|id| result_ids.push(id) }
end
assert_equal(target_ids, result_ids, caption)
end
def test_3_sheets_1023_and_1_and_1023_times
count1 = 1023
count2 = 1
count3 = 1023
for i in 1 .. count1
@worksheet1.write_comment(i -1, 0, 'aaa')
end
for i in 1 .. count2
@worksheet2.write_comment(i -1, 0, 'aaa')
end
for i in 1 .. count3
@worksheet3.write_comment(i -1, 0, 'aaa')
end
@workbook.calc_mso_sizes
target = %w(
EB 00 6A 00 0F 00 00 F0 62 00 00 00 00 00 06 F0
28 00 00 00 00 10 00 00 04 00 00 00 02 08 00 00
03 00 00 00 01 00 00 00 00 04 00 00 02 00 00 00
02 00 00 00 03 00 00 00 00 04 00 00 33 00 0B F0
12 00 00 00 BF 00 08 00 08 00 81 01 09 00 00 08
C0 01 40 00 00 08 40 00 1E F1 10 00 00 00 0D 00
00 08 0C 00 00 08 17 00 00 08 F7 00 00 10
).join(' ')
caption = sprintf( " \tSheet1: %4d comments, Sheet2: %4d comments,"+
"Sheet3: %4d comments.", count1, count2, count3)
result = unpack_record(@workbook.add_mso_drawing_group)
assert_equal(target, result, caption)
# Test the parameters pass to the worksheets
caption += ' (params)'
result_ids = []
target_ids = [
1024, 1, 1024, 2047,
2048, 2, 2, 2049,
3072, 3, 1024, 4095
]
@workbook.sheets.each do |sheet|
sheet.object_ids.each {|id| result_ids.push(id) }
end
assert_equal(target_ids, result_ids, caption)
end
def test_3_sheets_1023_and_1023_and_1_times
count1 = 1023
count2 = 1023
count3 = 1
for i in 1 .. count1
@worksheet1.write_comment(i -1, 0, 'aaa')
end
for i in 1 .. count2
@worksheet2.write_comment(i -1, 0, 'aaa')
end
for i in 1 .. count3
@worksheet3.write_comment(i -1, 0, 'aaa')
end
@workbook.calc_mso_sizes
target = %w(
EB 00 6A 00 0F 00 00 F0 62 00 00 00 00 00 06 F0
28 00 00 00 02 0C 00 00 04 00 00 00 02 08 00 00
03 00 00 00 01 00 00 00 00 04 00 00 02 00 00 00
00 04 00 00 03 00 00 00 02 00 00 00 33 00 0B F0
12 00 00 00 BF 00 08 00 08 00 81 01 09 00 00 08
C0 01 40 00 00 08 40 00 1E F1 10 00 00 00 0D 00
00 08 0C 00 00 08 17 00 00 08 F7 00 00 10
).join(' ')
caption = sprintf( " \tSheet1: %4d comments, Sheet2: %4d comments,"+
"Sheet3: %4d comments.", count1, count2, count3)
result = unpack_record(@workbook.add_mso_drawing_group)
assert_equal(target, result, caption)
# Test the parameters pass to the worksheets
caption += ' (params)'
result_ids = []
target_ids = [
1024, 1, 1024, 2047,
2048, 2, 1024, 3071,
3072, 3, 2, 3073
]
@workbook.sheets.each do |sheet|
sheet.object_ids.each {|id| result_ids.push(id) }
end
assert_equal(target_ids, result_ids, caption)
end
def test_3_sheets_1024_and_1_and_1024_times
count1 = 1024
count2 = 1
count3 = 1024
for i in 1 .. count1
@worksheet1.write_comment(i -1, 0, 'aaa')
end
for i in 1 .. count2
@worksheet2.write_comment(i -1, 0, 'aaa')
end
for i in 1 .. count3
@worksheet3.write_comment(i -1, 0, 'aaa')
end
@workbook.calc_mso_sizes
target = %w(
EB 00 7A 00 0F 00 00 F0 72 00 00 00 00 00 06 F0
38 00 00 00 01 14 00 00 06 00 00 00 04 08 00 00
03 00 00 00 01 00 00 00 00 04 00 00 01 00 00 00
01 00 00 00 02 00 00 00 02 00 00 00 03 00 00 00
00 04 00 00 03 00 00 00 01 00 00 00 33 00 0B F0
12 00 00 00 BF 00 08 00 08 00 81 01 09 00 00 08
C0 01 40 00 00 08 40 00 1E F1 10 00 00 00 0D 00
00 08 0C 00 00 08 17 00 00 08 F7 00 00 10
).join(' ')
caption = sprintf( " \tSheet1: %4d comments, Sheet2: %4d comments,"+
"Sheet3: %4d comments.", count1, count2, count3)
result = unpack_record(@workbook.add_mso_drawing_group)
assert_equal(target, result, caption)
# Test the parameters pass to the worksheets
caption += ' (params)'
result_ids = []
target_ids = [
1024, 1, 1025, 2048,
3072, 2, 2, 3073,
4096, 3, 1025, 5120
]
@workbook.sheets.each do |sheet|
sheet.object_ids.each {|id| result_ids.push(id) }
end
assert_equal(target_ids, result_ids, caption)
end
def test_3_sheets_1024_and_1024_and_1_times
count1 = 1024
count2 = 1024
count3 = 1
for i in 1 .. count1
@worksheet1.write_comment(i -1, 0, 'aaa')
end
for i in 1 .. count2
@worksheet2.write_comment(i -1, 0, 'aaa')
end
for i in 1 .. count3
@worksheet3.write_comment(i -1, 0, 'aaa')
end
@workbook.calc_mso_sizes
target = %w(
EB 00 7A 00 0F 00 00 F0 72 00 00 00 00 00 06 F0
38 00 00 00 02 14 00 00 06 00 00 00 04 08 00 00
03 00 00 00 01 00 00 00 00 04 00 00 01 00 00 00
01 00 00 00 02 00 00 00 00 04 00 00 02 00 00 00
01 00 00 00 03 00 00 00 02 00 00 00 33 00 0B F0
12 00 00 00 BF 00 08 00 08 00 81 01 09 00 00 08
C0 01 40 00 00 08 40 00 1E F1 10 00 00 00 0D 00
00 08 0C 00 00 08 17 00 00 08 F7 00 00 10
).join(' ')
caption = sprintf( " \tSheet1: %4d comments, Sheet2: %4d comments,"+
"Sheet3: %4d comments.", count1, count2, count3)
result = unpack_record(@workbook.add_mso_drawing_group)
assert_equal(target, result, caption)
# Test the parameters pass to the worksheets
caption += ' (params)'
result_ids = []
target_ids = [
1024, 1, 1025, 2048,
3072, 2, 1025, 4096,
5120, 3, 2, 5121
]
@workbook.sheets.each do |sheet|
sheet.object_ids.each {|id| result_ids.push(id) }
end
assert_equal(target_ids, result_ids, caption)
end
def test_3_sheets_1024_and_1024_and_1_times_duplicate
count1 = 1024
count2 = 1024
count3 = 1
for i in 1 .. count1
@worksheet1.write_comment(i -1, 0, 'aaa')
end
for i in 1 .. count2
@worksheet2.write_comment(i -1, 0, 'aaa')
end
for i in 1 .. count3
@worksheet3.write_comment(i -1, 0, 'aaa')
end
# dupulicate -- these are ignored. result is same as prev.--
for i in 1 .. count1
@worksheet1.write_comment(i -1, 0, 'aaa')
end
for i in 1 .. count2
@worksheet2.write_comment(i -1, 0, 'aaa')
end
for i in 1 .. count3
@worksheet3.write_comment(i -1, 0, 'aaa')
end
@workbook.calc_mso_sizes
target = %w(
EB 00 7A 00 0F 00 00 F0 72 00 00 00 00 00 06 F0
38 00 00 00 02 14 00 00 06 00 00 00 04 08 00 00
03 00 00 00 01 00 00 00 00 04 00 00 01 00 00 00
01 00 00 00 02 00 00 00 00 04 00 00 02 00 00 00
01 00 00 00 03 00 00 00 02 00 00 00 33 00 0B F0
12 00 00 00 BF 00 08 00 08 00 81 01 09 00 00 08
C0 01 40 00 00 08 40 00 1E F1 10 00 00 00 0D 00
00 08 0C 00 00 08 17 00 00 08 F7 00 00 10
).join(' ')
caption = sprintf( " \tSheet1: %4d comments, Sheet2: %4d comments,"+
"Sheet3: %4d comments.", count1, count2, count3)
result = unpack_record(@workbook.add_mso_drawing_group)
assert_equal(target, result, caption)
# Test the parameters pass to the worksheets
caption += ' (params)'
result_ids = []
target_ids = [
1024, 1, 1025, 2048,
3072, 2, 1025, 4096,
5120, 3, 2, 5121
]
@workbook.sheets.each do |sheet|
sheet.object_ids.each {|id| result_ids.push(id) }
end
assert_equal(target_ids, result_ids, caption)
end
=end
end
|
Radanisk/writeexcel
|
test/test_32_validation_dv_formula.rb
|
# -*- coding: utf-8 -*-
##########################################################################
# test_32_validation_dv_formula.rb
#
# Tests for the Excel DVAL structure used in data validation.
#
# reverse('©'), September 2005, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
#########################################################################
require 'helper'
require 'stringio'
class TC_validation_dv_formula < Test::Unit::TestCase
def setup
@workbook = WriteExcel.new(StringIO.new)
@worksheet = @workbook.add_worksheet
@worksheet2 = @workbook.add_worksheet
@data_validation = Writeexcel::Worksheet::DataValidation.new(@worksheet.__send__("parser"), {})
end
def teardown
if @workbook.instance_variable_get(:@filehandle)
@workbook.instance_variable_get(:@filehandle).close(true)
end
if @worksheet.instance_variable_get(:@filehandle)
@worksheet.instance_variable_get(:@filehandle).close(true)
end
end
def test_integer_values
formula = '10'
caption = " \tData validation: _pack_dv_formula('#{formula}')"
bytes = %w(
03 00 00 E0 1E 0A 00
)
# Zero out Excel's random unused word to allow comparison.
bytes[2] = '00'
bytes[3] = '00'
target = bytes.join(" ")
result = unpack_record(@data_validation.__send__("pack_dv_formula", formula))
assert_equal(target, result, caption)
end
def test_decimal_values
formula = '1.2345'
caption = " \tData validation: _pack_dv_formula('#{formula}')"
bytes = %w(
09 00 E0 3F 1F 8D 97 6E 12 83 C0 F3 3F
)
# Zero out Excel's random unused word to allow comparison.
bytes[2] = '00'
bytes[3] = '00'
target = bytes.join(" ")
result = unpack_record(@data_validation.__send__("pack_dv_formula", formula))
assert_equal(target, result, caption)
end
def test_date_values
formula = @worksheet.__send__("convert_date_time", '2008-07-24T')
caption = " \tData validation: _pack_dv_formula('2008-07-24T')"
bytes = %w(
03 00 E0 3F 1E E5 9A
)
# Zero out Excel's random unused word to allow comparison.
bytes[2] = '00'
bytes[3] = '00'
target = bytes.join(" ")
result = unpack_record(@data_validation.__send__("pack_dv_formula", formula))
assert_equal(target, result, caption)
end
def test_time_values
formula = @worksheet.__send__("convert_date_time", 'T12:00')
caption = " \tData validation: _pack_dv_formula('T12:00')"
bytes = %w(
09 00 E0 3F 1F 00 00 00 00 00 00 E0 3F
)
# Zero out Excel's random unused word to allow comparison.
bytes[2] = '00'
bytes[3] = '00'
target = bytes.join(" ")
result = unpack_record(@data_validation.__send__("pack_dv_formula", formula))
assert_equal(target, result, caption)
end
def test_cell_reference_value_C9
formula = '=C9'
caption = " \tData validation: _pack_dv_formula('#{formula}')"
bytes = %w(
05 00 E0 3F 44 08 00 02 C0
)
# Zero out Excel's random unused word to allow comparison.
bytes[2] = '00'
bytes[3] = '00'
target = bytes.join(" ")
result = unpack_record(@data_validation.__send__("pack_dv_formula", formula))
assert_equal(target, result, caption)
end
def test_cell_reference_value_E3_E6
formula = '=E3:E6'
caption = " \tData validation: _pack_dv_formula('#{formula}')"
bytes = %w(
09 00 0C 00 25 02 00 05 00 04 C0 04 C0
)
# Zero out Excel's random unused word to allow comparison.
bytes[2] = '00'
bytes[3] = '00'
target = bytes.join(" ")
result = unpack_record(@data_validation.__send__("pack_dv_formula", formula))
assert_equal(target, result, caption)
end
def test_cell_reference_value_E3_E6_absolute
formula = '=$E$3:$E$6'
caption = " \tData validation: _pack_dv_formula('#{formula}')"
bytes = %w(
09 00 0C 00 25 02 00 05 00 04 00 04 00
)
# Zero out Excel's random unused word to allow comparison.
bytes[2] = '00'
bytes[3] = '00'
target = bytes.join(" ")
result = unpack_record(@data_validation.__send__("pack_dv_formula", formula))
assert_equal(target, result, caption)
end
def test_list_values
formula = ['a', 'bb', 'ccc']
caption = " \tData validation: _pack_dv_formula(['a', 'bb', 'ccc'])"
bytes = %w(
0B 00 0C 00 17 08 00 61 00 62 62 00 63 63 63
)
# Zero out Excel's random unused word to allow comparison.
bytes[2] = '00'
bytes[3] = '00'
target = bytes.join(" ")
result = unpack_record(@data_validation.__send__("pack_dv_formula", formula))
assert_equal(target, result, caption)
end
def test_empty_string
formula = ''
caption = " \tData validation: _pack_dv_formula('')"
bytes = %w(
00 00 00
)
# Zero out Excel's random unused word to allow comparison.
bytes[2] = '00'
bytes[3] = '00'
target = bytes.join(" ")
result = unpack_record(@data_validation.__send__("pack_dv_formula", formula))
assert_equal(target, result, caption)
end
def test_undefined_value
formula = nil
caption = " \tData validation: _pack_dv_formula(nil)"
bytes = %w(
00 00 00
)
# Zero out Excel's random unused word to allow comparison.
bytes[2] = '00'
bytes[3] = '00'
target = bytes.join(" ")
result = unpack_record(@data_validation.__send__("pack_dv_formula", formula))
assert_equal(target, result, caption)
end
def test_pack_dv_formula_should_not_change_formula_string
formula = '=SUM(A1:D1)'
@data_validation.__send__("pack_dv_formula", formula)
assert_equal('=SUM(A1:D1)', formula)
end
end
|
Radanisk/writeexcel
|
test/test_04_dimensions.rb
|
<filename>test/test_04_dimensions.rb
# -*- coding: utf-8 -*-
###############################################################################
#
# A test for WriteExcel.
#
# Check that the Excel DIMENSIONS record is written correctly.
#
# reverse('©'), October 2007, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
############################################################################
require 'helper'
require 'stringio'
class TC_dimensions < Test::Unit::TestCase
def setup
@workbook = WriteExcel.new(StringIO.new)
@worksheet = @workbook.add_worksheet
@format = @workbook.add_format
@dims = ['row_min', 'row_max', 'col_min', 'col_max']
@smiley = [0x263a].pack('n')
end
def teardown
if @workbook.instance_variable_get(:@filehandle)
@workbook.instance_variable_get(:@filehandle).close(true)
end
if @worksheet.instance_variable_get(:@filehandle)
@worksheet.instance_variable_get(:@filehandle).close(true)
end
end
def test_no_worksheet_cell_data
data = @worksheet.__send__("store_dimensions")
vals = data.unpack('x4 VVvv')
alist = @dims.zip(vals)
results = Hash[*alist.flatten]
alist = @dims.zip([0, 0, 0, 0])
expected = Hash[*alist.flatten]
assert_equal(expected, results)
end
def test_data_in_cell_0_0
@worksheet.write(0, 0, 'Test')
data = @worksheet.__send__("store_dimensions")
vals = data.unpack('x4 VVvv')
alist = @dims.zip(vals)
results = Hash[*alist.flatten]
alist = @dims.zip([0, 1, 0, 1])
expected = Hash[*alist.flatten]
assert_equal(expected, results)
end
def test_data_in_cell_0_255
@worksheet.write(0, 255, 'Test')
data = @worksheet.__send__("store_dimensions")
vals = data.unpack('x4 VVvv')
alist = @dims.zip(vals)
results = Hash[*alist.flatten]
alist = @dims.zip([0, 1, 255, 256])
expected = Hash[*alist.flatten]
assert_equal(expected, results)
end
def test_data_in_cell_65535_0
@worksheet.write(65535, 0, 'Test')
data = @worksheet.__send__("store_dimensions")
vals = data.unpack('x4 VVvv')
alist = @dims.zip(vals)
results = Hash[*alist.flatten]
alist = @dims.zip([65535, 65536, 0, 1])
expected = Hash[*alist.flatten]
assert_equal(expected, results)
end
def test_data_in_cell_65535_255
@worksheet.write(65535, 255, 'Test')
data = @worksheet.__send__("store_dimensions")
vals = data.unpack('x4 VVvv')
alist = @dims.zip(vals)
results = Hash[*alist.flatten]
alist = @dims.zip([65535, 65536, 255, 256])
expected = Hash[*alist.flatten]
assert_equal(expected, results)
end
def test_set_row_for_row_4
@worksheet.set_row(4, 20)
data = @worksheet.__send__("store_dimensions")
vals = data.unpack('x4 VVvv')
alist = @dims.zip(vals)
results = Hash[*alist.flatten]
alist = @dims.zip([4, 5, 0, 0])
expected = Hash[*alist.flatten]
assert_equal(expected, results)
end
def test_set_row_for_row_4_to_6
@worksheet.set_row(4, 20)
@worksheet.set_row(5, 20)
@worksheet.set_row(6, 20)
data = @worksheet.__send__("store_dimensions")
vals = data.unpack('x4 VVvv')
alist = @dims.zip(vals)
results = Hash[*alist.flatten]
alist = @dims.zip([4, 7, 0, 0])
expected = Hash[*alist.flatten]
assert_equal(expected, results)
end
def test_set_column_for_row_4
@worksheet.set_column(4, 4, 20)
data = @worksheet.__send__("store_dimensions")
vals = data.unpack('x4 VVvv')
alist = @dims.zip(vals)
results = Hash[*alist.flatten]
alist = @dims.zip([0, 0, 0, 0])
expected = Hash[*alist.flatten]
assert_equal(expected, results)
end
def test_data_in_cell_0_0_and_set_row_for_row_4
@worksheet.write(0, 0, 'Test')
@worksheet.set_row(4, 20)
data = @worksheet.__send__("store_dimensions")
vals = data.unpack('x4 VVvv')
alist = @dims.zip(vals)
results = Hash[*alist.flatten]
alist = @dims.zip([0, 5, 0, 1])
expected = Hash[*alist.flatten]
assert_equal(expected, results)
end
def test_data_in_cell_0_0_and_set_row_for_row_4_reverse_order
@worksheet.set_row(4, 20)
@worksheet.write(0, 0, 'Test')
data = @worksheet.__send__("store_dimensions")
vals = data.unpack('x4 VVvv')
alist = @dims.zip(vals)
results = Hash[*alist.flatten]
alist = @dims.zip([0, 5, 0, 1])
expected = Hash[*alist.flatten]
assert_equal(expected, results)
end
def test_data_in_cell_5_3_and_set_row_for_row_4
@worksheet.write(5, 3, 'Test')
@worksheet.set_row(4, 20)
data = @worksheet.__send__("store_dimensions")
vals = data.unpack('x4 VVvv')
alist = @dims.zip(vals)
results = Hash[*alist.flatten]
alist = @dims.zip([4, 6, 3, 4])
expected = Hash[*alist.flatten]
assert_equal(expected, results)
end
def test_comment_in_cell_5_3
@worksheet.write_comment(5, 3, 'Test')
data = @worksheet.__send__("store_dimensions")
vals = data.unpack('x4 VVvv')
alist = @dims.zip(vals)
results = Hash[*alist.flatten]
alist = @dims.zip([5, 6, 3, 4])
expected = Hash[*alist.flatten]
assert_equal(expected, results)
end
def test_nil_value_for_row
error = @worksheet.write_string(nil, 1, 'Test')
data = @worksheet.__send__("store_dimensions")
vals = data.unpack('x4 VVvv')
alist = @dims.zip(vals)
results = Hash[*alist.flatten]
alist = @dims.zip([0, 0, 0, 0])
expected = Hash[*alist.flatten]
assert_equal(expected, results)
assert_equal(-2, error)
end
def test_data_in_cell_5_3_and_10_1
@worksheet.write( 5, 3, 'Test')
@worksheet.write(10, 1, 'Test')
data = @worksheet.__send__("store_dimensions")
vals = data.unpack('x4 VVvv')
alist = @dims.zip(vals)
results = Hash[*alist.flatten]
alist = @dims.zip([5, 11, 1, 4])
expected = Hash[*alist.flatten]
assert_equal(expected, results)
end
def test_data_in_cell_5_3_and_10_5
@worksheet.write( 5, 3, 'Test')
@worksheet.write(10, 5, 'Test')
data = @worksheet.__send__("store_dimensions")
vals = data.unpack('x4 VVvv')
alist = @dims.zip(vals)
results = Hash[*alist.flatten]
alist = @dims.zip([5, 11, 3, 6])
expected = Hash[*alist.flatten]
assert_equal(expected, results)
end
def test_write_string
@worksheet.write_string(5, 3, 'Test')
data = @worksheet.__send__("store_dimensions")
vals = data.unpack('x4 VVvv')
alist = @dims.zip(vals)
results = Hash[*alist.flatten]
alist = @dims.zip([5, 6, 3, 4])
expected = Hash[*alist.flatten]
assert_equal(expected, results)
end
def test_write_number
@worksheet.write_number(5, 3, 5)
data = @worksheet.__send__("store_dimensions")
vals = data.unpack('x4 VVvv')
alist = @dims.zip(vals)
results = Hash[*alist.flatten]
alist = @dims.zip([5, 6, 3, 4])
expected = Hash[*alist.flatten]
assert_equal(expected, results)
end
def test_write_url
@worksheet.write_url(5, 3, 'http://www.ruby.com')
data = @worksheet.__send__("store_dimensions")
vals = data.unpack('x4 VVvv')
alist = @dims.zip(vals)
results = Hash[*alist.flatten]
alist = @dims.zip([5, 6, 3, 4])
expected = Hash[*alist.flatten]
assert_equal(expected, results)
end
def test_write_formula
@worksheet.write_formula(5, 3, ' 1 + 2')
data = @worksheet.__send__("store_dimensions")
vals = data.unpack('x4 VVvv')
alist = @dims.zip(vals)
results = Hash[*alist.flatten]
alist = @dims.zip([5, 6, 3, 4])
expected = Hash[*alist.flatten]
assert_equal(expected, results)
end
def test_write_blank
@worksheet.write_string(5, 3, @format)
data = @worksheet.__send__("store_dimensions")
vals = data.unpack('x4 VVvv')
alist = @dims.zip(vals)
results = Hash[*alist.flatten]
alist = @dims.zip([5, 6, 3, 4])
expected = Hash[*alist.flatten]
assert_equal(expected, results)
end
def test_write_blank_no_format
@worksheet.write_string(5, 3)
data = @worksheet.__send__("store_dimensions")
vals = data.unpack('x4 VVvv')
alist = @dims.zip(vals)
results = Hash[*alist.flatten]
alist = @dims.zip([0, 0, 0, 0])
expected = Hash[*alist.flatten]
assert_equal(expected, results)
end
def test_write_utf16be_string
@worksheet.write_utf16be_string(5, 3, @smiley)
data = @worksheet.__send__("store_dimensions")
vals = data.unpack('x4 VVvv')
alist = @dims.zip(vals)
results = Hash[*alist.flatten]
alist = @dims.zip([5, 6, 3, 4])
expected = Hash[*alist.flatten]
assert_equal(expected, results)
end
def test_write_utf16le_string
@worksheet.write_utf16le_string(5, 3, @smiley)
data = @worksheet.__send__("store_dimensions")
vals = data.unpack('x4 VVvv')
alist = @dims.zip(vals)
results = Hash[*alist.flatten]
alist = @dims.zip([5, 6, 3, 4])
expected = Hash[*alist.flatten]
assert_equal(expected, results)
end
def test_repeat_formula
formula = @worksheet.__send__("store_formula", '=A1 * 3 + 50')
@worksheet.repeat_formula(5, 3, formula, @format, 'A1', 'A2')
data = @worksheet.__send__("store_dimensions")
vals = data.unpack('x4 VVvv')
alist = @dims.zip(vals)
results = Hash[*alist.flatten]
alist = @dims.zip([5, 6, 3, 4])
expected = Hash[*alist.flatten]
assert_equal(expected, results)
end
def test_store_formula_should_not_change_formula_string
formula = '=SUM(A1:D1)'
@worksheet.store_formula(formula)
assert_equal('=SUM(A1:D1)', formula)
end
def test_merge_range
formula = @worksheet.__send__("store_formula", '=A1 * 3 + 50')
@worksheet.merge_range('C6:E8', 'Test', @format)
data = @worksheet.__send__("store_dimensions")
vals = data.unpack('x4 VVvv')
alist = @dims.zip(vals)
results = Hash[*alist.flatten]
alist = @dims.zip([5, 8, 2, 5])
expected = Hash[*alist.flatten]
assert_equal(expected, results)
end
end
|
Radanisk/writeexcel
|
examples/panes.rb
|
<reponame>Radanisk/writeexcel
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
#######################################################################
#
# Example of using the WriteExcel module to create worksheet panes.
#
# reverse('©'), May 2001, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
workbook = WriteExcel.new("panes.xls")
worksheet1 = workbook.add_worksheet('Panes 1')
worksheet2 = workbook.add_worksheet('Panes 2')
worksheet3 = workbook.add_worksheet('Panes 3')
worksheet4 = workbook.add_worksheet('Panes 4')
# Freeze panes
worksheet1.freeze_panes(1, 0) # 1 row
worksheet2.freeze_panes(0, 1) # 1 column
worksheet3.freeze_panes(1, 1) # 1 row and column
# Split panes.
# The divisions must be specified in terms of row and column dimensions.
# The default row height is 12.75 and the default column width is 8.43
#
worksheet4.split_panes(12.75, 8.43, 1, 1) # 1 row and column
#######################################################################
#
# Set up some formatting and text to highlight the panes
#
header = workbook.add_format
header.set_color('white')
header.set_align('center')
header.set_align('vcenter')
header.set_pattern
header.set_fg_color('green')
center = workbook.add_format
center.set_align('center')
#######################################################################
#
# Sheet 1
#
worksheet1.set_column('A:I', 16)
worksheet1.set_row(0, 20)
worksheet1.set_selection('C3')
(0..8).each { |i| worksheet1.write(0, i, 'Scroll down', header) }
(1..100).each do |i|
(0..8).each { |j| worksheet1.write(i, j, i + 1, center) }
end
#######################################################################
#
# Sheet 2
#
worksheet2.set_column('A:A', 16)
worksheet2.set_selection('C3')
(0..49).each do |i|
worksheet2.set_row(i, 15)
worksheet2.write(i, 0, 'Scroll right', header)
end
(0..49).each do |i|
(1..25).each { |j| worksheet2.write(i, j, j, center) }
end
#######################################################################
#
# Sheet 3
#
worksheet3.set_column('A:Z', 16)
worksheet3.set_selection('C3')
(1..25).each { |i| worksheet3.write(0, i, 'Scroll down', header) }
(1..49).each { |i| worksheet3.write(i, 0, 'Scroll right', header) }
(1..49).each do |i|
(1..25).each { |j| worksheet3.write(i, j, j, center) }
end
#######################################################################
#
# Sheet 4
#
worksheet4.set_selection('C3')
(1..25).each { |i| worksheet4.write(0, i, 'Scroll', center) }
(1..49).each { |i| worksheet4.write(i, 0, 'Scroll', center) }
(1..49).each do |i|
(1..25).each { |j| worksheet4.write(i, j, j, center) }
end
workbook.close
|
Radanisk/writeexcel
|
test/test_05_rows.rb
|
<reponame>Radanisk/writeexcel
# -*- coding: utf-8 -*-
###############################################################################
#
# A test for WriteExcel.
#
# Check that max/min columns of the Excel ROW record are written correctly.
#
# reverse('©'), October 2007, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
############################################################################
require 'helper'
require 'stringio'
class TC_rows < Test::Unit::TestCase
def setup
end
def teardown
if @workbook.instance_variable_get(:@filehandle)
@workbook.instance_variable_get(:@filehandle).close(true)
end
if @worksheet.instance_variable_get(:@filehandle)
@worksheet.instance_variable_get(:@filehandle).close(true)
end
end
def test_1
file = StringIO.new
workbook = WriteExcel.new(file)
workbook.compatibility_mode(1)
@tests = []
# for test case 1
row = 1
col1 = 0
col2 = 0
worksheet = workbook.add_worksheet
worksheet.set_row(row, 15)
@tests.push(
[
" \tset_row(): row = #{row}, col1 = #{col1}, col2 = #{col2}",
{
:col_min => 0,
:col_max => 0,
}
]
)
# for test case 2
row = 2
col1 = 0
col2 = 0
worksheet = workbook.add_worksheet
worksheet.write(row, col1, 'Test')
worksheet.write(row, col2, 'Test')
@tests.push(
[
" \tset_row(): row = #{row}, col1 = #{col1}, col2 = #{col2}",
{
:col_min => 0,
:col_max => 1,
}
]
)
# for test case 3
row = 3
col1 = 0
col2 = 1
worksheet = workbook.add_worksheet
worksheet.write(row, col1, 'Test')
worksheet.write(row, col2, 'Test')
@tests.push(
[
" \twrite(): row = #{row}, col1 = #{col1}, col2 = #{col2}",
{
:col_min => 0,
:col_max => 2,
}
]
)
# for test case 4
row = 4
col1 = 1
col2 = 1
worksheet = workbook.add_worksheet
worksheet.write(row, col1, 'Test')
worksheet.write(row, col2, 'Test')
@tests.push(
[
" \twrite(): row = #{row}, col1 = #{col1}, col2 = #{col2}",
{
:col_min => 1,
:col_max => 2,
}
]
)
# for test case 5
row = 5
col1 = 1
col2 = 255
worksheet = workbook.add_worksheet
worksheet.write(row, col1, 'Test')
worksheet.write(row, col2, 'Test')
@tests.push(
[
" \twrite(): row = #{row}, col1 = #{col1}, col2 = #{col2}",
{
:col_min => 1,
:col_max => 256,
}
]
)
# for test case 6
row = 6
col1 = 255
col2 = 255
worksheet = workbook.add_worksheet
worksheet.write(row, col1, 'Test')
worksheet.write(row, col2, 'Test')
@tests.push(
[
" \twrite(): row = #{row}, col1 = #{col1}, col2 = #{col2}",
{
:col_min => 255,
:col_max => 256,
}
]
)
# for test case 7
row = 7
col1 = 2
col2 = 9
worksheet = workbook.add_worksheet
worksheet.set_row(row, 15)
worksheet.write(row, col1, 'Test')
worksheet.write(row, col2, 'Test')
@tests.push(
[
" \tset_row + write(): row = #{row}, col1 = #{col1}, col2 = #{col2}",
{
:col_min => 2,
:col_max => 10,
}
]
)
workbook.biff_only = 1
workbook.close
# Read in the row records
rows = []
xlsfile = StringIO.new(file.string)
while header = xlsfile.read(4)
record, length = header.unpack('vv')
data = xlsfile.read(length)
#read the row records only
next unless record == 0x0208
col_min, col_max = data.unpack('x2 vv')
rows.push(
{
:col_min => col_min,
:col_max => col_max
}
)
end
xlsfile.close
(0 .. @tests.size - 1).each do |i|
assert_equal(@tests[i][1], rows[i], @tests[i][0])
end
end
end
|
Radanisk/writeexcel
|
test/test_31_validation_dv_strings.rb
|
<filename>test/test_31_validation_dv_strings.rb<gh_stars>10-100
# -*- coding: utf-8 -*-
##########################################################################
# test_31_validation_dv_strings.rb
#
# Tests for the packed caption/message strings used in the Excel DV structure
# as part of data validation.
#
# reverse('©'), September 2005, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
#########################################################################
require 'helper'
require 'stringio'
class TC_validation_dv_strings < Test::Unit::TestCase
def setup
workbook = WriteExcel.new(StringIO.new)
worksheet = workbook.add_worksheet
@data_validation = Writeexcel::Worksheet::DataValidation.new(worksheet.__send__("parser"), {})
end
def teardown
if @workbook.instance_variable_get(:@filehandle)
@workbook.instance_variable_get(:@filehandle).close(true)
end
if @worksheet.instance_variable_get(:@filehandle)
@worksheet.instance_variable_get(:@filehandle).close(true)
end
end
def test_empty_string
string = ''
max_length = 32
caption = " \tData validation: _pack_dv_string('', #{max_length})"
target = %w(
01 00 00 00
).join(' ')
result = unpack_record(@data_validation.__send__("pack_dv_string", string, max_length))
assert_equal(target, result, caption)
end
def test_nil
string = nil
max_length = 32
caption = " \tData validation: _pack_dv_string('', #{max_length})"
target = %w(
01 00 00 00
).join(' ')
result = unpack_record(@data_validation.__send__("pack_dv_string", string, max_length))
assert_equal(target, result, caption)
end
def test_single_space
string = ' '
max_length = 32
caption = " \tData validation: _pack_dv_string('', #{max_length})"
target = %w(
01 00 00 20
).join(' ')
result = unpack_record(@data_validation.__send__("pack_dv_string", string, max_length))
assert_equal(target, result, caption)
end
def test_single_character
string = 'A'
max_length = 32
caption = " \tData validation: _pack_dv_string('', #{max_length})"
target = %w(
01 00 00 41
).join(' ')
result = unpack_record(@data_validation.__send__("pack_dv_string", string, max_length))
assert_equal(target, result, caption)
end
def test_string_longer_than_32_characters_for_dialog_captions
string = 'This string is longer than 32 characters'
max_length = 32
caption = " \tData validation: _pack_dv_string('', #{max_length})"
target = %w(
20 00 00 54 68 69 73 20
73 74 72 69 6E 67 20 69 73 20 6C 6F 6E 67 65 72
20 74 68 61 6E 20 33 32 20 63 68
).join(' ')
result = unpack_record(@data_validation.__send__("pack_dv_string", string, max_length))
assert_equal(target, result, caption)
end
def test_string_longer_than_32_characters_for_dialog_messages
string = 'ABCD' * 64
max_length = 255
caption = " \tData validation: _pack_dv_string('', #{max_length})"
target = %w(
FF 00 00 41 42 43 44 41 42 43 44 41 42 43 44 41
42 43 44 41 42 43 44 41 42 43 44 41 42 43 44 41
42 43 44 41 42 43 44 41 42 43 44 41 42 43 44 41
42 43 44 41 42 43 44 41 42 43 44 41 42 43 44 41
42 43 44 41 42 43 44 41 42 43 44 41 42 43 44 41
42 43 44 41 42 43 44 41 42 43 44 41 42 43 44 41
42 43 44 41 42 43 44 41 42 43 44 41 42 43 44 41
42 43 44 41 42 43 44 41 42 43 44 41 42 43 44 41
42 43 44 41 42 43 44 41 42 43 44 41 42 43 44 41
42 43 44 41 42 43 44 41 42 43 44 41 42 43 44 41
42 43 44 41 42 43 44 41 42 43 44 41 42 43 44 41
42 43 44 41 42 43 44 41 42 43 44 41 42 43 44 41
42 43 44 41 42 43 44 41 42 43 44 41 42 43 44 41
42 43 44 41 42 43 44 41 42 43 44 41 42 43 44 41
42 43 44 41 42 43 44 41 42 43 44 41 42 43 44 41
42 43 44 41 42 43 44 41 42 43 44 41 42 43 44 41
42 43
).join(' ')
result = unpack_record(@data_validation.__send__("pack_dv_string", string, max_length))
assert_equal(target, result, caption)
end
end
|
Radanisk/writeexcel
|
examples/repeat.rb
|
# -*- coding: utf-8 -*-
#!/usr/bin/ruby -w
######################################################################
#
# Example of writing repeated formulas.
#
# reverse('©'), August 2002, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
workbook = WriteExcel.new("repeat.xls")
worksheet = workbook.add_worksheet
limit = 1000
# Write a column of numbers
0.upto(limit) do |row|
worksheet.write(row, 0, row)
end
# Store a formula
formula = worksheet.store_formula('=A1*5+4')
# Write a column of formulas based on the stored formula
0.upto(limit) do |row|
worksheet.repeat_formula(row, 1, formula, nil,
/A1/, 'A'+(row+1).to_s)
end
# Direct formula writing. As a speed comparison uncomment the
# following and run the program again
#for row (0..limit) {
# worksheet.write_formula(row, 2, '=A'.(row+1).'*5+4')
#}
workbook.close
|
Radanisk/writeexcel
|
test/test_30_validation_dval.rb
|
<filename>test/test_30_validation_dval.rb
# -*- coding: utf-8 -*-
##########################################################################
# test_30_validation_dval.rb
#
# Tests for the Excel DVAL structure used in data validation.
#
# reverse('©'), September 2005, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
#########################################################################
require 'helper'
require 'stringio'
class TC_validation_dval < Test::Unit::TestCase
def setup
@workbook = WriteExcel.new(StringIO.new)
@worksheet = @workbook.add_worksheet
@validations = Writeexcel::Worksheet::DataValidations.new
end
def teardown
if @workbook.instance_variable_get(:@filehandle)
@workbook.instance_variable_get(:@filehandle).close(true)
end
if @worksheet.instance_variable_get(:@filehandle)
@worksheet.instance_variable_get(:@filehandle).close(true)
end
end
def test_1
obj_id = 1
dv_count = 1
caption = " \tData validation: _store_dval(#{obj_id}, #{dv_count})"
target = %w(
B2 01 12 00 04 00 00 00 00 00 00 00 00 00 01 00
00 00 01 00 00 00
).join(' ')
result = unpack_record(@validations.__send__("dval_record", obj_id, dv_count))
assert_equal(target, result, caption)
end
def test_2
obj_id = -1
dv_count = 1
caption = " \tData validation: _store_dval(#{obj_id}, #{dv_count})"
target = %w(
B2 01 12 00 04 00 00 00 00 00 00 00 00 00 FF FF
FF FF 01 00 00 00
).join(' ')
result = unpack_record(@validations.__send__("dval_record", obj_id, dv_count))
assert_equal(target, result, caption)
end
def test_3
obj_id = 1
dv_count = 2
caption = " \tData validation: _store_dval(#{obj_id}, #{dv_count})"
target = %w(
B2 01 12 00 04 00 00 00 00 00 00 00 00 00 01 00
00 00 02 00 00 00
).join(' ')
result = unpack_record(@validations.__send__("dval_record", obj_id, dv_count))
assert_equal(target, result, caption)
end
end
|
Radanisk/writeexcel
|
test/test_40_property_types.rb
|
<filename>test/test_40_property_types.rb
# -*- coding: utf-8 -*-
##########################################################################
# test_40_property_types.rb
#
# Tests for the basic property types used in OLE property sets.
#
# reverse('©'), September 2005, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
#########################################################################
require 'helper'
class TC_property_types < Test::Unit::TestCase
def setup
@smiley = '☺' # chr 0x263A; in perl
end
def test_pack_a_VT_I2
caption = " \tDoc properties: pack_VT_I2(1252)"
target = %w(
02 00 00 00 E4 04 00 00
).join(' ')
result = unpack_record(pack_VT_I2(1252))
assert_equal(target, result, caption)
end
def test_pack_a_VT_LPSTR_string_and_check_for_padding
string = ''
codepage = 0x04E4
caption = " \tDoc properties: _pack_VT_LPSTR('#{string}',\t#{codepage}')"
target = %w(
1E 00 00 00 01 00 00 00 00 00 00 00
).join(' ')
result = unpack_record(pack_VT_LPSTR(string, codepage))
assert_equal(target, result, caption)
end
def test_pack_a_VT_LPSTR_string_and_check_for_padding_2
string = 'a'
codepage = 0x04E4
caption = " \tDoc properties: _pack_VT_LPSTR('#{string}',\t#{codepage}')"
target = %w(
1E 00 00 00 02 00 00 00 61 00 00 00
).join(' ')
result = unpack_record(pack_VT_LPSTR(string, codepage))
assert_equal(target, result, caption)
end
def test_pack_a_VT_LPSTR_string_and_check_for_padding_3
string = 'bb'
codepage = 0x04E4
caption = " \tDoc properties: _pack_VT_LPSTR('#{string}',\t#{codepage}')"
target = %w(
1E 00 00 00 03 00 00 00 62 62 00 00
).join(' ')
result = unpack_record(pack_VT_LPSTR(string, codepage))
assert_equal(target, result, caption)
end
def test_pack_a_VT_LPSTR_string_and_check_for_padding_4
string = 'ccc'
codepage = 0x04E4
caption = " \tDoc properties: _pack_VT_LPSTR('#{string}',\t#{codepage}')"
target = %w(
1E 00 00 00 04 00 00 00 63 63 63 00
).join(' ')
result = unpack_record(pack_VT_LPSTR(string, codepage))
assert_equal(target, result, caption)
end
def test_pack_a_VT_LPSTR_string_and_check_for_padding_5
string = 'dddd'
codepage = 0x04E4
caption = " \tDoc properties: _pack_VT_LPSTR('#{string}',\t#{codepage}')"
target = %w(
1E 00 00 00 05 00 00 00 64 64 64 64 00 00 00 00
).join(' ')
result = unpack_record(pack_VT_LPSTR(string, codepage))
assert_equal(target, result, caption)
end
def test_pack_a_VT_LPSTR_string_and_check_for_padding_6
string = 'Username'
codepage = 0x04E4
caption = " \tDoc properties: _pack_VT_LPSTR('#{string}',\t#{codepage}')"
target = %w(
1E 00 00 00 09 00 00 00 55 73 65 72 6E 61 6D 65
00 00 00 00
).join(' ')
result = unpack_record(pack_VT_LPSTR(string, codepage))
assert_equal(target, result, caption)
end
def test_pack_a_VT_LPSTR_UTF8_string
string = @smiley
codepage = 0xFDE9
caption = " \tDoc properties: _pack_VT_LPSTR('#{@smiley}',\t#{codepage}')"
target = %w(
1E 00 00 00 04 00 00 00 E2 98 BA 00
).join(' ')
result = unpack_record(pack_VT_LPSTR(string, codepage))
assert_equal(target, result, caption)
end
def test_pack_a_VT_LPSTR_UTF8_string_2
string = "a" + @smiley
codepage = 0xFDE9
caption = " \tDoc properties: _pack_VT_LPSTR('a#{@smiley}',\t#{codepage}')"
target = %w(
1E 00 00 00 05 00 00 00 61 E2 98 BA 00 00 00 00
).join(' ')
result = unpack_record(pack_VT_LPSTR(string, codepage))
assert_equal(target, result, caption)
end
def test_pack_a_VT_LPSTR_UTF8_string_3
string = "aa" + @smiley
codepage = 0xFDE9
caption = " \tDoc properties: _pack_VT_LPSTR('#{string}',\t#{codepage}')"
target = %w(
1E 00 00 00 06 00 00 00 61 61 E2 98 BA 00 00 00
).join(' ')
result = unpack_record( pack_VT_LPSTR(string, codepage) )
assert_equal(target, result, caption)
end
def test_pack_a_VT_LPSTR_UTF8_string_4
string = "aaa" + @smiley
codepage = 0xFDE9
caption = " \tDoc properties: _pack_VT_LPSTR('#{string}',\t#{codepage}')"
target = %w(
1E 00 00 00 07 00 00 00 61 61 61 E2 98 BA 00 00
).join(' ')
result = unpack_record( pack_VT_LPSTR(string, codepage) )
assert_equal(target, result, caption)
end
def test_pack_a_VT_LPSTR_UTF8_string_5
string = "aaaa" + @smiley
codepage = 0xFDE9
caption = " \tDoc properties: _pack_VT_LPSTR('#{string}',\t#{codepage}')"
target = %w(
1E 00 00 00 08 00 00 00 61 61 61 61 E2 98 BA 00
).join(' ')
result = unpack_record( pack_VT_LPSTR(string, codepage) )
assert_equal(target, result, caption)
end
def test_pack_a_VT_FILETIME
# Wed Aug 13 00:40:00 2008
# $sec,$min,$hour,$mday,$mon,$year
# We normalise the time using timegm() so that the tests don't fail due to
# different timezones.
filetime = Time.gm(2008,8,13,0,40,0)
caption = " \tDoc properties: _pack_VT_FILETIME()"
target = %w(
40 00 00 00 00 70 EB 1D DD FC C8 01
).join(' ')
result = unpack_record( pack_VT_FILETIME(filetime) )
assert_equal(target, result, caption)
end
end
|
Radanisk/writeexcel
|
test/test_27_autofilter.rb
|
<filename>test/test_27_autofilter.rb<gh_stars>10-100
# -*- coding: utf-8 -*-
##########################################################################
# test_27_autofilter.rb
#
# Tests for the token extraction method used to parse autofilter expressions.
#
# reverse('©'), September 2005, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
#########################################################################
require 'helper'
require 'stringio'
class TC_27_autofilter < Test::Unit::TestCase
def test_27_autofilter
@tests.each do |test|
expression = test[0]
expected = test[1]
result = @worksheet.__send__("extract_filter_tokens", expression)
testname = expression || 'none'
assert_equal(expected, result, testname)
end
end
def setup
@workbook = WriteExcel.new(StringIO.new)
@worksheet = @workbook.add_worksheet
@tests = [
[
nil,
[],
],
[
'',
[],
],
[
'0 < 2000',
[0, '<', 2000],
],
[
'x < 2000',
['x', '<', 2000],
],
[
'x > 2000',
['x', '>', 2000],
],
[
'x == 2000',
['x', '==', 2000],
],
[
'x > 2000 and x < 5000',
['x', '>', 2000, 'and', 'x', '<', 5000],
],
[
'x = "foo"',
['x', '=', 'foo'],
],
[
'x = foo',
['x', '=', 'foo'],
],
[
'x = "foo bar"',
['x', '=', 'foo bar'],
],
[
'x = "foo "" bar"',
['x', '=', 'foo " bar'],
],
[
'x = "foo bar" or x = "bar foo"',
['x', '=', 'foo bar', 'or', 'x', '=', 'bar foo'],
],
[
'x = "foo "" bar" or x = "bar "" foo"',
['x', '=', 'foo " bar', 'or', 'x', '=', 'bar " foo'],
],
[
'x = """"""""',
['x', '=', '"""'],
],
[
'x = Blanks',
['x', '=', 'Blanks'],
],
[
'x = NonBlanks',
['x', '=', 'NonBlanks'],
],
[
'top 10 %',
['top', 10, '%'],
],
[
'top 10 items',
['top', 10, 'items'],
],
]
end
end
|
Radanisk/writeexcel
|
charts/demo1.rb
|
<filename>charts/demo1.rb<gh_stars>10-100
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
###############################################################################
#
# Simple example of how to add an externally created chart to a Spreadsheet::
# WriteExcel file.
#
#
# This example adds a line chart extracted from the file Chart1.xls as follows:
#
# perl chartex.pl -c=demo1 Chart1.xls
#
#
# reverse('ゥ'), September 2004, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
workbook = WriteExcel.new("demo1.xls")
worksheet = workbook.add_worksheet
# Add the chart extracted using the chartex utility
chart = workbook.add_chart_ext('demo101.bin', 'Chart1')
# Link the chart to the worksheet data using a dummy formula.
worksheet.store_formula('=Sheet1!A1')
# Add some extra formats to cover formats used in the charts.
chart_font_1 = workbook.add_format(:font_only => 1)
chart_font_2 = workbook.add_format(:font_only => 1)
chart_font_3 = workbook.add_format(:font_only => 1)
# Add all other formats (if any).
# Add data to range that the chart refers to.
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
worksheet.write_col('A1', nums )
worksheet.write_col('B1', squares)
workbook.close
|
Radanisk/writeexcel
|
test/test_13_date_seconds.rb
|
<reponame>Radanisk/writeexcel
# -*- coding: utf-8 -*-
###############################################################################
#
# A test for WriteExcel.
#
# Tests date and time second handling.
#
# reverse('©'), May 2004, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
############################################################################
require 'helper'
require 'stringio'
class TC_data_seconds < Test::Unit::TestCase
def setup
@workbook = WriteExcel.new(StringIO.new)
@worksheet = @workbook.add_worksheet
@fit_delta = 0.5/(24 * 60 * 60 * 1000)
end
def fit_cmp(a, b)
return (a-b).abs < @fit_delta
end
def test_some_false_times
# These should fail.
date_time = '1899-12-31T24:00:00.000'
assert(! @worksheet.__send__("convert_date_time", date_time),
" Testing incorrect time: #{date_time}\tincorrect hour caught.")
date_time = '1899-12-31T00:60:00.000'
assert(! @worksheet.__send__("convert_date_time", date_time),
" Testing incorrect time: #{date_time}\tincorrect mins caught.")
date_time = '1899-12-31T00:00:60.000'
assert(! @worksheet.__send__("convert_date_time", date_time),
" Testing incorrect time: $date_time\tincorrect secs caught.")
date_time = '1899-12-31T00:00:59.9999999999999999999'
assert(! @worksheet.__send__("convert_date_time", date_time),
" Testing incorrect time: $date_time\tincorrect secs caught.")
end
def test_the_time_data_generated_in_excel
lines = data_generated_excel.split(/\n/)
while !lines.empty?
line = lines.shift
braak if line =~ /^\s*# stop/ # For debugging
next unless line =~ /\S/ # Ignore blank lines
next if line =~ /^\s*#/ # Ignore comments
if line =~ /"DateTime">([^<]+)/
date_time = $1
line = lines.shift
if line =~ /"Number">([^<]+)/
number = $1.to_f
result = @worksheet.__send__("convert_date_time", date_time)
result = -1 if result.nil?
assert(fit_cmp(number, result),
"date_time: #{date_time}\n" +
"difference between #{number} and #{result}\n" +
"= #{(number - result).abs.to_s}\n" +
"> #{@fit_delta.to_s}")
end
end
end
end
def data_generated_excel
return <<-__DATA_END__
# Test data taken from Excel in XML format.
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T00:00:00.000</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T00:15:20.213</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">1.0650613425925924E-2</Data>< /Cell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T00:16:48.290</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">1.1670023148148148E-2</Data>< /Cell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T00:55:25.446</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">3.8488958333333337E-2</Data>< /Cell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T01:02:46.891</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">4.3598275462962965E-2</Data>< /Cell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T01:04:15.597</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">4.4624965277777782E-2</Data>< /Cell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T01:09:40.889</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">4.8389918981481483E-2</Data>< /Cell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T01:11:32.560</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">4.9682407407407404E-2</Data>< /Cell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T01:30:19.169</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">6.2721863425925936E-2</Data>< /Cell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T01:48:25.580</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">7.5296064814814809E-2</Data>< /Cell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T02:03:31.919</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">8.5786099537037031E-2</Data>< /Cell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T02:11:11.986</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">9.1110949074074077E-2</Data>< /Cell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T02:24:37.095</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.10042934027777778</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T02:35:07.220</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.1077224537037037</Data></Ce ll>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T02:45:12.109</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.11472348379629631</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T03:06:39.990</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.12962951388888888</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T03:08:08.251</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.13065105324074075</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T03:19:12.576</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.13833999999999999</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T03:29:42.574</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.14563164351851851</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T03:37:30.813</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.1510510763888889</Data></Ce ll>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T04:14:38.231</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.1768313773148148</Data></Ce ll>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T04:16:28.559</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.17810832175925925</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T04:17:58.222</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.17914608796296297</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T04:21:41.794</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.18173372685185185</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T04:56:35.792</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.2059698148148148</Data></Ce ll>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T05:25:14.885</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.22586672453703704</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T05:26:05.724</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.22645513888888891</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T05:46:44.068</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.24078782407407406</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T05:48:01.141</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.2416798726851852</Data></Ce ll>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T05:53:52.315</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.24574438657407408</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T06:14:48.580</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.26028449074074073</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T06:46:15.738</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.28212659722222222</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T07:31:20.407</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.31343063657407405</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T07:58:33.754</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.33233511574074076</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T08:07:43.130</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.33869363425925925</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T08:29:11.091</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.35360059027777774</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T09:08:15.328</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.380732962962963</Data></Cel l>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T09:30:41.781</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.39631690972222228</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T09:34:04.462</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.39866275462962958</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T09:37:23.945</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.40097158564814817</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T09:37:56.655</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.40135017361111114</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T09:45:12.230</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.40639155092592594</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T09:54:14.782</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.41267108796296298</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T09:54:22.108</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.41275587962962962</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T10:01:36.151</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.41777952546296299</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T12:09:48.602</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.50681252314814818</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T12:34:08.549</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.52371005787037039</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T12:56:06.495</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.53896406249999995</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T12:58:58.217</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.54095158564814816</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T12:59:54.263</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.54160026620370372</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T13:34:41.331</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.56575614583333333</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T13:58:28.601</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.58227547453703699</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T14:02:16.899</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.58491781249999997</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T14:36:17.444</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.60853523148148148</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T14:37:57.451</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.60969271990740748</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T14:57:42.757</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.6234115393518519</Data></Ce ll>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T15:10:48.307</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.6325035532407407</Data></Ce ll>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T15:14:39.890</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.63518391203703706</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T15:19:47.988</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.63874986111111109</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T16:04:24.344</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.66972620370370362</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T16:22:23.952</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.68222166666666662</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T16:29:55.999</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.6874536921296297</Data></Ce ll>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T16:58:20.259</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.70717892361111112</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T17:04:02.415</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.71113906250000003</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T17:18:29.630</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.72117627314814825</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T17:47:21.323</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.74121901620370367</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T17:53:29.866</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.74548456018518516</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T17:53:41.076</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.74561430555555563</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T17:55:06.044</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.74659773148148145</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T18:14:49.151</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.760291099537037</Data></Cel l>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T18:17:45.738</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.76233493055555546</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T18:29:59.700</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.77082986111111118</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T18:33:21.233</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.77316241898148153</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T19:14:24.673</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.80167445601851861</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T19:17:12.816</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.80362055555555545</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T19:23:36.418</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.80806039351851855</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T19:46:25.908</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.82391097222222232</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T20:07:47.314</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.83874206018518516</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T20:31:37.603</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.85529633101851854</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T20:39:57.770</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.86108530092592594</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T20:50:17.067</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.86825309027777775</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T21:02:57.827</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.87705818287037041</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T21:23:05.519</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.891036099537037</Data></Cel l>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T21:34:49.572</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.89918486111111118</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T21:39:05.944</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.90215212962962965</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T21:39:18.426</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.90229659722222222</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T21:46:07.769</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.90703436342592603</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T21:57:55.662</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.91522756944444439</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T22:19:11.732</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.92999689814814823</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T22:23:51.376</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.93323351851851843</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T22:27:58.771</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.93609688657407408</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T22:43:30.392</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.94687953703703709</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T22:48:25.834</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.95029900462962968</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T22:53:51.727</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.95407091435185187</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T23:12:56.536</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.96732101851851848</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T23:15:54.109</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.96937626157407408</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T23:17:12.632</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.97028509259259266</Data></C ell>
</Row>
<Row>
<Cell ss:StyleID="s22"><Data ss:Type="DateTime">1899-12-31T23:59:59.999</Data></Cell>
<Cell ss:StyleID="s23" ss:Formula="=RC[-1]"><Data ss:Type="Number">0.99999998842592586</Data></C ell>
</Row>
__DATA_END__
end
end
|
Radanisk/writeexcel
|
lib/writeexcel/charts/stock.rb
|
# -*- coding: utf-8 -*-
###############################################################################
#
# Stock - A writer class for Excel Stock charts.
#
# Used in conjunction with WriteExcel::Chart.
#
# See formatting note in WriteExcel::Chart.
#
# Copyright 2000-2010, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
module Writeexcel
class Chart
# ==SYNOPSIS
#
# To create a simple Excel file with a Stock chart using WriteExcel:
#
# #!/usr/bin/ruby -w
#
# require 'writeexcel'
#
# workbook = WriteExcel.new('chart.xls')
# worksheet = workbook.add_worksheet
#
# chart = workbook.add_chart(:type => 'Chart::Stock')
#
# # Add a series for each Open-High-Low-Close.
# chart.add_series(:categories => '=Sheet1!$A$2:$A$6', :values => '=Sheet1!$B$2:$B$6')
# chart.add_series(:categories => '=Sheet1!$A$2:$A$6', :values => '=Sheet1!$C$2:$C$6')
# chart.add_series(:categories => '=Sheet1!$A$2:$A$6', :values => '=Sheet1!$D$2:$D$6')
# chart.add_series(:categories => '=Sheet1!$A$2:$A$6', :values => '=Sheet1!$E$2:$E$6')
#
# # Add the worksheet data the chart refers to.
# # ... See the full example below.
#
# workbook.close
#
# ==DESCRIPTION
#
# This module implements Stock charts for WriteExcel. The chart object
# is created via the Workbook add_chart() method:
#
# chart = workbook.add_chart(:type => 'Chart::Stock')
#
# Once the object is created it can be configured via the following methods
# that are common to all chart classes:
#
# chart.add_series
# chart.set_x_axis
# chart.set_y_axis
# chart.set_title
#
# These methods are explained in detail in Chart section of WriteExcel.
# Class specific methods or settings, if any, are explained below.
#
# ==Stock Chart Methods
#
# There aren't currently any stock chart specific methods.
# See the TODO section of Chart section in WriteExcel.
#
# The default Stock chart is an Open-High-Low-Close chart.
# A series must be added for each of these data sources.
#
# The default Stock chart is in black and white. User defined colours
# will be added at a later stage.
#
# ==EXAMPLE
#
# Here is a complete example that demonstrates most of the available features
# when creating a Stock chart.
#
# #!/usr/bin/ruby -w
#
# require 'writeexcel'
#
# workbook = WriteExcel.new('chart_stock_ex.xls')
# worksheet = workbook.add_worksheet
# bold = workbook.add_format(:bold => 1)
# date_format = workbook.add_format(:num_format => 'dd/mm/yyyy')
#
# # Add the worksheet data that the charts will refer to.
# headings = [ 'Date', 'Open', 'High', 'Low', 'Close' ]
# data = [
# [ '2009-08-23', 110.75, 113.48, 109.05, 109.40 ],
# [ '2009-08-24', 111.24, 111.60, 103.57, 104.87 ],
# [ '2009-08-25', 104.96, 108.00, 103.88, 106.00 ],
# [ '2009-08-26', 104.95, 107.95, 104.66, 107.91 ],
# [ '2009-08-27', 108.10, 108.62, 105.69, 106.15 ]
# ]
#
# worksheet.write('A1', headings, bold)
#
# row = 1
# data.each do |d|
# worksheet.write(row, 0, d[0], date_format)
# worksheet.write(row, 1, d[1])
# worksheet.write(row, 2, d[2])
# worksheet.write(row, 3, d[3])
# worksheet.write(row, 4, d[4])
# row += 1
# end
#
# # Create a new chart object. In this case an embedded chart.
# chart = workbook.add_chart(:type => 'Chart::Stock', ::embedded => 1)
#
# # Add a series for each of the Open-High-Low-Close columns.
# chart.add_series(
# :categories => '=Sheet1!$A$2:$A$6',
# :values => '=Sheet1!$B$2:$B$6',
# :name => 'Open'
# )
#
# chart.add_series(
# :categories => '=Sheet1!$A$2:$A$6',
# :values => '=Sheet1!$C$2:$C$6',
# :name => 'High'
# )
#
# chart.add_series(
# :categories => '=Sheet1!$A$2:$A$6',
# :values => '=Sheet1!$D$2:$D$6',
# :name => 'Low'
# )
#
# chart.add_series(
# :categories => '=Sheet1!$A$2:$A$6',
# :values => '=Sheet1!$E$2:$E$6',
# :name => 'Close'
# )
#
# # Add a chart title and some axis labels.
# chart.set_title(:name => 'Open-High-Low-Close')
# chart.set_x_axis(:name => 'Date')
# chart.set_y_axis(:name => 'Share price')
#
# # Insert the chart into the worksheet (with an offset).
# worksheet.insert_chart('F2', chart, 25, 10)
#
# workbook.close
#
class Stock < Chart
###############################################################################
#
# new()
#
#
def initialize(*args) # :nodoc:
super
end
###############################################################################
#
# _store_chart_type()
#
# Implementation of the abstract method from the specific chart class.
#
# Write the LINE chart BIFF record. A stock chart uses the same LINE record
# as a line chart but with additional DROPBAR and CHARTLINE records to define
# the stock style.
#
def store_chart_type # :nodoc:
record = 0x1018 # Record identifier.
length = 0x0002 # Number of bytes to follow.
grbit = 0x0000 # Option flags.
store_simple(record, length, grbit)
end
###############################################################################
#
# _store_marker_dataformat_stream(). Overridden.
#
# This is an implementation of the parent abstract method to define
# properties of markers, linetypes, pie formats and other.
#
def store_marker_dataformat_stream # :nodoc:
store_dropbar
store_begin
store_lineformat(0x00000000, 0x0000, 0xFFFF, 0x0001, 0x004F)
store_areaformat(0x00FFFFFF, 0x0000, 0x01, 0x01, 0x09, 0x08)
store_end
store_dropbar
store_begin
store_lineformat(0x00000000, 0x0000, 0xFFFF, 0x0001, 0x004F)
store_areaformat(0x0000, 0x00FFFFFF, 0x01, 0x01, 0x08, 0x09)
store_end
store_chartline
store_lineformat(0x00000000, 0x0000, 0xFFFF, 0x0000, 0x004F)
store_dataformat(0x0000, 0xFFFD, 0x0000)
store_begin
store_3dbarshape
store_lineformat(0x00000000, 0x0005, 0xFFFF, 0x0000, 0x004F)
store_areaformat(0x00000000, 0x0000, 0x00, 0x01, 0x4D, 0x4D)
store_pieformat
store_markerformat(0x00, 0x00, 0x00, 0x00, 0x4D, 0x4D, 0x3C)
store_end
end
end
end # class Chart
end # module Writeexcel
|
Radanisk/writeexcel
|
lib/writeexcel/charts/scatter.rb
|
<reponame>Radanisk/writeexcel
# -*- coding: utf-8 -*-
###############################################################################
#
# Scatter - A writer class for Excel Scatter charts.
#
# Used in conjunction with WriteExcel::Chart.
#
# See formatting note in WriteExcel::Chart.
#
# Copyright 2000-2010, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
module Writeexcel
class Chart
# ==SYNOPSIS
#
# To create a simple Excel file with a Scatter chart using WriteExcel:
#
# #!/usr/bin/ruby -w
#
# require 'writeexcel'
#
# workbook = WriteExcel.new('chart.xls')
# worksheet = workbook.add_worksheet
#
# chart = workbook.add_chart(:type => 'Chart::Scatter')
#
# # Configure the chart.
# chart.add_series(
# :categories => '=Sheet1!$A$2:$A$7',
# :values => '=Sheet1!$B$2:$B$7'
# )
#
# # Add the worksheet data the chart refers to.
# data = [
# [ 'Category', 2, 3, 4, 5, 6, 7 ],
# [ 'Value', 1, 4, 5, 2, 1, 5 ]
# ]
#
# worksheet.write('A1', data)
#
# workbook.close
#
# ==DESCRIPTION
#
# This module implements Scatter charts for WriteExcel.
# The chart object is created via the Workbook add_chart() method:
#
# chart = workbook.add_chart(:type => 'Chart::Scatter')
#
# Once the object is created it can be configured via the following
# methods that are common to all chart classes:
#
# chart.add_series
# chart.set_x_axis
# chart.set_y_axis
# chart.set_title
#
# These methods are explained in detail in Chart section of WriteExcel.
# Class specific methods or settings, if any, are explained below.
#
# ==Scatter Chart Methods
#
# There aren't currently any scatter chart specific methods. See the TODO
# section of Chart section in WriteExcel.
#
# ==EXAMPLE
#
# Here is a complete example that demonstrates most of the available
# features when creating a chart.
#
# #!/usr/bin/ruby -w
#
# require 'writeexcel'
#
# workbook = WriteExcel.new('chart_scatter.xls')
# worksheet = workbook.add_worksheet
# bold = workbook.add_format(:bold => 1)
#
# # Add the worksheet data that the charts will refer to.
# headings = [ 'Number', 'Sample 1', 'Sample 2' ]
# data = [
# [ 2, 3, 4, 5, 6, 7 ],
# [ 1, 4, 5, 2, 1, 5 ],
# [ 3, 6, 7, 5, 4, 3 ]
# ]
#
# worksheet.write('A1', headings, bold)
# worksheet.write('A2', data)
#
# # Create a new chart object. In this case an embedded chart.
# chart = workbook.add_chart(:type => 'Chart::Scatter', :embedded => 1)
#
# # Configure the first series. (Sample 1)
# chart.add_series(
# :name => 'Sample 1',
# :categories => '=Sheet1!$A$2:$A$7',
# :values => '=Sheet1!$B$2:$B$7'
# )
#
# # Configure the second series. (Sample 2)
# chart.add_series(
# :name => 'Sample 2',
# :categories => '=Sheet1!$A$2:$A$7',
# :values => '=Sheet1!$C$2:$C$7'
# )
#
# # Add a chart title and some axis labels.
# chart.set_title (:name => 'Results of sample analysis')
# chart.set_x_axis(:name => 'Test number')
# chart.set_y_axis(:name => 'Sample length (cm)')
#
# # Insert the chart into the worksheet (with an offset).
# worksheet.insert_chart('D2', chart, 25, 10)
#
# workbook.close
#
class Scatter < Chart
###############################################################################
#
# new()
#
#
def initialize(*args) # :nodoc:
super
end
###############################################################################
#
# _store_chart_type()
#
# Implementation of the abstract method from the specific chart class.
#
# Write the AREA chart BIFF record. Defines a area chart type.
#
def store_chart_type # :nodoc:
record = 0x101B # Record identifier.
length = 0x0006 # Number of bytes to follow.
bubble_ratio = 0x0064 # Bubble ratio.
bubble_type = 0x0001 # Bubble type.
grbit = 0x0000 # Option flags.
store_simple(record, length, bubble_ratio, bubble_type, grbit)
end
###############################################################################
#
# _store_axis_category_stream(). Overridden.
#
# Write the AXIS chart substream for the chart category.
#
# For a Scatter chart the category stream is replace with a values stream. We
# override this method and turn it into a values stream.
#
def store_axis_category_stream # :nodoc:
store_axis(0)
store_begin
store_valuerange
store_tick
store_end
end
###############################################################################
#
# _store_marker_dataformat_stream(). Overridden.
#
# This is an implementation of the parent abstract method to define
# properties of markers, linetypes, pie formats and other.
#
def store_marker_dataformat_stream # :nodoc:
store_dataformat(0x0000, 0xFFFD, 0x0000)
store_begin
store_3dbarshape
store_lineformat(0x00000000, 0x0005, 0xFFFF, 0x0008, 0x004D)
store_areaformat(0x00FFFFFF, 0x0000, 0x01, 0x01, 0x4E, 0x4D)
store_pieformat
store_markerformat(0x00, 0x00, 0x02, 0x01, 0x4D, 0x4D, 0x3C)
store_end
end
end
end # class Chart
end # module Writeexcel
|
Radanisk/writeexcel
|
test/test_06_extsst.rb
|
# -*- coding: utf-8 -*-
###############################################################################
#
# A test for WriteExcel.
#
# all test is commented out because Workbook#calculate_extsst_size was set to
# private method. Before that, all test passed.
#
# Check that we calculate the correct bucket size and number for the EXTSST
# record. The data is taken from actual Excel files.
#
# reverse('©'), October 2007, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
############################################################################
require 'helper'
require 'stringio'
class TC_extsst < Test::Unit::TestCase
def setup
@tests = [
# Unique Number of Bucket
# strings buckets size
[0, 0, 8],
[1, 1, 8],
[7, 1, 8],
[8, 1, 8],
[15, 2, 8],
[16, 2, 8],
[17, 3, 8],
[32, 4, 8],
[33, 5, 8],
[64, 8, 8],
[128, 16, 8],
[256, 32, 8],
[512, 64, 8],
[1023, 128, 8],
[1024, 114, 9],
[1025, 114, 9],
[2048, 121, 17],
[4096, 125, 33],
[4097, 125, 33],
[8192, 127, 65],
[8193, 127, 65],
[9000, 127, 71],
[10000, 127, 79],
[16384, 128, 129],
[262144, 128, 2049],
[1048576, 128, 8193],
[4194304, 128, 32769],
[8257536, 128, 64513],
]
end
def teardown
if @workbook.instance_variable_get(:@filehandle)
@workbook.instance_variable_get(:@filehandle).close(true)
end
if @worksheet.instance_variable_get(:@filehandle)
@worksheet.instance_variable_get(:@filehandle).close(true)
end
end
def test_to_tests
@tests.each do |test|
io = StringIO.new
workbook = WriteExcel.new(io)
workbook.not_using_tmpfile
str_unique = test[0]
workbook.__send__("calculate_extsst_size", str_unique)
assert_equal(test[1], workbook.extsst_buckets,
" \tBucket number for #{str_unique} strings")
assert_equal(test[2], workbook.extsst_bucket_size,
" \tBucket size for #{str_unique} strings")
end
end
end
|
Radanisk/writeexcel
|
lib/writeexcel/worksheet.rb
|
<reponame>Radanisk/writeexcel
# -*- coding: utf-8 -*-
###############################################################################
#
# Worksheet - A writer class for Excel Worksheets.
#
#
# Used in conjunction with WriteExcel
#
# Copyright 2000-2010, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel/biffwriter'
require 'writeexcel/format'
require 'writeexcel/formula'
require 'writeexcel/compatibility'
require 'writeexcel/image'
require 'writeexcel/cell_range'
require 'writeexcel/embedded_chart'
require 'writeexcel/outline'
require 'writeexcel/col_info'
require 'writeexcel/comments'
require 'writeexcel/data_validations'
require 'writeexcel/convert_date_time'
class MaxSizeError < StandardError #:nodoc:
end
module Writeexcel
#
# = class Worksheet
#
# A new worksheet is created by calling the add_worksheet() method from a workbook object:
#
# Examples:
#
# workbook = WriteExcel.new('file.xls')
# worksheet1 = workbook.add_worksheet
# worksheet2 = workbook.add_worksheet
#
class Worksheet < BIFFWriter
require 'writeexcel/helper'
include ConvertDateTime
class ObjectIds
attr_accessor :spid
attr_reader :drawings_saved, :num_shapes, :max_spid
def initialize(spid, drawings_saved, num_shapes, max_spid)
@spid = spid
@drawings_saved = drawings_saved
@num_shapes = num_shapes
@max_spid = max_spid
end
end
RowMax = 65536 # :nodoc:
ColMax = 256 # :nodoc:
StrMax = 0 # :nodoc:
Buffer = 4096 # :nodoc:
attr_reader :title_range, :print_range, :filter_area, :object_ids
#
# Constructor. Creates a new Worksheet object from a BIFFwriter object
#
def initialize(workbook, name, name_utf16be) # :nodoc:
super()
@workbook = workbook
@name = name
@name_utf16be = name_utf16be
@type = 0x0000
@ext_sheets = []
@using_tmpfile = true
@fileclosed = false
@offset = 0
@dimension = CellDimension.new(self)
@colinfo = []
@selection = [0, 0]
@panes = []
@active_pane = 3
@frozen_no_split = 1
@tab_color = 0
@first_row = 0
@first_col = 0
@display_formulas = 0
@display_headers = 1
@paper_size = 0x0
@orientation = 0x1
@margin_header = 0.50
@margin_footer = 0.50
@margin_left = 0.75
@margin_right = 0.75
@margin_top = 1.00
@margin_bottom = 1.00
@title_range = TitleRange.new(self)
@print_range = PrintRange.new(self)
@print_gridlines = 1
@screen_gridlines = 1
@page_order = 0
@black_white = 0
@draft_quality = 0
@print_comments = 0
@page_start = 1
@custom_start = 0
@fit_page = 0
@fit_width = 0
@fit_height = 0
@hbreaks = []
@vbreaks = []
@password = <PASSWORD>
@col_sizes = {}
@row_sizes = {}
@col_formats = {}
@row_formats = {}
@zoom = 100
@print_scale = 100
@page_view = 0
@leading_zeros = false
@outline = Outline.new
@write_match = []
@images = Collection.new
@charts = Collection.new
@comments = Comments.new
@num_images = 0
@image_mso_size = 0
@filter_area = FilterRange.new(self)
@filter_on = 0
@filter_cols = []
@db_indices = []
@validations = DataValidations.new
@table = []
@row_data = {}
end
#
# Add data to the beginning of the workbook (note the reverse order)
# and to the end of the workbook.
#
def close #:nodoc:
################################################
# Prepend in reverse order!!
#
# Prepend the sheet dimensions
store_dimensions
# Prepend the autofilter filters.
store_autofilters
# Prepend the sheet autofilter info.
store_autofilterinfo
# Prepend the sheet filtermode record.
store_filtermode
# Prepend the COLINFO records if they exist
@colinfo.reverse.each do |colinfo|
store_colinfo(colinfo)
end
# Prepend the DEFCOLWIDTH record
store_defcol
# Prepend the sheet password
store_password
# Prepend the sheet protection
store_protect
store_obj_protect
# Prepend the page setup
store_setup
# Prepend the bottom margin
store_margin_bottom
# Prepend the top margin
store_margin_top
# Prepend the right margin
store_margin_right
# Prepend the left margin
store_margin_left
# Prepend the page vertical centering
store_vcenter
# Prepend the page horizontal centering
store_hcenter
# Prepend the page footer
store_footer
# Prepend the page header
store_header
# Prepend the vertical page breaks
store_vbreak
# Prepend the horizontal page breaks
store_hbreak
# Prepend WSBOOL
store_wsbool
# Prepend the default row height.
store_defrow
# Prepend GUTS
store_guts
# Prepend GRIDSET
store_gridset
# Prepend PRINTGRIDLINES
store_print_gridlines
# Prepend PRINTHEADERS
store_print_headers
#
# End of prepend. Read upwards from here.
################################################
# Append
store_table
store_images
store_charts
store_filters
store_comments
store_window2
store_page_view
store_zoom
store_panes(*@panes) if @panes && !@panes.empty?
store_selection(*@selection)
store_validation_count
store_validations
store_tab_color
store_eof
# Prepend the BOF and INDEX records
store_index
store_bof(0x0010)
end
def cleanup # :nodoc:
super
end
#
# The name() method is used to retrieve the name of a worksheet. For example:
#
# workbook.sheets.each do |sheet|
# print sheet.name
# end
#
# For reasons related to the design of WriteExcel and to the internals of
# Excel there is no set_name() method. The only way to set the worksheet
# name is via the add_worksheet() method.
#
def name
@name
end
#
# Set this worksheet as a selected worksheet, i.e. the worksheet has its tab
# highlighted.
#
# The select() method is used to indicate that a worksheet is selected in a
# multi-sheet workbook:
#
# worksheet1.activate
# worksheet2.select
# worksheet3.select
#
# A selected worksheet has its tab highlighted. Selecting worksheets is a way
# of grouping them together so that, for example, several worksheets could be
# printed in one go. A worksheet that has been activated via the activate()
# method will also appear as selected.
#
def select
@hidden = false # Selected worksheet can't be hidden.
@selected = true
end
#
# Set this worksheet as the active worksheet, i.e. the worksheet that is
# displayed when the workbook is opened. Also set it as selected.
#
# The activate() method is used to specify which worksheet is initially
# visible in a multi-sheet workbook:
#
# worksheet1 = workbook.add_worksheet('To')
# worksheet2 = workbook.add_worksheet('the')
# worksheet3 = workbook.add_worksheet('wind')
#
# worksheet3.activate
#
# This is similar to the Excel VBA activate method. More than one worksheet
# can be selected via the select() method, see below, however only one
# worksheet can be active.
#
# The default active worksheet is the first worksheet.
#
def activate
@hidden = false # Active worksheet can't be hidden.
@selected = true
@workbook.worksheets.activesheet = self
end
#
# Hide this worksheet.
#
# The hide() method is used to hide a worksheet:
#
# worksheet2.hide
#
# You may wish to hide a worksheet in order to avoid confusing a user with
# intermediate data or calculations.
#
# A hidden worksheet can not be activated or selected so this method is
# mutually exclusive with the activate() and select() methods. In addition,
# since the first worksheet will default to being the active worksheet,
# you cannot hide the first worksheet without activating another sheet:
#
# worksheet2.activate
# worksheet1.hide
#
def hide
@hidden = true
# A hidden worksheet shouldn't be active or selected.
@selected = false
@workbook.worksheets.activesheet = @workbook.worksheets.first
@workbook.worksheets.firstsheet = @workbook.worksheets.first
end
#
# Set this worksheet as the first visible sheet. This is necessary
# when there are a large number of worksheets and the activated
# worksheet is not visible on the screen.
#
# The activate() method determines which worksheet is initially selected.
# However, if there are a large number of worksheets the selected worksheet
# may not appear on the screen. To avoid this you can select which is the
# leftmost visible worksheet using set_first_sheet
#
# 20.times { workbook.add_worksheet }
#
# worksheet21 = workbook.add_worksheet
# worksheet22 = workbook.add_worksheet
#
# worksheet21.set_first_sheet
# worksheet22.activate
#
# This method is not required very often. The default value is the first
# worksheet.
#
def set_first_sheet
@hidden = false # Active worksheet can't be hidden.
@workbook.worksheets.firstsheet = self
end
#
# Set the worksheet protection flag to prevent accidental modification and to
# hide formulas if the locked and hidden format properties have been set.
#
# The protect() method is used to protect a worksheet from modification:
#
# worksheet.protect
#
# It can be turned off in Excel via the
# Tools->Protection->Unprotect Sheet menu command.
#
# The protect() method also has the effect of enabling a cell's locked and
# hidden properties if they have been set. A "locked" cell cannot be edited.
# A "hidden" cell will display the results of a formula but not the formula
# itself. In Excel a cell's locked property is on by default.
#
# # Set some format properties
# unlocked = workbook.add_format(:locked => 0)
# hidden = workbook.add_format(:hidden => 1)
#
# # Enable worksheet protection
# worksheet.protect
#
# # This cell cannot be edited, it is locked by default
# worksheet.write('A1', '=1+2')
#
# # This cell can be edited
# worksheet.write('A2', '=1+2', unlocked)
#
# # The formula in this cell isn't visible
# worksheet.write('A3', '=1+2', hidden)
#
# See also the set_locked and set_hidden format methods in "CELL FORMATTING".
#
# You can optionally add a password to the worksheet protection:
#
# worksheet.protect('drowssap')
#
# Note,
#
# the worksheet level password in Excel provides very weak protection. It
# does not encrypt your data in any way and it is very easy to deactivate.
# Therefore, do not use the above method if you wish to protect sensitive
# data or calculations. However, before you get worried, Excel's own
# workbook level password protection does provide strong encryption in
# Excel 97+. For technical reasons this will never be supported by
# WriteExcel.
#
def protect(password = <PASSWORD>)
@protect = true
@password = <PASSWORD>(password) if password
end
#
# row : Row Number
# height : Format object
# format : Format object
# hidden : Hidden boolean flag
# level : Outline level
# collapsed : Collapsed row
#
# This method is used to set the height and XF format for a row.
# Writes the BIFF record ROW.
#
# This method can be used to change the default properties of a row. All
# parameters apart from _row_ are optional.
#
# The most common use for this method is to change the height of a row:
#
# worksheet.set_row(0, 20) # Row 1 height set to 20
#
# If you wish to set the _format_ without changing the _height_ you can pass
# nil as the _height_ parameter:
#
# worksheet.set_row(0, nil, format)
#
# The _format_ parameter will be applied to any cells in the row that don't
# have a format. For example
#
# worksheet.set_row(0, nil, format1) # Set the format for row 1
# worksheet.write('A1', 'Hello') # Defaults to format1
# worksheet.write('B1', 'Hello', format2) # Keeps format2
#
# If you wish to define a row format in this way you should call the method
# before any calls to write(). Calling it afterwards will overwrite any format
# that was previously specified.
#
# The hidden parameter should be set to true if you wish to hide a row. This can
# be used, for example, to hide intermediary steps in a complicated calculation:
#
# worksheet.set_row(0, 20, format, true)
# worksheet.set_row(1, nil, nil, true)
#
# The level parameter is used to set the outline level of the row. Outlines
# are described in "OUTLINES AND GROUPING IN EXCEL". Adjacent rows with the
# same outline level are grouped together into a single outline.
#
# The following example sets an outline level of 1 for rows 1 and 2
# (zero-indexed):
#
# worksheet.set_row(1, nil, nil, false, 1)
# worksheet.set_row(2, nil, nil, false, 1)
#
# The hidden parameter can also be used to hide collapsed outlined rows when
# used in conjunction with the level parameter.
#
# worksheet.set_row(1, nil, nil, true, 1)
# worksheet.set_row(2, nil, nil, true, 1)
#
# For collapsed outlines you should also indicate which row has the
# collapsed + symbol using the optional collapsed parameter.
#
# worksheet.set_row(3, nil, nil, false, 0, true)
#
# For a more complete example see the outline.pl and outline_collapsed.rb
# programs in the examples directory of the distro.
#
# Excel allows up to 7 outline levels. Therefore the level parameter should
# be in the range 0 <= level <= 7.
#
def set_row(row, height = nil, format = nil, hidden = false, level = 0, collapsed = false)
record = 0x0208 # Record identifier
length = 0x0010 # Number of bytes to follow
colMic = 0x0000 # First defined column
colMac = 0x0000 # Last defined column
# miyRw; # Row height
irwMac = 0x0000 # Used by Excel to optimise loading
reserved = 0x0000 # Reserved
grbit = 0x0000 # Option flags
# ixfe; # XF index
return unless row
# Check that row and col are valid and store max and min values
return -2 if check_dimensions(row, 0, 0, 1) != 0
# Check for a format object
if format.respond_to?(:xf_index)
ixfe = format.xf_index
else
ixfe = 0x0F
end
# Set the row height in units of 1/20 of a point. Note, some heights may
# not be obtained exactly due to rounding in Excel.
#
if height
miyRw = height *20
else
miyRw = 0xff # The default row height
height = 0
end
# Set the limits for the outline levels (0 <= x <= 7).
level = 0 if level < 0
level = 7 if level > 7
@outline.row_level = level if level > @outline.row_level
# Set the options flags.
# 0x10: The fCollapsed flag indicates that the row contains the "+"
# when an outline group is collapsed.
# 0x20: The fDyZero height flag indicates a collapsed or hidden row.
# 0x40: The fUnsynced flag is used to show that the font and row heights
# are not compatible. This is usually the case for WriteExcel.
# 0x80: The fGhostDirty flag indicates that the row has been formatted.
#
grbit |= level
grbit |= 0x0010 if collapsed && collapsed != 0
grbit |= 0x0020 if hidden && hidden != 0
grbit |= 0x0040
grbit |= 0x0080 if format
grbit |= 0x0100
header = [record, length].pack("vv")
data = [row, colMic, colMac, miyRw, irwMac, reserved, grbit, ixfe].pack("vvvvvvvv")
# Store the data or write immediately depending on the compatibility mode.
if compatibility?
@row_data[row] = header + data
else
append(header, data)
end
# Store the row sizes for use when calculating image vertices.
# Also store the column formats.
@row_sizes[row] = height
@row_formats[row] = format if format
end
#
# :call-seq:
# set_column(first_col, last_col, width, format, hidden, level, collapsed)
# set_column(A1_notation, width, format, hidden, level, collapsed)
#
# Set the width of a single column or a range of columns.
#--
# See also: store_colinfo
#++
#
# This method can be used to change the default properties of a single
# column or a range of columns. All parameters apart from _first_col_ and
# _last_col_ are optional.
#
# If set_column() is applied to a single column the value of _first_col_ and
# _last_col_ should be the same. In the case where _last_col_ is zero it is
# set to the same value as _first_col_.
#
# It is also possible, and generally clearer, to specify a column range
# using the form of A1 notation used for columns. See the note about
# "Cell notation".
#
# Examples:
#
# worksheet.set_column(0, 0, 20) # Column A width set to 20
# worksheet.set_column(1, 3, 30) # Columns B-D width set to 30
# worksheet.set_column('E:E', 20) # Column E width set to 20
# worksheet.set_column('F:H', 30) # Columns F-H width set to 30
#
# The width corresponds to the column width value that is specified in Excel.
# It is approximately equal to the length of a string in the default font
# of Arial 10. Unfortunately, there is no way to specify "AutoFit" for a
# column in the Excel file format. This feature is only available at
# runtime from within Excel.
#
# As usual the _format_ parameter is optional, for additional information,
# see "CELL FORMATTING". If you wish to set the format without changing the
# width you can pass undef as the width parameter:
#
# worksheet.set_column(0, 0, nil, format)
#
# The _format_ parameter will be applied to any cells in the column that
# don't have a format. For example
#
# worksheet.set_column('A:A', nil, format1) # Set format for col 1
# worksheet.write('A1', 'Hello') # Defaults to format1
# worksheet.write('A2', 'Hello', format2) # Keeps format2
#
# If you wish to define a column format in this way you should call the
# method before any calls to write(). If you call it afterwards it won't
# have any effect.
#
# A default row format takes precedence over a default column format
#
# worksheet.set_row(0, nil, format1) # Set format for row 1
# worksheet.set_column('A:A', nil, format2) # Set format for col 1
# worksheet.write('A1', 'Hello') # Defaults to format1
# worksheet.write('A2', 'Hello') # Defaults to format2
#
# The _hidden_ parameter should be set to true if you wish to hide a column.
# This can be used, for example, to hide intermediary steps in a complicated
# calculation:
#
# worksheet.set_column('D:D', 20, format, true)
# worksheet.set_column('E:E', nil, nil, true)
#
# The _level_ parameter is used to set the outline level of the column.
# Outlines are described in "OUTLINES AND GROUPING IN EXCEL". Adjacent
# columns with the same outline level are grouped together into a single
# outline.
#
# The following example sets an outline level of 1 for columns B to G:
#
# worksheet.set_column('B:G', nil, nil, true, 1)
#
# The _hidden_ parameter can also be used to hide collapsed outlined columns
# when used in conjunction with the _level_ parameter.
#
# worksheet.set_column('B:G', nil, nil, true, 1)
#
# For collapsed outlines you should also indicate which row has the
# collapsed + symbol using the optional _collapsed_ parameter.
#
# worksheet.set_column('H:H', nil, nil, true, 0, true)
#
# For a more complete example see the outline.pl and outline_collapsed.rb
# programs in the examples directory of the distro.
#
# Excel allows up to 7 outline levels. Therefore the _level_ parameter
# should be in the range 0 <= level <= 7.
#
def set_column(*args)
# Check for a cell reference in A1 notation and substitute row and column
if args[0] =~ /^\D/
row1, firstcol, row2, lastcol, *data = substitute_cellref(*args)
else
firstcol, lastcol, *data = args
end
# Ensure at least firstcol, lastcol and width
return unless firstcol && lastcol && !data.empty?
# Assume second column is the same as first if 0. Avoids KB918419 bug.
lastcol = firstcol if lastcol == 0
# Ensure 2nd col is larger than first. Also for KB918419 bug.
firstcol, lastcol = lastcol, firstcol if firstcol > lastcol
# Limit columns to Excel max of 255.
firstcol = ColMax - 1 if firstcol > ColMax - 1
lastcol = ColMax - 1 if lastcol > ColMax - 1
@colinfo << ColInfo.new(firstcol, lastcol, *data)
# Store the col sizes for use when calculating image vertices taking
# hidden columns into account. Also store the column formats.
#
width, format, hidden = data
width ||= 0 # Ensure width isn't undef.
width = 0 if hidden && hidden != 0 # Set width to zero if col is hidden
(firstcol .. lastcol).each do |col|
@col_sizes[col] = width
@col_formats[col] = format if format
end
end
#
# :call-seq:
# set_selection(first_row, first_col[, last_row, last_col])
# set_selection('B3')
# set_selection('B3:C8')
#
# Set which cell or cells are selected in a worksheet: see also the
# sub store_selection
#
# This method can be used to specify which cell or cells are selected in a
# worksheet. The most common requirement is to select a single cell, in which
# case _last_row_ and _last_col_ can be omitted. The active cell within a
# selected range is determined by the order in which _first_ and _last_ are
# specified. It is also possible to specify a cell or a range using
# A1 notation. See the note about "Cell notation".
#
# Examples:
#
# worksheet1.set_selection(3, 3) # 1. Cell D4.
# worksheet2.set_selection(3, 3, 6, 6) # 2. Cells D4 to G7.
# worksheet3.set_selection(6, 6, 3, 3) # 3. Cells G7 to D4.
# worksheet4.set_selection('D4') # Same as 1.
# worksheet5.set_selection('D4:G7') # Same as 2.
# worksheet6.set_selection('G7:D4') # Same as 3.
#
# The default cell selections is (0, 0), 'A1'.
#
def set_selection(*args)
# Check for a cell reference in A1 notation and substitute row and column
args = row_col_notation(args)
@selection = args
end
#
# :call-seq:
# outline_settings(visible, symbols_below, symbols_right, auto_style)
#
# This method sets the properties for outlining and grouping. The defaults
# correspond to Excel's defaults.
#
# The outline_settings() method is used to control the appearance of
# outlines in Excel. Outlines are described in
# "OUTLINES AND GROUPING IN EXCEL".
#
# The _visible_ parameter is used to control whether or not outlines are
# visible. Setting this parameter to false will cause all outlines on the
# worksheet to be hidden. They can be unhidden in Excel by means of the
# "Show Outline Symbols" command button. The default setting is true for
# visible outlines.
#
# worksheet.outline_settings(false)
#
# The _symbols__below parameter is used to control whether the row outline
# symbol will appear above or below the outline level bar. The default
# setting is 1 for symbols to appear below the outline level bar.
#
# The symbols_right parameter is used to control whether the column outline
# symbol will appear to the left or the right of the outline level bar. The
# default setting is 1 for symbols to appear to the right of the outline
# level bar.
#
# The _auto_style_ parameter is used to control whether the automatic outline
# generator in Excel uses automatic styles when creating an outline. This has
# no effect on a file generated by WriteExcel but it does have an effect on
# how the worksheet behaves after it is created. The default setting is 0 for
# "Automatic Styles" to be turned off.
#
# The default settings for all of these parameters correspond to Excel's
# default parameters.
#
# The worksheet parameters controlled by outline_settings() are rarely used.
#
def outline_settings(*args)
@outline.visible = args[0] || 1
@outline.below = args[1] || 1
@outline.right = args[2] || 1
@outline.style = args[3] || 0
# Ensure this is a boolean value for Window2
@outline.visible = true unless @outline.visible?
end
#
# :call-seq:
# freeze_pane(row, col, top_row, left_col)
#
# Set panes and mark them as frozen.
#--
# See also store_panes().
#++
#
# This method can be used to divide a worksheet into horizontal or vertical
# regions known as panes and to also "freeze" these panes so that the
# splitter bars are not visible. This is the same as the Window->Freeze Panes
# menu command in Excel
#
# The parameters _row_ and _col_ are used to specify the location of the split.
# It should be noted that the split is specified at the top or left of a
# cell and that the method uses zero based indexing. Therefore to freeze the
# first row of a worksheet it is necessary to specify the split at row 2
# (which is 1 as the zero-based index). This might lead you to think that
# you are using a 1 based index but this is not the case.
#
# You can set one of the _row_ and _col_ parameters as zero if you do not
# want either a vertical or horizontal split.
#
# Examples:
#
# worksheet.freeze_panes(1, 0) # Freeze the first row
# worksheet.freeze_panes('A2') # Same using A1 notation
# worksheet.freeze_panes(0, 1) # Freeze the first column
# worksheet.freeze_panes('B1') # Same using A1 notation
# worksheet.freeze_panes(1, 2) # Freeze first row and first 2 columns
# worksheet.freeze_panes('C2') # Same using A1 notation
#
# The parameters _top_row_ and _left_col_ are optional. They are used to
# specify the top-most or left-most visible row or column in the scrolling
# region of the panes. For example to freeze the first row and to have the
# scrolling region begin at row twenty:
#
# worksheet.freeze_panes(1, 0, 20, 0)
#
# You cannot use A1 notation for the _top_row_ and _left_col_ parameters.
#
# See also the panes.rb program in the examples directory of the distribution.
#
def freeze_panes(*args)
# Check for a cell reference in A1 notation and substitute row and column
args = row_col_notation(args)
# Extra flag indicated a split and freeze.
@frozen_no_split = 0 if args[4] && args[4] != 0
@frozen = true
@panes = args
end
#
# :call-seq:
# split_panes(y, x, top_row, left_col)
#
# Set panes and mark them as split.
#--
# See also store_panes().
#++
#
# This method can be used to divide a worksheet into horizontal or vertical
# regions known as panes. This method is different from the freeze_panes()
# method in that the splits between the panes will be visible to the user
# and each pane will have its own scroll bars.
#
# The parameters _y_ and _x_ are used to specify the vertical and horizontal
# position of the split. The units for _y_ and _x_ are the same as those
# used by Excel to specify row height and column width. However, the
# vertical and horizontal units are different from each other. Therefore you
# must specify the _y_ and _x_ parameters in terms of the row heights and
# column widths that you have set or the default values which are 12.75 for
# a row and 8.43 for a column.
#
# You can set one of the _y_ and _x_ parameters as zero if you do not want
# either a vertical or horizontal split. The parameters _top_row_ and
# _left_col_ are optional. They are used to specify the top-most or
# left-most visible row or column in the bottom-right pane.
#
# Example:
#
# worksheet.split_panes(12.75, 0, 1, 0) # First row
# worksheet.split_panes(0, 8.43, 0, 1) # First column
# worksheet.split_panes(12.75, 8.43, 1, 1) # First row and column
#
# You cannot use A1 notation with this method.
#
# See also the freeze_panes() method and the panes.pl program in the examples
# directory of the distribution.
#
# Note:
#
def split_panes(*args)
@frozen = false
@frozen_no_split = 0
@panes = args
end
# Older method name for backwards compatibility.
# *thaw_panes = *split_panes;
#
# :call-seq:
# merge_range(first_row, first_col, last_row, last_col, token, format, utf_16_be)
#
# This is a wrapper to ensure correct use of the merge_cells method, i.e.,
# write the first cell of the range, write the formatted blank cells in the
# range and then call the merge_cells record. Failing to do the steps in
# this order will cause Excel 97 to crash.
#
# Merging cells can be achieved by setting the merge property of a Format
# object, see "CELL FORMATTING". However, this only allows simple Excel5
# style horizontal merging which Excel refers to as "center across selection".
#
#
# The merge_range() method allows you to do Excel97+ style formatting where
# the cells can contain other types of alignment in addition to the merging:
#
# format = workbook.add_format(
# :border => 6,
# :valign => 'vcenter',
# :align => 'center'
# )
#
# worksheet.merge_range('B3:D4', 'Vertical and horizontal', format)
#
# <em>WARNING.</em> The format object that is used with a merge_range()
# method call is marked internally as being associated with a merged range.
# It is a fatal error to use a merged format in a non-merged cell. Instead
# you should use separate formats for merged and non-merged cells. This
# restriction will be removed in a future release.
#
# The _utf_16_be_ parameter is optional, see below.
#
# merge_range() writes its _token_ argument using the worksheet write()
# method. Therefore it will handle numbers, strings, formulas or urls as
# required.
#
# Setting the merge property of the format isn't required when you are using
# merge_range(). In fact using it will exclude the use of any other horizontal
# alignment option.
#
# Your can specify UTF-16BE worksheet names using an additional optional
# parameter:
#
# str = [0x263a].pack('n')
# worksheet.merge_range('B3:D4', str, format, 1) # Smiley
#
# The full possibilities of this method are shown in the merge3.rb to
# merge65.rb programs in the examples directory of the distribution.
#
def merge_range(*args)
# Check for a cell reference in A1 notation and substitute row and column
args = row_col_notation(args)
raise "Incorrect number of arguments" if args.size != 6 and args.size != 7
raise "Format argument is not a format object" unless args[5].respond_to?(:xf_index)
rwFirst = args[0]
colFirst = args[1]
rwLast = args[2]
colLast = args[3]
string = args[4]
format = args[5]
encoding = args[6] ? 1 : 0
merge_range_core(rwFirst, colFirst, rwLast, colLast, string, format, encoding) do |rwFirst, colFirst, string, format, encoding|
if encoding != 0
write_utf16be_string(rwFirst, colFirst, string, format)
else
write(rwFirst, colFirst, string, format)
end
end
end
#
# :call-seq:
# merge_range_with_date_time(first_row, first_col, last_row, last_col, token, format)
#
# Write to meged cells, a datetime string in ISO8601 "yyyy-mm-ddThh:mm:ss.ss" format as a
# number representing an Excel date. format is optional.
#
def merge_range_with_date_time(*args)
# Check for a cell reference in A1 notation and substitute row and column
args = row_col_notation(args)
raise "Incorrect number of arguments" if args.size != 6 and args.size != 7
raise "Format argument is not a format object" unless args[5].respond_to?(:xf_index)
rwFirst = args[0]
colFirst = args[1]
rwLast = args[2]
colLast = args[3]
string = args[4]
format = args[5]
encoding = nil
merge_range_core(rwFirst, colFirst, rwLast, colLast, string, format, encoding) do |rwFirst, colFirst, string, format, encoding|
write_date_time(rwFirst, colFirst, string, format)
end
end
#
# Set the worksheet zoom factor in the range 10 <= scale <= 400:
#
# worksheet1.set_zoom(50)
# worksheet2.set_zoom(75)
# worksheet3.set_zoom(300)
# worksheet4.set_zoom(400)
#
# The default zoom factor is 100. You cannot zoom to "Selection" because
# it is calculated by Excel at run-time.
#
# Note, set_zoom() does not affect the scale of the printed page. For that
# you should use set_print_scale().
#
def set_zoom(scale = 100)
# Confine the scale to Excel's range
if scale < 10 or scale > 400
# carp "Zoom factor scale outside range: 10 <= zoom <= 400";
scale = 100
end
@zoom = scale.to_i
end
#
# Display the worksheet right to left for some eastern versions of Excel.
#
# The right_to_left() method is used to change the default direction of the
# worksheet from left-to-right, with the A1 cell in the top left, to
# right-to-left, with the he A1 cell in the top right.
#
# worksheet.right_to_left
#
# This is useful when creating Arabic, Hebrew or other near or far eastern
# worksheets that use right-to-left as the default direction.
#
def right_to_left
@display_arabic = 1
end
#
# Hide cell zero values.
#
# The hide_zero() method is used to hide any zero values that appear in
# cells.
#
# worksheet.hide_zero
#
# In Excel this option is found under Tools->Options->View.
#
def hide_zero
@hide_zeros = true
end
#
# Set the colour of the worksheet colour.
#
# The set_tab_color() method is used to change the colour of the worksheet
# tab. This feature is only available in Excel 2002 and later. You can
# use one of the standard colour names provided by the Format object or a
# colour index. See "COLOURS IN EXCEL" and the set_custom_color() method.
#
# worksheet1.set_tab_color('red')
# worksheet2.set_tab_color(0x0C)
#
# See the tab_colors.rb program in the examples directory of the distro.
#
def set_tab_color(color)
color = Colors.new.get_color(color)
color = 0 if color == 0x7FFF # Default color.
@tab_color = color
end
#
# :call-seq:
# autofilter(first_row, first_col, last_row, last_col)
# autofilter("A1:G10")
#
# Set the autofilter area in the worksheet.
#
#
# This method allows an autofilter to be added to a worksheet. An
# autofilter is a way of adding drop down lists to the headers of a 2D range
# of worksheet data. This is turn allow users to filter the data based on
# simple criteria so that some data is highlighted and some is hidden.
#
# To add an autofilter to a worksheet:
#
# worksheet.autofilter(0, 0, 10, 3)
# worksheet.autofilter('A1:D11') # Same as above in A1 notation.
#
# Filter conditions can be applied using the filter_column() method.
#
# See the autofilter.rb program in the examples directory of the distro
# for a more detailed example.
#
def autofilter(*args)
# Check for a cell reference in A1 notation and substitute row and column
args = row_col_notation(args)
return if args.size != 4 # Require 4 parameters
row_min, col_min, row_max, col_max = args
# Reverse max and min values if necessary.
row_min, row_max = row_max, row_min if row_max < row_min
col_min, col_max = col_max, col_min if col_max < col_min
# Store the Autofilter information
@filter_area.row_min = row_min
@filter_area.row_max = row_max
@filter_area.col_min = col_min
@filter_area.col_max = col_max
end
#
# :call-seq:
# filter_column(column, expression)
#
# Set the column filter criteria.
#
# The filter_column method can be used to filter columns in a autofilter
# range based on simple conditions.
#
# NOTE:
# It isn't sufficient to just specify the filter condition. You must also
# hide any rows that don't match the filter condition. Rows are hidden using
# the set_row() visible parameter. WriteExcel cannot do this
# automatically since it isn't part of the file format. See the autofilter.rb
# program in the examples directory of the distro for an example.
#
# The conditions for the filter are specified using simple expressions:
#
# worksheet.filter_column('A', 'x > 2000')
# worksheet.filter_column('B', 'x > 2000 and x < 5000')
#
# The _column_ parameter can either be a zero indexed column number or a
# string column name.
#
# The following operators are available:
#
# Operator Synonyms
# == = eq =~
# != <> ne !=
# >
# <
# >=
# <=
#
# and &&
# or ||
#
# The operator synonyms are just syntactic sugar to make you more comfortable
# using the expressions. It is important to remember that the expressions will
# be interpreted by Excel and not by ruby.
#
# An expression can comprise a single statement or two statements separated by
# the and and or operators. For example:
#
# 'x < 2000'
# 'x > 2000'
# 'x == 2000'
# 'x > 2000 and x < 5000'
# 'x == 2000 or x == 5000'
#
# Filtering of blank or non-blank data can be achieved by using a value of
# Blanks or NonBlanks in the expression:
#
# 'x == Blanks'
# 'x == NonBlanks'
#
# Top 10 style filters can be specified using a expression like the
# following:
#
# Top|Bottom 1-500 Items|%
#
# For example:
#
# 'Top 10 Items'
# 'Bottom 5 Items'
# 'Top 25 %'
# 'Bottom 50 %'
#
# Excel also allows some simple string matching operations:
#
# 'x =~ b*' # begins with b
# 'x !~ b*' # doesn't begin with b
# 'x =~ *b' # ends with b
# 'x !~ *b' # doesn't end with b
# 'x =~ *b*' # contains b
# 'x !~ *b*' # doesn't contains b
#
# You can also use * to match any character or number and ? to match any
# single character or number. No other regular expression quantifier is
# supported by Excel's filters. Excel's regular expression characters can
# be escaped using ~.
#
# The placeholder variable x in the above examples can be replaced by any
# simple string. The actual placeholder name is ignored internally so the
# following are all equivalent:
#
# 'x < 2000'
# 'col < 2000'
# 'Price < 2000'
#
# Also, note that a filter condition can only be applied to a column in a
# range specified by the autofilter() Worksheet method.
#
# See the autofilter.rb program in the examples directory of the distro
# for a more detailed example.
#
def filter_column(col, expression)
raise "Must call autofilter() before filter_column()" if @filter_area.count == 0
# Check for a column reference in A1 notation and substitute.
# Convert col ref to a cell ref and then to a col number.
dummy, col = substitute_cellref("#{col}1") if col =~ /^\D/
# Reject column if it is outside filter range.
unless @filter_area.inside?(col)
raise "Column '#{col}' outside autofilter() column range " +
"(#{@filter_area.col_min} .. #{@filter_area.col_max})"
end
tokens = extract_filter_tokens(expression)
unless (tokens.size == 3 or tokens.size == 7)
raise "Incorrect number of tokens in expression '#{expression}'"
end
@filter_cols[col] = parse_filter_expression(expression, tokens)
@filter_on = 1
end
#
# Set the page orientation as portrait.
#
# This method is used to set the orientation of a worksheet's printed page
# to portrait. The default worksheet orientation is portrait, so you won't
# generally need to call this method.
#
def set_portrait
@orientation = 1
end
#
# Set the page orientation as landscape.
#
def set_landscape
@orientation = 0
end
#
# This method is used to display the worksheet in "Page View" mode. This
# is currently only supported by Mac Excel, where it is the default.
#
def set_page_view
@page_view = 1
end
#
# Set the paper type. Ex. 1 = US Letter, 9 = A4
#
# This method is used to set the paper format for the printed output of a
# worksheet. The following paper styles are available:
#
# Index Paper format Paper size
# ===== ============ ==========
# 0 Printer default -
# 1 Letter 8 1/2 x 11 in
# 2 Letter Small 8 1/2 x 11 in
# 3 Tabloid 11 x 17 in
# 4 Ledger 17 x 11 in
# 5 Legal 8 1/2 x 14 in
# 6 Statement 5 1/2 x 8 1/2 in
# 7 Executive 7 1/4 x 10 1/2 in
# 8 A3 297 x 420 mm
# 9 A4 210 x 297 mm
# 10 A4 Small 210 x 297 mm
# 11 A5 148 x 210 mm
# 12 B4 250 x 354 mm
# 13 B5 182 x 257 mm
# 14 Folio 8 1/2 x 13 in
# 15 Quarto 215 x 275 mm
# 16 - 10x14 in
# 17 - 11x17 in
# 18 Note 8 1/2 x 11 in
# 19 Envelope 9 3 7/8 x 8 7/8
# 20 Envelope 10 4 1/8 x 9 1/2
# 21 Envelope 11 4 1/2 x 10 3/8
# 22 Envelope 12 4 3/4 x 11
# 23 Envelope 14 5 x 11 1/2
# 24 C size sheet -
# 25 D size sheet -
# 26 E size sheet -
# 27 Envelope DL 110 x 220 mm
# 28 Envelope C3 324 x 458 mm
# 29 Envelope C4 229 x 324 mm
# 30 Envelope C5 162 x 229 mm
# 31 Envelope C6 114 x 162 mm
# 32 Envelope C65 114 x 229 mm
# 33 Envelope B4 250 x 353 mm
# 34 Envelope B5 176 x 250 mm
# 35 Envelope B6 176 x 125 mm
# 36 Envelope 110 x 230 mm
# 37 Monarch 3.875 x 7.5 in
# 38 Envelope 3 5/8 x 6 1/2 in
# 39 Fanfold 14 7/8 x 11 in
# 40 German Std Fanfold 8 1/2 x 12 in
# 41 German Legal Fanfold 8 1/2 x 13 in
#
# Note, it is likely that not all of these paper types will be available to
# the end user since it will depend on the paper formats that the user's
# printer supports. Therefore, it is best to stick to standard paper types.
#
# worksheet.set_paper(1) # US Letter
# worksheet.set_paper(9) # A4
#
# If you do not specify a paper type the worksheet will print using the
# printer's default paper.
#
def set_paper(paper_size = 0)
@paper_size = paper_size
end
#
# Center the worksheet data horizontally between the margins on the printed page.
#
def center_horizontally
@hcenter = 1
end
#
# Center the worksheet data vertically between the margins on the printed page:
#
def center_vertically
@vcenter = 1
end
#
# Set all the page margins to the same value in inches.
#
# There are several methods available for setting the worksheet margins on
# the printed page:
#
# set_margins() # Set all margins to the same value
# set_margins_LR() # Set left and right margins to the same value
# set_margins_TB() # Set top and bottom margins to the same value
# set_margin_left(); # Set left margin
# set_margin_right(); # Set right margin
# set_margin_top(); # Set top margin
# set_margin_bottom(); # Set bottom margin
#
# All of these methods take a distance in inches as a parameter.
#
# Note: 1 inch = 25.4mm. ;-) The default left and right margin is 0.75 inch.
# The default top and bottom margin is 1.00 inch.
#
def set_margins(margin)
set_margin_left(margin)
set_margin_right(margin)
set_margin_top(margin)
set_margin_bottom(margin)
end
#
# Set the left and right margins to the same value in inches.
#
def set_margins_LR(margin)
set_margin_left(margin)
set_margin_right(margin)
end
#
# Set the top and bottom margins to the same value in inches.
#
def set_margins_TB(margin)
set_margin_top(margin)
set_margin_bottom(margin)
end
#
# Set the left margin in inches.
#
def set_margin_left(margin = 0.75)
@margin_left = margin
end
#
# Set the right margin in inches.
#
def set_margin_right(margin = 0.75)
@margin_right = margin
end
#
# Set the top margin in inches.
#
def set_margin_top(margin = 1.00)
@margin_top = margin
end
#
# Set the bottom margin in inches.
#
def set_margin_bottom(margin = 1.00)
@margin_bottom = margin
end
#
# Set the page header caption and optional margin.
#
# Headers and footers are generated using a _string_ which is a combination
# of plain text and control characters. The _margin_ parameter is optional.
#
# The available control character are:
#
# Control Category Description
# ======= ======== ===========
# &L Justification Left
# &C Center
# &R Right
#
# &P Information Page number
# &N Total number of pages
# &D Date
# &T Time
# &F File name
# &A Worksheet name
# &Z Workbook path
#
# &fontsize Font Font size
# &"font,style" Font name and style
# &U Single underline
# &E Double underline
# &S Strikethrough
# &X Superscript
# &Y Subscript
#
# && Miscellaneous Literal ampersand &
#
# Text in headers and footers can be justified (aligned) to the left, center
# and right by prefixing the text with the control characters &L, &C and &R.
#
# For example (with ASCII art representation of the results):
#
# worksheet.set_header('&LHello')
#
# ---------------------------------------------------------------
# | |
# | Hello |
# | |
#
#
# worksheet.set_header('&CHello')
#
# ---------------------------------------------------------------
# | |
# | Hello |
# | |
#
#
# worksheet.set_header('&RHello')
#
# ---------------------------------------------------------------
# | |
# | Hello |
# | |
#
# For simple text, if you do not specify any justification the text will be
# centred. However, you must prefix the text with &C if you specify a font
# name or any other formatting:
#
# worksheet.set_header('Hello')
#
# ---------------------------------------------------------------
# | |
# | Hello |
# | |
#
# You can have text in each of the justification regions:
#
# worksheet.set_header('&LCiao&CBello&RCielo')
#
# ---------------------------------------------------------------
# | |
# | Ciao Bello Cielo |
# | |
#
# The information control characters act as variables that Excel will update
# as the workbook or worksheet changes. Times and dates are in the users
# default format:
#
# worksheet.set_header('&CPage &P of &N')
#
# ---------------------------------------------------------------
# | |
# | Page 1 of 6 |
# | |
#
#
# worksheet.set_header('&CUpdated at &T')
#
# ---------------------------------------------------------------
# | |
# | Updated at 12:30 PM |
# | |
#
# You can specify the font size of a section of the text by prefixing it
# with the control character &n where n is the font size:
#
# worksheet1.set_header('&C&30Hello Big' )
# worksheet2.set_header('&C&10Hello Small')
#
# You can specify the font of a section of the text by prefixing it with the
# control sequence &"font,style" where fontname is a font name such as
# "Courier New" or "Times New Roman" and style is one of the standard Windows
# font descriptions: "Regular", "Italic", "Bold" or "Bold Italic":
#
# worksheet1.set_header('&C&"Courier New,Italic"Hello')
# worksheet2.set_header('&C&"Courier New,Bold Italic"Hello')
# worksheet3.set_header('&C&"Times New Roman,Regular"Hello')
#
# It is possible to combine all of these features together to create
# sophisticated headers and footers. As an aid to setting up complicated
# headers and footers you can record a page set-up as a macro in Excel and
# look at the format strings that VBA produces. Remember however that VBA uses
# two double quotes "" to indicate a single double quote. For the last example
# above the equivalent VBA code looks like this:
#
# .LeftHeader = ""
# .CenterHeader = "&""Times New Roman,Regular""Hello"
# .RightHeader = ""
#
# To include a single literal ampersand & in a header or footer you should
# use a double ampersand &&:
#
# worksheet1.set_header('&CCuriouser && Curiouser - Attorneys at Law')
#
# As stated above the margin parameter is optional. As with the other margins
# the value should be in inches. The default header and footer margin is 0.50
# inch. The header and footer margin size can be set as follows:
#
# worksheet.set_header('&CHello', 0.75)
#
# The header and footer margins are independent of the top and bottom margins.
#
# Note, the header or footer string must be less than 255 characters. Strings
# longer than this will not be written and a warning will be generated.
#
# worksheet.set_header("&C\x{263a}")
#
# See, also the headers.rb program in the examples directory of the
# distribution.
#
def set_header(string = '', margin = 0.50, encoding = 0)
set_header_footer_common(:header, string, margin, encoding)
end
#
# Set the page footer caption and optional margin.
#
# The syntax of the set_footer() method is the same as set_header(), see
# there.
#
def set_footer(string = '', margin = 0.50, encoding = 0)
set_header_footer_common(:footer, string, margin, encoding)
end
#
# Set the rows to repeat at the top of each printed page.
#--
# See also the store_name_xxxx() methods in Workbook.rb.
#++
#
# Set the number of rows to repeat at the top of each printed page.
#
# For large Excel documents it is often desirable to have the first row or
# rows of the worksheet print out at the top of each page. This can be
# achieved by using the repeat_rows() method. The parameters _first_row_ and
# _last_row_ are zero based. The _last_row_ parameter is optional if you
# only wish to specify one row:
#
# worksheet1.repeat_rows(0) # Repeat the first row
# worksheet2.repeat_rows(0, 1) # Repeat the first two rows
#
def repeat_rows(first_row, last_row = nil)
@title_range.row_min = first_row
@title_range.row_max = last_row || first_row # Second row is optional
end
#
# :call-seq:
# repeat_columns(firstcol[, lastcol])
# repeat_columns(A1_notation)
#
# Set the columns to repeat at the left hand side of each printed page.
#--
# See also the store_names() methods in Workbook.pm.
#++
#
# For large Excel documents it is often desirable to have the first column
# or columns of the worksheet print out at the left hand side of each page.
# This can be achieved by using the repeat_columns() method. The parameters
# _firstcolumn_ and _lastcolumn_ are zero based. The _last_column_
# parameter is optional if you only wish to specify one column. You can also
# specify the columns using A1 column notation, see the note about
# "Cell notation".
#
# worksheet1.repeat_columns(0) # Repeat the first column
# worksheet2.repeat_columns(0, 1) # Repeat the first two columns
# worksheet3.repeat_columns('A:A') # Repeat the first column
# worksheet4.repeat_columns('A:B') # Repeat the first two columns
#
def repeat_columns(*args)
# Check for a cell reference in A1 notation and substitute row and column
if args[0] =~ /^\D/
row1, firstcol, row2, lastcol = substitute_cellref(*args)
else
firstcol, lastcol = args
end
@title_range.col_min = firstcol
@title_range.col_max = lastcol || firstcol # Second col is optional
end
#
# :call-seq:
# hide_gridlines(option = 1)
#
# Set the option to hide gridlines on the screen and the printed page.
#--
# There are two ways of doing this in the Excel BIFF format: The first is by
# setting the DspGrid field of the WINDOW2 record, this turns off the screen
# and subsequently the print gridline. The second method is to via the
# PRINTGRIDLINES and GRIDSET records, this turns off the printed gridlines
# only. The first method is probably sufficient for most cases. The second
# method is supported for backwards compatibility. Porters take note.
#++
#
# This method is used to hide the gridlines on the screen and printed page.
# Gridlines are the lines that divide the cells on a worksheet. Screen and
# printed gridlines are turned on by default in an Excel worksheet. If you
# have defined your own cell borders you may wish to hide the default
# gridlines.
#
# worksheet.hide_gridlines
#
# The following values of _option_ are valid:
#
# 0 : Don't hide gridlines
# 1 : Hide printed gridlines only
# 2 : Hide screen and printed gridlines
#
# If you don't supply an argument the default option is 1, i.e.
# only the printed gridlines are hidden.
#
def hide_gridlines(option = 1)
if option == 0
@print_gridlines = 1 # 1 = display, 0 = hide
@screen_gridlines = 1
elsif option == 1
@print_gridlines = 0
@screen_gridlines = 1
else
@print_gridlines = 0
@screen_gridlines = 0
end
end
#
# Set the option to print the row and column headers on the printed page.
# See also the store_print_headers() method.
#
# An Excel worksheet looks something like the following;
#
# ------------------------------------------
# | | A | B | C | D | ...
# ------------------------------------------
# | 1 | | | | | ...
# | 2 | | | | | ...
# | 3 | | | | | ...
# | 4 | | | | | ...
# |...| ... | ... | ... | ... | ...
#
# The headers are the letters and numbers at the top and the left of the
# worksheet. Since these headers serve mainly as a indication of position on
# the worksheet they generally do not appear on the printed page. If you wish
# to have them printed you can use the print_row_col_headers() method :
#
# worksheet.print_row_col_headers
#
# Do not confuse these headers with page headers as described in the
# set_header() section.
#
def print_row_col_headers(option = nil)
unless option
@print_headers = 1
else
@print_headers = option
end
end
#
# :call-seq:
# print_area(first_row, first_col, last_row, last_col)
# print_area(A1_notation)
#
# Set the area of each worksheet that will be printed.
#--
# See also the_store_names() methods in Workbook.rb.
#++
#
# This method is used to specify the area of the worksheet that will be
# printed. All four parameters must be specified. You can also use
# A1 notation, see the note about "Cell notation".
#
# worksheet1.print_area('A1:H20') # Cells A1 to H20
# worksheet2.print_area(0, 0, 19, 7) # The same
# worksheet2.print_area('A:H') # Columns A to H if rows have data
#
def print_area(*args)
# Check for a cell reference in A1 notation and substitute row and column
args = row_col_notation(args)
return if args.size != 4 # Require 4 parameters
@print_range.row_min, @print_range.col_min, @print_range.row_max, @print_range.col_max = args
end
#
# Set the order in which pages are printed.
#
# The print_across method is used to change the default print direction.
# This is referred to by Excel as the sheet "page order".
#
# worksheet.print_across
#
# The default page order is shown below for a worksheet that extends over 4
# pages. The order is called "down then across":
#
# [1] [3]
# [2] [4]
#
# However, by using the print_across method the print order will be changed
# to "across then down":
#
# [1] [2]
# [3] [4]
#
def print_across
@page_order = 1
end
#
# Store the vertical and horizontal number of pages that will define the
# maximum area printed.
#--
# See also store_setup() and store_wsbool() below.
#++
#
# The fit_to_pages() method is used to fit the printed area to a specific
# number of pages both vertically and horizontally. If the printed area
# exceeds the specified number of pages it will be scaled down to fit.
# This guarantees that the printed area will always appear on the
# specified number of pages even if the page size or margins change.
#
# worksheet1.fit_to_pages(1, 1) # Fit to 1x1 pages
# worksheet2.fit_to_pages(2, 1) # Fit to 2x1 pages
# worksheet3.fit_to_pages(1, 2) # Fit to 1x2 pages
#
# The print area can be defined using the print_area() method.
#
# A common requirement is to fit the printed output to n pages wide but
# have the height be as long as necessary. To achieve this set the _height_
# to zero or leave it blank:
#
# worksheet1.fit_to_pages(1, 0) # 1 page wide and as long as necessary
# worksheet2.fit_to_pages(1) # The same
#
# Note that although it is valid to use both fit_to_pages() and set_print
#_scale() on the same worksheet only one of these options can be active at
# a time. The last method call made will set the active option.
#
# Note that fit_to_pages() will override any manual page breaks that are
# defined in the worksheet.
#
def fit_to_pages(width = 0, height = 0)
@fit_page = 1
@fit_width = width
@fit_height = height
end
#
# Set the scale factor of the printed page. Scale factors in the range
# 10 <= _scale_ <= 400 are valid:
#
# worksheet1.set_print_scale(50)
# worksheet2.set_print_scale(75)
# worksheet3.set_print_scale(300)
# worksheet4.set_print_scale(400)
#
# The default scale factor is 100. Note, set_print_scale() does not affect
# the scale of the visible page in Excel. For that you should use set_zoom().
#
# Note also that although it is valid to use both fit_to_pages() and
# set_print_scale() on the same worksheet only one of these options can be
# active at a time. The last method call made will set the active option.
#
def set_print_scale(scale = 100)
# Confine the scale to Excel's range
if scale < 10 or scale > 400
# carp "Print scale scale outside range: 10 <= zoom <= 400";
scale = 100
end
# Turn off "fit to page" option
@fit_page = 0
@print_scale = scale.to_i
end
#
# Store the horizontal page breaks on a worksheet. _breaks_ is Fixnum or Array
# of Fixnum.
#
# Add horizontal page breaks to a worksheet. A page break causes all the
# data that follows it to be printed on the next page. Horizontal page breaks
# act between rows. To create a page break between rows 20 and 21 you must
# specify the break at row 21. However in zero index notation this is
# actually row 20. So you can pretend for a small while that you are using 1
# index notation:
#
# worksheet1.set_h_pagebreaks(20) # Break between row 20 and 21
#
# The set_h_pagebreaks() method will accept a array of page breaks and you
# can call it more than once:
#
# worksheet2.set_h_pagebreaks([ 20, 40, 60, 80, 100]) # Add breaks
# worksheet2.set_h_pagebreaks([120, 140, 160, 180, 200]) # Add some more
#
# Note: If you specify the "fit to page" option via the fit_to_pages()
# method it will override all manual page breaks.
#
# There is a silent limitation of about 1000 horizontal page breaks per
# worksheet in line with an Excel internal limitation.
#
def set_h_pagebreaks(breaks)
@hbreaks += breaks.respond_to?(:to_ary) ? breaks : [breaks]
end
#
# Store the vertical page breaks on a worksheet. _breaks_ is Fixnum or Array
# of Fixnum.
#
# Add vertical page breaks to a worksheet. A page break causes all the data
# that follows it to be printed on the next page. Vertical page breaks act
# between columns. To create a page break between columns 20 and 21 you must
# specify the break at column 21. However in zero index notation this is
# actually column 20. So you can pretend for a small while that you are using
# 1 index notation:
#
# worksheet1.set_v_pagebreaks(20) # Break between column 20 and 21
#
# The set_v_pagebreaks() method will accept a list of page breaks and you
# can call it more than once:
#
# worksheet2.set_v_pagebreaks([ 20, 40, 60, 80, 100]) # Add breaks
# worksheet2.set_v_pagebreaks([120, 140, 160, 180, 200]) # Add some more
#
# Note: If you specify the "fit to page" option via the fit_to_pages() method
# it will override all manual page breaks.
#
def set_v_pagebreaks(breaks)
@vbreaks += breaks.respond_to?(:to_ary) ? breaks : [breaks]
end
#
# Causes the write() method to treat integers with a leading zero as a string.
# This ensures that any leading zeros such, as in zip codes, are maintained.
#
# This method changes the default handling of integers with leading zeros
# when using the write() method.
#
# The write() method uses regular expressions to determine what type of data
# to write to an Excel worksheet. If the data looks like a number it writes
# a number using write_number(). One problem with this approach is that
# occasionally data looks like a number but you don't want it treated as
# a number.
#
# Zip codes and ID numbers, for example, often start with a leading zero.
# If you write this data as a number then the leading zero(s) will be
# stripped. This is the also the default behaviour when you enter data
# manually in Excel.
#
# To get around this you can use one of three options. Write a formatted
# number, write the number as a string or use the keep_leading_zeros()
# method to change the default behaviour of write():
#
# # Implicitly write a number, the leading zero is removed: 1209
# worksheet.write('A1', '01209')
#
# # Write a zero padded number using a format: 01209
# format1 = workbook.add_format(:num_format => '00000')
# worksheet.write('A2', '01209', format1)
#
# # Write explicitly as a string: 01209
# worksheet.write_string('A3', '01209')
#
# # Write implicitly as a string: 01209
# worksheet.keep_leading_zeros()
# worksheet.write('A4', '01209')
#
# The above code would generate a worksheet that looked like the following:
#
# -----------------------------------------------------------
# | | A | B | C | D | ...
# -----------------------------------------------------------
# | 1 | 1209 | | | | ...
# | 2 | 01209 | | | | ...
# | 3 | 01209 | | | | ...
# | 4 | 01209 | | | | ...
#
# The examples are on different sides of the cells due to the fact that Excel
# displays strings with a left justification and numbers with a right
# justification by default. You can change this by using a format to justify
# the data, see "CELL FORMATTING".
#
# It should be noted that if the user edits the data in examples A3 and A4
# the strings will revert back to numbers. Again this is Excel's default
# behaviour. To avoid this you can use the text format @:
#
# # Format as a string (01209)
# format2 = workbook.add_format(:num_format => '@')
# worksheet.write_string('A5', '01209', format2)
#
# The keep_leading_zeros() property is off by default. The keep
#_leading_zeros() method takes 0 or 1 as an argument. It defaults to 1 if
# an argument isn't specified:
#
# worksheet.keep_leading_zeros() # Set on
# worksheet.keep_leading_zeros(1) # Set on
# worksheet.keep_leading_zeros(0) # Set off
#
# See also the add_write_handler() method.
#
def keep_leading_zeros(val = true)
@leading_zeros = val
end
#
# Make any comments in the worksheet visible.
#
# This method is used to make all cell comments visible when a worksheet is
# opened.
#
# Individual comments can be made visible using the visible parameter of the
# write_comment method (see above):
#
# worksheet.write_comment('C3', 'Hello', :visible => 1)
#
# If all of the cell comments have been made visible you can hide individual
# comments as follows:
#
# worksheet.write_comment('C3', 'Hello', :visible => 0)
#
#
def show_comments(val = true)
@comments.visible = val ? true : false
end
#
# Set the start page number.
#
# The set_start_page() method is used to set the number of the starting page
# when the worksheet is printed out. The default value is 1.
#
# worksheet.set_start_page(2)
#
def set_start_page(start_page = 1)
@page_start = start_page
@custom_start = 1
end
#
# Set the topmost and leftmost visible row and column.
# TODO: Document this when tested fully for interaction with panes.
#
def set_first_row_column(row = 0, col = 0)
row = RowMax - 1 if row > RowMax - 1
col = ColMax - 1 if col > ColMax - 1
@first_row = row
@first_col = col
end
#--
#
# Allow the user to add their own matches and handlers to the write() method.
#
# This method is used to extend the WriteExcel write() method to handle user
# defined data.
#
# If you refer to the section on write() above you will see that it acts as an
# alias for several more specific write_* methods. However, it doesn't always
# act in exactly the way that you would like it to.
#
# One solution is to filter the input data yourself and call the appropriate
# write_* method. Another approach is to use the add_write_handler() method
# to add your own automated behaviour to write().
#
# The add_write_handler() method take two arguments, _re_, a regular
# expression to match incoming data and _code_ a callback function to handle
# the matched data:
#
# worksheet.add_write_handler(qr/^\d\d\d\d$/, \&my_write)
#
# (In the these examples the qr operator is used to quote the regular expression
# strings, see perlop for more details).
#
# The method is used as follows. say you wished to write 7 digit ID numbers as
# a string so that any leading zeros were preserved*, you could do something
# like the following:
#
# worksheet.add_write_handler(qr/^\d{7}$/, \&write_my_id)
#
# sub write_my_id {
# my $worksheet = shift;
# return $worksheet->write_string(@_);
# }
#
# * You could also use the keep_leading_zeros() method for this.
#
# Then if you call write() with an appropriate string it will be handled automatically:
#
# # Writes 0000000. It would normally be written as a number; 0.
# $worksheet->write('A1', '0000000');
#
# The callback function will receive a reference to the calling worksheet
# and all of the other arguments that were passed to write(). The callback
# will see an @_ argument list that looks like the following:
#
# $_[0] A ref to the calling worksheet. *
# $_[1] Zero based row number.
# $_[2] Zero based column number.
# $_[3] A number or string or token.
# $_[4] A format ref if any.
# $_[5] Any other arguments.
# ...
#
# * It is good style to shift this off the list so the @_ is the same
# as the argument list seen by write().
#
# Your callback should return() the return value of the write_* method that
# was called or undef to indicate that you rejected the match and want
# write() to continue as normal.
#
# So for example if you wished to apply the previous filter only to ID
# values that occur in the first column you could modify your callback
# function as follows:
#
# sub write_my_id {
# my $worksheet = shift;
# my $col = $_[1];
#
# if ($col == 0) {
# return $worksheet->write_string(@_);
# }
# else {
# # Reject the match and return control to write()
# return undef;
# }
# }
#
# Now, you will get different behaviour for the first column and other
# columns:
#
# $worksheet->write('A1', '0000000'); # Writes 0000000
# $worksheet->write('B1', '0000000'); # Writes 0
#
# You may add more than one handler in which case they will be called in the
# order that they were added.
#
# Note, the add_write_handler() method is particularly suited for handling
# dates.
#
# See the write_handler 1-4 programs in the examples directory for further
# examples.
#
#++
# def add_write_handler(regexp, code_ref)
# # return unless ref $_[1] eq 'CODE';
#
# @write_match.push([regexp, code_ref])
# end
#
# :call-seq:
# write(row, col, token, format)
# write(A1_notation, token, format)
#
# Parse token and call appropriate write method. row and column are zero
# indexed. format is optional.
#
# The write_url() methods have a flag to prevent recursion when writing a
# string that looks like a url.
#
# Returns: return value of called subroutine
#
#
# Excel makes a distinction between data types such as strings, numbers,
# blanks, formulas and hyperlinks. To simplify the process of writing
# data the write() method acts as a general alias for several more
# specific methods:
# write_string()
# write_number()
# write_blank()
# write_formula()
# write_url()
# write_row()
# write_col()
#
# The general rule is that if the data looks like a something then a
# something is written. Here are some examples in both row-column
# and A1 notation:
# # Same as:
# worksheet.write(0, 0, 'Hello' ) # write_string()
# worksheet.write(1, 0, 'One' ) # write_string()
# worksheet.write(2, 0, 2 ) # write_number()
# worksheet.write(3, 0, 3.00001 ) # write_number()
# worksheet.write(4, 0, "" ) # write_blank()
# worksheet.write(5, 0, '' ) # write_blank()
# worksheet.write(6, 0, nil ) # write_blank()
# worksheet.write(7, 0 ) # write_blank()
# worksheet.write(8, 0, 'http://www.ruby-lang.org/') # write_url()
# worksheet.write('A9', 'ftp://ftp.ruby-lang.org/' ) # write_url()
# worksheet.write('A10', 'internal:Sheet1!A1' ) # write_url()
# worksheet.write('A11', 'external:c:\foo.xls' ) # write_url()
# worksheet.write('A12', '=A3 + 3*A4' ) # write_formula()
# worksheet.write('A13', '=SIN(PI()/4)' ) # write_formula()
# worksheet.write('A14', ['name', 'company'] ) # write_row()
# worksheet.write('A15', [ ['name', 'company'] ] ) # write_col()
#
# And if the keep_leading_zeros property is set:
# $worksheet.write('A16, 2 ); # write_number()
# $worksheet.write('A17, 02 ); # write_string()
# $worksheet.write('A18, 00002 ); # write_string()
#
# The "looks like" rule is defined by regular expressions:
#
# * write_number() if _token_ is a number based on the following regex:
# token =~ /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/.
#
# * write_string() if keep_leading_zeros() is set and _token_ is an integer
# with leading zeros based on the following regex: token =~ /^0\d+$/.
#
# * write_blank() if _token_ is undef or a blank string: undef, "" or ''.
#
# * write_url() if _token_ is a http, https, ftp or mailto URL based on the
# following regexes: token =~ m|^[fh]tt?ps?://| or $token =~ m|^mailto:|.
#
# * write_url() if _token_ is an internal or external sheet reference based
# on the following regex: token =~ m[^(in|ex)ternal:].
#
# * write_formula() if the first character of _token_ is "=".
#
# * write_row() if _token_ is an array.
#
# * write_col() if _token+ is an array of array.
#
# * write_string() if none of the previous conditions apply.
#
# The format parameter is optional. It should be a valid Format object, see
# "CELL FORMATTING":
#
# format = workbook.add_format
# format.set_bold
# format.set_color('red')
# format.set_align('center')
#
# worksheet.write(4, 0, 'Hello', format) # Formatted string
#
# The write() method will ignore empty strings or undef tokens unless a
# format is also supplied. As such you needn't worry about special
# handling for empty or undef values in your data. See also the
# write_blank() method.
#
# One problem with the write() method is that occasionally data looks like a
# number but you don't want it treated as a number. For example, zip codes or
# ID numbers often start with a leading zero. If you write this data as a
# number then the leading zero(s) will be stripped. You can change this
# default behaviour by using the keep_leading_zeros() method. While this
# property is in place any integers with leading zeros will be treated as
# strings and the zeros will be preserved. See the keep_leading_zeros()
# section for a full discussion of this issue.
#
# You can also add your own data handlers to the write() method using
# add_write_handler().
#
# The write methods return:
#
# 0 for success.
# -1 for insufficient number of arguments.
# -2 for row or column out of bounds.
# -3 for string too long.
#
def write(*args)
# Check for a cell reference in A1 notation and substitute row and column
args = row_col_notation(args)
token = args[2]
# Handle undefs as blanks
token ||= ''
# First try user defined matches.
@write_match.each do |aref|
re = aref[0]
sub = aref[1]
if token =~ Regexp.new(re)
match = eval("#{sub} self, args")
return match if match
end
end
# Match an array ref.
if token.respond_to?(:to_ary)
write_row(*args)
elsif token.respond_to?(:coerce) # Numeric
write_number(*args)
# Match http, https or ftp URL
elsif token =~ %r|^[fh]tt?ps?://|
write_url(*args)
# Match mailto:
elsif token =~ %r|^mailto:|
write_url(*args)
# Match internal or external sheet link
elsif token =~ %r!^(?:in|ex)ternal:!
write_url(*args)
# Match formula
elsif token =~ /^=/
write_formula(*args)
# Match blank
elsif token == ''
args.delete_at(2) # remove the empty string from the parameter list
write_blank(*args)
else
write_string(*args)
end
end
#
# :call-seq:
# write_number(row, col, token[, format])
# write_number(A1_notation, token[, format])
#
# Write a double to the specified row and column (zero indexed).
# An integer can be written as a double. Excel will display an
# integer. $format is optional.
#
# Returns 0 : normal termination
# -1 : insufficient number of arguments
# -2 : row or column out of range
#
# Write an integer or a float to the cell specified by row and column
#
# worksheet.write_number(0, 0, 123456)
# worksheet.write_number('A2', 2.3451)
#
# See the note about "Cell notation". The format parameter is optional.
#
# In general it is sufficient to use the write() method.
#
def write_number(*args)
# Check for a cell reference in A1 notation and substitute row and column
args = row_col_notation(args)
return -1 if args.size < 3 # Check the number of args
record = 0x0203 # Record identifier
length = 0x000E # Number of bytes to follow
row = args[0] # Zero indexed row
col = args[1] # Zero indexed column
num = args[2]
xf = xf_record_index(row, col, args[3]) # The cell format
# Check that row and col are valid and store max and min values
return -2 if check_dimensions(row, col) != 0
header = [record, length].pack('vv')
data = [row, col, xf].pack('vvv')
xl_double = [num].pack("d")
xl_double.reverse! if @byte_order
# Store the data or write immediately depending on the compatibility mode.
store_with_compatibility(row, col, header + data + xl_double)
0
end
#
# :call-seq:
# write_string(row, col, token[, format])
# write_string(A1_notation, token[, format])
#
# Write a string to the specified row and column (zero indexed).
#
# The format parameter is optional.
#
# Returns 0 : normal termination
# -1 : insufficient number of arguments
# -2 : row or column out of range
# -3 : long string truncated to 255 chars
#
#
# worksheet.write_string(0, 0, 'Your text here')
# worksheet.write_string('A2', 'or here')
#
# The maximum string size is 32767 characters. However the maximum string
# segment that Excel can display in a cell is 1000. All 32767 characters can
# be displayed in the formula bar.
#
# The write() method will also handle strings in UTF-8 format.
# You can also write Unicode in UTF16 format via the
# write_utf16be_string() method.
#
# In general it is sufficient to use the write() method. However, you may
# sometimes wish to use the write_string() method to write data that looks
# like a number but that you don't want treated as a number. For example,
# zip codes or phone numbers:
#
# # Write as a plain string
# worksheet.write_string('A1', '01209')
#
# However, if the user edits this string Excel may convert it back to a
# number. To get around this you can use the Excel text format @:
#
# # Format as a string. Doesn't change to a number when edited
# format1 = workbook.add_format(:num_format => '@')
# worksheet.write_string('A2', '01209', format1)
#
def write_string(*args)
# Check for a cell reference in A1 notation and substitute row and column
args = row_col_notation(args)
return -1 if (args.size < 3) # Check the number of args
row, col, str, format = args
str = str.to_s
xf = xf_record_index(row, col, format) # The cell format
encoding = 0x0
str_error = 0
ruby_19 {str = convert_to_ascii_if_ascii(str) }
# Handle utf8 strings
if is_utf8?(str)
str_utf16le = utf8_to_16le(str)
return write_utf16le_string(row, col, str_utf16le, args[3])
end
# Check that row and col are valid and store max and min values
return -2 unless check_dimensions(row, col) == 0
# Limit the string to the max number of chars.
if str.bytesize > 32767
str = str[0, 32767]
str_error = -3
end
# Prepend the string with the type.
str_header = [str.length, encoding].pack('vC')
str = str_header + str
str_unique = update_workbook_str_table(str)
record = 0x00FD # Record identifier
length = 0x000A # Bytes to follow
header = [record, length].pack('vv')
data = [row, col, xf, str_unique].pack('vvvV')
# Store the data or write immediately depending on the compatibility mode.
store_with_compatibility(row, col, header + data)
str_error
end
#
# :call-seq:
# write_utf16be_string(row, col, string, format)
#
# Write a Unicode string to the specified row and column (zero indexed).
# $format is optional.
# Returns 0 : normal termination
# -1 : insufficient number of arguments
# -2 : row or column out of range
# -3 : long string truncated to 255 chars
#
def write_utf16be_string(*args)
# Check for a cell reference in A1 notation and substitute row and column
args = row_col_notation(args)
return -1 if args.size < 3 # Check the number of args
record = 0x00FD # Record identifier
length = 0x000A # Bytes to follow
row, col, str = args
xf = xf_record_index(row, col, args[3]) # The cell format
encoding = 0x1
str_error = 0
# Check that row and col are valid and store max and min values
return -2 unless check_dimensions(row, col) == 0
# Limit the utf16 string to the max number of chars (not bytes).
if str.bytesize > 32767* 2
str = str[0..32767*2]
str_error = -3
end
num_bytes = str.bytesize
num_chars = (num_bytes / 2).to_i
# Check for a valid 2-byte char string.
raise "Uneven number of bytes in Unicode string" unless num_bytes % 2 == 0
# Change from UTF16 big-endian to little endian
str = utf16be_to_16le(str)
# Add the encoding and length header to the string.
str_header = [num_chars, encoding].pack("vC")
str = str_header + str
str_unique = update_workbook_str_table(str)
header = [record, length].pack("vv")
data = [row, col, xf, str_unique].pack("vvvV")
# Store the data or write immediately depending on the compatibility mode.
store_with_compatibility(row, col, header + data)
str_error
end
#
# :call-seq:
# write_utf16le_string(row, col, string, format)
#
# Write a UTF-16LE string to the specified row and column (zero indexed).
# $format is optional.
# Returns 0 : normal termination
# -1 : insufficient number of arguments
# -2 : row or column out of range
# -3 : long string truncated to 255 chars
#
def write_utf16le_string(*args)
# Check for a cell reference in A1 notation and substitute row and column
args = row_col_notation(args)
return -1 if (args.size < 3) # Check the number of args
row, col, str, format = args
# Change from UTF16 big-endian to little endian
str = utf16be_to_16le(str)
write_utf16be_string(row, col, str, format)
end
#
# :call-seq:
# write_blank(row, col , format) -> Fixnum
# write_blank(A1_notation, format) -> Fixnum
#
# Write a blank cell to the specified row and column (zero indexed).
# A blank cell is used to specify formatting without adding a string
# or a number.
#
# A blank cell without a format serves no purpose. Therefore, we don't write
# a BLANK record unless a format is specified. This is mainly an optimisation
# for the write_row() and write_col() methods.
#
# Returns 0 : normal termination (including no format)
# -1 : insufficient number of arguments
# -2 : row or column out of range
#
#This method is used to add formatting to a cell which doesn't contain a
# string or number value.
#
# Excel differentiates between an "Empty" cell and a "Blank" cell. An
# "Empty" cell is a cell which doesn't contain data whilst a "Blank" cell
# is a cell which doesn't contain data but does contain formatting. Excel
# stores "Blank" cells but ignores "Empty" cells.
#
# As such, if you write an empty cell without formatting it is ignored:
#
# worksheet.write('A1', nil, format) # write_blank()
# worksheet.write('A2', nil ) # Ignored
#
# This seemingly uninteresting fact means that you can write arrays of data
# without special treatment for undef or empty string values.
#
# See the note about "Cell notation".
#
def write_blank(*args)
# Check for a cell reference in A1 notation and substitute row and column
args = row_col_notation(args)
# Check the number of args
return -1 if args.size < 2
# Don't write a blank cell unless it has a format
return 0 unless args[2]
row, col, format = args
# Check that row and col are valid and store max and min values
return -2 unless check_dimensions(row, col) == 0
xf = xf_record_index(row, col, format) # The cell format
record = 0x0201 # Record identifier
length = 0x0006 # Number of bytes to follow
header = [record, length].pack('vv')
data = [row, col, xf].pack('vvv')
# Store the data or write immediately depending on the compatibility mode.
store_with_compatibility(row, col, header + data)
0
end
#
# :call-seq:
# write_formula(row, col , formula[, format, value]) -> Fixnum
# write_formula(A1_notation, formula[, format, value]) -> Fixnum
#
# Write a formula to the specified row and column (zero indexed).
#
# format is optional.
# value is an optional result of the formula that can be supplied by the
# user.
#
# Returns 0 : normal termination
# -1 : insufficient number of arguments
# -2 : row or column out of range
#
# Write a formula or function to the cell specified by row and column:
#
# worksheet.write_formula(0, 0, '=$B$3 + B4' )
# worksheet.write_formula(1, 0, '=SIN(PI()/4)')
# worksheet.write_formula(2, 0, '=SUM(B1:B5)' )
# worksheet.write_formula('A4', '=IF(A3>1,"Yes", "No")' )
# worksheet.write_formula('A5', '=AVERAGE(1, 2, 3, 4)' )
# worksheet.write_formula('A6', '=DATEVALUE("1-Jan-2001")')
#
# See the note about "Cell notation". For more information about writing
# Excel formulas see "FORMULAS AND FUNCTIONS IN EXCEL"
#
# See also the section "Improving performance when working with formulas"
# and the store_formula() and repeat_formula() methods.
#
# If required, it is also possible to specify the calculated value of the
# formula. This is occasionally necessary when working with non-Excel
# applications that don't calculated the value of the formula. The
# calculated value is added at the end of the argument list:
#
# worksheet.write('A1', '=2+2', format, 4);
#
# However, this probably isn't something that will ever need to do. If you
# do use this feature then do so with care.
#
# =FORMULAS AND FUNCTIONS IN EXCEL
#
# ==Caveats
#
# The first thing to note is that there are still some outstanding issues
# with the implementation of formulas and functions:
#
# 1. Writing a formula is much slower than writing the equivalent string.
# 2. You cannot use array constants, i.e. {1;2;3}, in functions.
# 3. Unary minus isn't supported.
# 4. Whitespace is not preserved around operators.
# 5. Named ranges are not supported.
# 6. Array formulas are not supported.
#
# However, these constraints will be removed in future versions. They are
# here because of a trade-off between features and time. Also, it is possible
# to work around issue 1 using the store_formula() and repeat_formula()
# methods as described later in this section.
#
# ==Introduction
#
# The following is a brief introduction to formulas and functions in Excel
# and WriteExcel.
#
# A formula is a string that begins with an equals sign:
#
# '=A1+B1'
# '=AVERAGE(1, 2, 3)'
#
# The formula can contain numbers, strings, boolean values, cell references,
# cell ranges and functions. Named ranges are not supported. Formulas should
# be written as they appear in Excel, that is cells and functions must be
# in uppercase.
#
# Cells in Excel are referenced using the A1 notation system where the column
# is designated by a letter and the row by a number. Columns range from A to
# IV i.e. 0 to 255, rows range from 1 to 65536.
#
# The Excel $ notation in cell references is also supported. This allows you
# to specify whether a row or column is relative or absolute. This only has
# an effect if the cell is copied. The following examples show relative and
# absolute values.
#
# '=A1' # Column and row are relative
# '=$A1' # Column is absolute and row is relative
# '=A$1' # Column is relative and row is absolute
# '=$A$1' # Column and row are absolute
#
# Formulas can also refer to cells in other worksheets of the current
# workbook. For example:
#
# '=Sheet2!A1'
# '=Sheet2!A1:A5'
# '=Sheet2:Sheet3!A1'
# '=Sheet2:Sheet3!A1:A5'
# %q{='Test Data'!A1}
# %q{='Test Data1:Test Data2'!A1}
#
# The sheet reference and the cell reference are separated by ! the exclamation
# mark symbol. If worksheet names contain spaces, commas o parentheses then
# Excel requires that the name is enclosed in single quotes as shown in the
# last two examples above. In order to avoid using a lot of escape characters
# you can use the quote operator %q{} to protect the quotes. See perlop in
# the main Perl documentation. Only valid sheet names that have been added
# using the add_worksheet() method can be used in formulas. You cannot
# reference external workbooks.
#
# The following table lists the operators that are available in Excel's
# formulas. The majority of the operators are the same as Perl's,
# differences are indicated:
#
# Arithmetic operators:
# =====================
# Operator Meaning Example
# + Addition 1+2
# - Subtraction 2-1
# * Multiplication 2*3
# / Division 1/4
# ^ Exponentiation 2^3 # Equivalent to **
# - Unary minus -(1+2) # Not yet supported
# % Percent (Not modulus) 13% # Not supported, [1]
#
#
# Comparison operators:
# =====================
# Operator Meaning Example
# = Equal to A1 = B1 # Equivalent to ==
# <> Not equal to A1 <> B1 # Equivalent to !=
# > Greater than A1 > B1
# < Less than A1 < B1
# >= Greater than or equal to A1 >= B1
# <= Less than or equal to A1 <= B1
#
#
# String operator:
# ================
# Operator Meaning Example
# & Concatenation "Hello " & "World!" # [2]
#
#
# Reference operators:
# ====================
# Operator Meaning Example
# : Range operator A1:A4 # [3]
# , Union operator SUM(1, 2+2, B3) # [4]
#
#
# Notes:
# [1]: You can get a percentage with formatting and modulus with MOD().
# [2]: Equivalent to ("Hello " . "World!") in Perl.
# [3]: This range is equivalent to cells A1, A2, A3 and A4.
# [4]: The comma behaves like the list separator in Perl.
#
# The range and comma operators can have different symbols in non-English
# versions of Excel. These will be supported in a later version of
# WriteExcel. European users of Excel take note:
#
# worksheet.write('A1', '=SUM(1; 2; 3)') # Wrong!!
# worksheet.write('A1', '=SUM(1, 2, 3)') # Okay
#
# The following table lists all of the core functions supported by Excel 5
# and WriteExcel. Any additional functions that are available through the
# "Analysis ToolPak" or other add-ins are not supported. These functions
# have all been tested to verify that they work.
#
# ABS DB INDIRECT NORMINV SLN
# ACOS DCOUNT INFO NORMSDIST SLOPE
# ACOSH DCOUNTA INT NORMSINV SMALL
# ADDRESS DDB INTERCEPT NOT SQRT
# AND DEGREES IPMT NOW STANDARDIZE
# AREAS DEVSQ IRR NPER STDEV
# ASIN DGET ISBLANK NPV STDEVP
# ASINH DMAX ISERR ODD STEYX
# ATAN DMIN ISERROR OFFSET SUBSTITUTE
# ATAN2 DOLLAR ISLOGICAL OR SUBTOTAL
# ATANH DPRODUCT ISNA PEARSON SUM
# AVEDEV DSTDEV ISNONTEXT PERCENTILE SUMIF
# AVERAGE DSTDEVP ISNUMBER PERCENTRANK SUMPRODUCT
# BETADIST DSUM ISREF PERMUT SUMSQ
# BETAINV DVAR ISTEXT PI SUMX2MY2
# BINOMDIST DVARP KURT PMT SUMX2PY2
# CALL ERROR.TYPE LARGE POISSON SUMXMY2
# CEILING EVEN LEFT POWER SYD
# CELL EXACT LEN PPMT T
# CHAR EXP LINEST PROB TAN
# CHIDIST EXPONDIST LN PRODUCT TANH
# CHIINV FACT LOG PROPER TDIST
# CHITEST FALSE LOG10 PV TEXT
# CHOOSE FDIST LOGEST QUARTILE TIME
# CLEAN FIND LOGINV RADIANS TIMEVALUE
# CODE FINV LOGNORMDIST RAND TINV
# COLUMN FISHER LOOKUP RANK TODAY
# COLUMNS FISHERINV LOWER RATE TRANSPOSE
# COMBIN FIXED MATCH REGISTER.ID TREND
# CONCATENATE FLOOR MAX REPLACE TRIM
# CONFIDENCE FORECAST MDETERM REPT TRIMMEAN
# CORREL FREQUENCY MEDIAN RIGHT TRUE
# COS FTEST MID ROMAN TRUNC
# COSH FV MIN ROUND TTEST
# COUNT GAMMADIST MINUTE ROUNDDOWN TYPE
# COUNTA GAMMAINV MINVERSE ROUNDUP UPPER
# COUNTBLANK GAMMALN MIRR ROW VALUE
# COUNTIF GEOMEAN MMULT ROWS VAR
# COVAR GROWTH MOD RSQ VARP
# CRITBINOM HARMEAN MODE SEARCH VDB
# DATE HLOOKUP MONTH SECOND VLOOKUP
# DATEVALUE HOUR N SIGN WEEKDAY
# DAVERAGE HYPGEOMDIST NA SIN WEIBULL
# DAY IF NEGBINOMDIST SINH YEAR
# DAYS360 INDEX NORMDIST SKEW ZTEST
#
# --
# You can also modify the module to support function names in the following
# languages: German, French, Spanish, Portuguese, Dutch, Finnish, Italian
# and Swedish. See the function_locale.pl program in the examples
# directory of the distro.
# ++
#
# For a general introduction to Excel's formulas and an explanation of
# the syntax of the function refer to the Excel help files or the
# following: http://office.microsoft.com/en-us/assistance/CH062528031033.aspx
#
# If your formula doesn't work in WriteExcel try the following:
#
# 1. Verify that the formula works in Excel (or Gnumeric or OpenOffice.org).
# 2. Ensure that it isn't on the Caveats list shown above.
# 3. Ensure that cell references and formula names are in uppercase.
# 4. Ensure that you are using ':' as the range operator, A1:A4.
# 5. Ensure that you are using ',' as the union operator, SUM(1,2,3).
# 6. Ensure that the function is in the above table.
#
# If you go through steps 1-6 and you still have a problem, mail me.
#
# ==Improving performance when working with formulas
#
# Writing a large number of formulas with WriteExcel can be
# slow. This is due to the fact that each formula has to be parsed and
# with the current implementation this is computationally expensive.
#
# However, in a lot of cases the formulas that you write will be quite
# similar, for example:
#
# worksheet.write_formula('B1', '=A1 * 3 + 50', format)
# worksheet.write_formula('B2', '=A2 * 3 + 50', format)
# ...
# ...
# worksheet.write_formula('B99', '=A999 * 3 + 50', format)
# worksheet.write_formula('B1000', '=A1000 * 3 + 50', format)
#
# In this example the cell reference changes in iterations from A1 to A1000.
# The parser treats this variable as a token and arranges it according to
# predefined rules. However, since the parser is oblivious to the value of
# the token, it is essentially performing the same calculation 1000 times.
# This is inefficient.
#
# The way to avoid this inefficiency and thereby speed up the writing of
# formulas is to parse the formula once and then repeatedly substitute
# similar tokens.
#
# A formula can be parsed and stored via the store_formula() worksheet
# method. You can then use the repeat_formula() method to substitute
# _pattern_, _replace_ pairs in the stored formula:
#
# formula = worksheet.store_formula('=A1 * 3 + 50')
#
# (0...1000).each do |row|
# worksheet.repeat_formula(row, 1, formula, format, 'A1', 'A'.(row +1))
# end
#
# On an arbitrary test machine this method was 10 times faster than the
# brute force method shown above.
# --
# For more information about how WriteExcel parses and stores formulas see
# the WriteExcel::Formula man page.
#
# It should be noted however that the overall speed of direct formula
# parsing will be improved in a future version.
# ++
def write_formula(*args)
# Check for a cell reference in A1 notation and substitute row and column
args = row_col_notation(args)
return -1 if args.size < 3 # Check the number of args
row, col, formula, format, value = args
# Check that row and col are valid and store max and min values
return -2 unless check_dimensions(row, col) == 0
xf = xf_record_index(row, col, format) # The cell format
# Strip the = sign at the beginning of the formula string
formula = formula.sub(/^=/, '')
# Parse the formula using the parser in Formula.pm
# nakamura add: to get byte_stream, set second arg TRUE
# because ruby doesn't have Perl's "wantarray"
formula = parser.parse_formula(formula, true)
store_formula_common(row, col, xf, value, formula)
0
end
#
# :call-seq:
# store_formula(formula) # formula : text string of formula
#
# Pre-parse a formula. This is used in conjunction with repeat_formula()
# to repetitively rewrite a formula without re-parsing it.
#
# The store_formula() method is used in conjunction with repeat_formula()
# to speed up the generation of repeated formulas. See
# "Improving performance when working with formulas" in
# "FORMULAS AND FUNCTIONS IN EXCEL".
#
# The store_formula() method pre-parses a textual representation of a
# formula and stores it for use at a later stage by the repeat_formula()
# method.
#
# store_formula() carries the same speed penalty as write_formula(). However,
# in practice it will be used less frequently.
#
# The return value of this method is a scalar that can be thought of as a
# reference to a formula.
#
# sin = worksheet.store_formula('=SIN(A1)')
# cos = worksheet.store_formula('=COS(A1)')
#
# worksheet.repeat_formula('B1', sin, format, 'A1', 'A2')
# worksheet.repeat_formula('C1', cos, format, 'A1', 'A2')
#
# Although store_formula() is a worksheet method the return value can be used
# in any worksheet:
#
# now = worksheet.store_formula('=NOW()')
#
# worksheet1.repeat_formula('B1', now)
# worksheet2.repeat_formula('B1', now)
# worksheet3.repeat_formula('B1', now)
#
def store_formula(formula) #:nodoc:
# In order to raise formula errors from the point of view of the calling
# program we use an eval block and re-raise the error from here.
#
tokens = parser.parse_formula(formula.sub(/^=/, ''))
# if ($@) {
# $@ =~ s/\n$// # Strip the \n used in the Formula.pm die()
# croak $@ # Re-raise the error
# }
# Return the parsed tokens in an anonymous array
[*tokens]
end
#
# :call-seq:
# repeat_formula(row, col, formula, format, pat, rep, (pat2, rep2,, ...) -> Fixnum
# repeat_formula(A1_notation, formula, format, pat, rep, (pat2, rep2,, ...) -> Fixnum
#
# Write a formula to the specified row and column (zero indexed) by
# substituting _pattern_ _replacement_ pairs in the formula created via
# store_formula(). This allows the user to repetitively rewrite a formula
# without the significant overhead of parsing.
#
# Returns 0 : normal termination
# -1 : insufficient number of arguments
# -2 : row or column out of range
#
# The repeat_formula() method is used in conjunction with store_formula() to
# speed up the generation of repeated formulas. See
# "Improving performance when working with formulas" in
# "FORMULAS AND FUNCTIONS IN EXCEL".
#
# In many respects repeat_formula() behaves like write_formula() except that
# it is significantly faster.
#
# The repeat_formula() method creates a new formula based on the pre-parsed
# tokens returned by store_formula(). The new formula is generated by
# substituting _pattern_, _replace_ pairs in the stored formula:
#
# formula = worksheet.store_formula('=A1 * 3 + 50')
#
# (0...100).each do |row|
# worksheet.repeat_formula(row, 1, formula, format, 'A1', "A#{row + 1}")
# end
#
# It should be noted that repeat_formula() doesn't modify the tokens. In the
# above example the substitution is always made against the original token,
# A1, which doesn't change.
#
# As usual, you can use undef if you don't wish to specify a format:
#
# worksheet.repeat_formula('B2', formula, format, 'A1', 'A2')
# worksheet.repeat_formula('B3', formula, nil, 'A1', 'A3')
#
# The substitutions are made from left to right and you can use as many
# pattern, replace pairs as you need. However, each substitution is made
# only once:
#
# formula = worksheet.store_formula('=A1 + A1')
#
# # Gives '=B1 + A1'
# worksheet.repeat_formula('B1', formula, undef, 'A1', 'B1')
#
# # Gives '=B1 + B1'
# worksheet.repeat_formula('B2', formula, undef, 'A1', 'B1', 'A1', 'B1')
#
# Since the pattern is interpolated each time that it is used it is worth
# using the %q operator to quote the pattern. The qr operator is explained
# in the perlop man page.
#
# worksheet.repeat_formula('B1', formula, format, %q!A1!, 'A2')
#
# Care should be taken with the values that are substituted. The formula
# returned by repeat_formula() contains several other tokens in addition to
# those in the formula and these might also match the pattern that you are
# trying to replace. In particular you should avoid substituting a single
# 0, 1, 2 or 3.
#
# You should also be careful to avoid false matches. For example the following
# snippet is meant to change the stored formula in steps
# from =A1 + SIN(A1) to =A10 + SIN(A10).
#
# formula = worksheet.store_formula('=A1 + SIN(A1)')
#
# (1..10).each do |row|
# worksheet.repeat_formula(row -1, 1, formula, nil,
# 'A1', "A#{row}", #! Bad.
# 'A1', "A#{row}" #! Bad.
# )
# end
#
# However it contains a bug. In the last iteration of the loop when row is
# 10 the following substitutions will occur:
#
# sub('A1', 'A10') changes =A1 + SIN(A1) to =A10 + SIN(A1)
# sub('A1', 'A10') changes =A10 + SIN(A1) to =A100 + SIN(A1) # !!
#
# The solution in this case is to use a more explicit match such as /(?!A1\d+)A1/:
#
# worksheet.repeat_formula(row -1, 1, formula, nil,
# 'A1', 'A' . row,
# /(?!A1\d+)A1/, 'A' . row
# )
#
# See also the repeat.rb program in the examples directory of the distro.
#
def repeat_formula(*args) #:nodoc:
# Check for a cell reference in A1 notation and substitute row and column
args = row_col_notation(args)
return -1 if args.size < 2 # Check the number of args
row, col, formula, format, *pairs = args
# Check that row and col are valid and store max and min values
return -2 unless check_dimensions(row, col) == 0
# Enforce an even number of arguments in the pattern/replacement list
raise "Odd number of elements in pattern/replacement list" unless pairs.size % 2 == 0
# Check that formula is an array ref
raise "Not a valid formula" unless formula.respond_to?(:to_ary)
tokens = formula.join("\t").split("\t")
# Ensure that there are tokens to substitute
raise "No tokens in formula" if tokens.empty?
# As a temporary and undocumented measure we allow the user to specify the
# result of the formula by appending a result => value pair to the end
# of the arguments.
value = nil
if pairs[-2] == 'result'
value = pairs.pop
pairs.pop
end
while !pairs.empty?
pattern = pairs.shift
replace = pairs.shift
tokens.each do |token|
break if token.sub!(pattern, replace)
end
end
# Change the parameters in the formula cached by the Formula.pm object
formula = parser.parse_tokens(tokens)
raise "Unrecognised token in formula" unless formula
xf = xf_record_index(row, col, format) # The cell format
store_formula_common(row, col, xf, value, formula)
0
end
#
# :call-seq:
# write_row(row, col , array[, format])
# write_row(A1_notation, array[, format])
#
# Write a row of data starting from (row, col). Call write_col() if any of
# the elements of the array are in turn array. This allows the writing of
# 1D or 2D arrays of data in one go.
#
# Returns: the first encountered error value or zero for no errors
#
#
# The write_row() method can be used to write a 1D or 2D array of data in
# one go. This is useful for converting the results of a database query into
# an Excel worksheet. You must pass a reference to the array of data rather
# than the array itself. The write() method is then called for each element
# of the data. For example:
#
# array = ['awk', 'gawk', 'mawk']
#
# worksheet.write_row(0, 0, array_ref)
#
# # The above example is equivalent to:
# worksheet.write(0, 0, array[0])
# worksheet.write(0, 1, array[1])
# worksheet.write(0, 2, array[2])
#
# Note: For convenience the write() method behaves in the same way as
# write_row() if it is passed an array. Therefore the following two method
# calls are equivalent:
#
# worksheet.write_row('A1', array) # Write a row of data
# worksheet.write( 'A1', array) # Same thing
#
# As with all of the write methods the format parameter is optional. If a
# format is specified it is applied to all the elements of the data array.
#
# Array references within the data will be treated as columns. This allows you
# to write 2D arrays of data in one go. For example:
#
# eec = [
# ['maggie', 'milly', 'molly', 'may' ],
# [13, 14, 15, 16 ],
# ['shell', 'star', 'crab', 'stone']
# ]
#
# worksheet.write_row('A1', eec)
#
# Would produce a worksheet as follows:
#
# -----------------------------------------------------------
# | | A | B | C | D | E | ...
# -----------------------------------------------------------
# | 1 | maggie | 13 | shell | ... | ... | ...
# | 2 | milly | 14 | star | ... | ... | ...
# | 3 | molly | 15 | crab | ... | ... | ...
# | 4 | may | 16 | stone | ... | ... | ...
# | 5 | ... | ... | ... | ... | ... | ...
# | 6 | ... | ... | ... | ... | ... | ...
#
# To write the data in a row-column order refer to the write_col() method
# below.
#
# Any +nil+ values in the data will be ignored unless a format is applied
# to the data, in which case a formatted blank cell will be written. In
# either case the appropriate row or column value will still be
# incremented.
#
# The write_row() method returns the first error encountered when
# writing the elements of the data or zero if no errors were encountered.
# See the return values described for the write() method above.
#
# See also the write_arrays.rb program in the examples directory of the
# distro.
#
def write_row(*args)
# Check for a cell reference in A1 notation and substitute row and column
args = row_col_notation(args)
# Catch non array refs passed by user.
raise "Not an array ref in call to write_row() #{$!}" unless args[2].respond_to?(:to_ary)
row, col, tokens, options = args
error = false
if tokens
tokens.each do |token|
# Check for nested arrays
if token.respond_to?(:to_ary)
ret = write_col(row, col, token, options)
else
ret = write(row, col, token, options)
end
# Return only the first error encountered, if any.
error ||= ret
col += 1
end
end
error || 0
end
#
# :call-seq:
# write_column(row, col , array[, format])
# write_column(A1_notation, array[, format])
#
# Write a column of data starting from (row, col). Call write_row() if any of
# the elements of the array are in turn array. This allows the writing
# of 1D or 2D arrays of data in one go.
#
# Returns: the first encountered error value or zero for no errors
#
#
# The write_col() method can be used to write a 1D or 2D array of data in one
# go. This is useful for converting the results of a database query into an
# Excel worksheet. The write() method is then called for each element of the
# data. For example:
#
# array = ['awk', 'gawk', 'mawk']
#
# worksheet.write_col(0, 0, array)
#
# # The above example is equivalent to:
# worksheet.write(0, 0, array[0])
# worksheet.write(1, 0, array[1])
# worksheet.write(2, 0, array[2])
#
# As with all of the write methods the format parameter is optional. If a
# format is specified it is applied to all the elements of the data array.
#
# Array within the data will be treated as rows. This allows you to write
# 2D arrays of data in one go. For example:
#
# eec = [
# ['maggie', 'milly', 'molly', 'may' ],
# [13, 14, 15, 16 ],
# ['shell', 'star', 'crab', 'stone']
# ]
#
# worksheet.write_col('A1', eec)
#
# Would produce a worksheet as follows:
#
# -----------------------------------------------------------
# | | A | B | C | D | E | ...
# -----------------------------------------------------------
# | 1 | maggie | milly | molly | may | ... | ...
# | 2 | 13 | 14 | 15 | 16 | ... | ...
# | 3 | shell | star | crab | stone | ... | ...
# | 4 | ... | ... | ... | ... | ... | ...
# | 5 | ... | ... | ... | ... | ... | ...
# | 6 | ... | ... | ... | ... | ... | ...
#
# To write the data in a column-row order refer to the write_row() method
# above.
#
# Any +nil+ values in the data will be ignored unless a format is applied to
# the data, in which case a formatted blank cell will be written. In either
# case the appropriate row or column value will still be incremented.
#
# As noted above the write() method can be used as a synonym for write_row()
# and write_row() handles nested array as columns. Therefore, the following
# two method calls are equivalent although the more explicit call to
# write_col() would be preferable for maintainability:
#
# worksheet.write_col('A1', array) # Write a column of data
# worksheet.write( 'A1', [ array ]) # Same thing
#
# The write_col() method returns the first error encountered when writing
# the elements of the data or zero if no errors were encountered. See the
# return values described for the write() method above.
#
# See also the write_arrays.pl program in the examples directory of the distro.
#
def write_col(*args)
# Check for a cell reference in A1 notation and substitute row and column
args = row_col_notation(args)
# Catch non array refs passed by user.
raise "Not an array ref in call to write_row()" unless args[2].respond_to?(:to_ary)
row, col, tokens, options = args
error = false
if tokens
tokens.each do |token|
# write() will deal with any nested arrays
ret = write(row, col, token, options)
# Return only the first error encountered, if any.
error ||= ret
row += 1
end
end
error || 0
end
#
# :call-seq:
# write_date_time(row, col , date_string[, format])
# write_date_time(A1_notation, date_string[, format])
#
# Write a datetime string in ISO8601 "yyyy-mm-ddThh:mm:ss.ss" format as a
# number representing an Excel date. format is optional.
#
# Returns 0 : normal termination
# -1 : insufficient number of arguments
# -2 : row or column out of range
# -3 : Invalid date_time, written as string
#
# The write_date_time() method can be used to write a date or time to the
# cell specified by row and column:
#
# worksheet.write_date_time('A1', '2004-05-13T23:20', date_format)
#
# The date_string should be in the following format:
#
# yyyy-mm-ddThh:mm:ss.sss
#
# This conforms to an ISO8601 date but it should be noted that the full
# range of ISO8601 formats are not supported.
#
# The following variations on the date_string parameter are permitted:
#
# yyyy-mm-ddThh:mm:ss.sss # Standard format
# yyyy-mm-ddT # No time
# Thh:mm:ss.sss # No date
# yyyy-mm-ddThh:mm:ss.sssZ # Additional Z (but not time zones)
# yyyy-mm-ddThh:mm:ss # No fractional seconds
# yyyy-mm-ddThh:mm # No seconds
#
# Note that the T is required in all cases.
#
# A date should always have a format, otherwise it will appear as a number,
# see "DATES AND TIME IN EXCEL" and "CELL FORMATTING". Here is a typical
# example:
#
# date_format = workbook.add_format(:num_format => 'mm/dd/yy')
# worksheet.write_date_time('A1', '2004-05-13T23:20', date_format)
#
# Valid dates should be in the range 1900-01-01 to 9999-12-31, for the 1900
# epoch and 1904-01-01 to 9999-12-31, for the 1904 epoch. As with Excel,
# dates outside these ranges will be written as a string.
#
# See also the date_time.rb program in the examples directory of the distro.
#
def write_date_time(*args)
# Check for a cell reference in A1 notation and substitute row and column
args = row_col_notation(args)
return -1 if args.size < 3 # Check the number of args
row, col, str, format = args
# Check that row and col are valid and store max and min values
return -2 unless check_dimensions(row, col) == 0
date_time = convert_date_time(str, date_1904?)
if date_time
error = write_number(row, col, date_time, args[3])
else
# The date isn't valid so write it as a string.
write_string(row, col, str, format)
error = -3
end
error
end
#
# :call-seq:
# write_comment(row, col, comment[, optionhash(es)]) -> Fixnum
# write_comment(A1_notation, comment[, optionhash(es)]) -> Fixnum
#
# Write a comment to the specified row and column (zero indexed).
#
# Returns 0 : normal termination
# -1 : insufficient number of arguments
# -2 : row or column out of range
#
# The write_comment() method is used to add a comment to a cell. A cell
# comment is indicated in Excel by a small red triangle in the upper
# right-hand corner of the cell. Moving the cursor over the red triangle
# will reveal the comment.
#
# The following example shows how to add a comment to a cell:
#
# worksheet.write (2, 2, 'Hello')
# worksheet.write_comment(2, 2, 'This is a comment.')
#
# As usual you can replace the row and column parameters with an A1 cell
# reference. See the note about "Cell notation".
#
# worksheet.write ('C3', 'Hello')
# worksheet.write_comment('C3', 'This is a comment.')
#
# On systems with perl 5.8 and later the write_comment() method will also
# handle strings in UTF-8 format.
#
# worksheet.write_comment('C3', "\x{263a}") # Smiley
# worksheet.write_comment('C4', 'Comment ca va?')
#
# In addition to the basic 3 argument form of write_comment() you can pass in
# several optional key/value pairs to control the format of the comment.
# For example:
#
# worksheet.write_comment('C3', 'Hello', :visible => 1, :author => 'Ruby')
#
# Most of these options are quite specific and in general the default comment
# behaviour will be all that you need. However, should you need greater
# control over the format of the cell comment the following options are
# available:
#
# :encoding
# :author
# :author_encoding
# :visible
# :x_scale
# :width
# :y_scale
# :height
# :color
# :start_cell
# :start_row
# :start_col
# :x_offset
# :y_offset
#
# Option: :encoding
#
# This option is used to indicate that the comment string is encoded as
# UTF-16BE.
#
# comment = [0x263a].pack('n') # UTF-16BE Smiley symbol
#
# worksheet.write_comment('C3', comment, :encoding => 1)
#
# Option: :author
#
# This option is used to indicate who the author of the comment is. Excel
# displays the author of the comment in the status bar at the bottom of
# the worksheet. This is usually of interest in corporate environments
# where several people might review and provide comments to a workbook.
#
# worksheet.write_comment('C3', 'Atonement', :author => '<NAME>')
#
# Option: :author_encoding
#
# This option is used to indicate that the author string is encoded as UTF-16BE.
#
# Option: :visible
#
# This option is used to make a cell comment visible when the worksheet
# is opened. The default behaviour in Excel is that comments are initially
# hidden. However, it is also possible in Excel to make individual or all
# comments visible. In WriteExcel individual comments can be made visible
# as follows:
#
# worksheet.write_comment('C3', 'Hello', :visible => 1)
#
# It is possible to make all comments in a worksheet visible using the show
# comments() worksheet method (see below). Alternatively, if all of the cell
# comments have been made visible you can hide individual comments:
#
# worksheet.write_comment('C3', 'Hello', :visible => 0)
#
# Option: :x_scale
#
# This option is used to set the width of the cell comment box as a factor
# of the default width.
#
# worksheet.write_comment('C3', 'Hello', :x_scale => 2)
# worksheet.write_comment('C4', 'Hello', :x_scale => 4.2)
#
# Option: :width
#
# This option is used to set the width of the cell comment box
# explicitly in pixels.
#
# worksheet.write_comment('C3', 'Hello', :width => 200)
#
# Option: :y_scale
#
# This option is used to set the height of the cell comment box as a
# factor of the default height.
#
# worksheet.write_comment('C3', 'Hello', :y_scale => 2)
# worksheet.write_comment('C4', 'Hello', :y_scale => 4.2)
#
# Option: :height
#
# This option is used to set the height of the cell comment box
# explicitly in pixels.
#
# worksheet.write_comment('C3', 'Hello', :height => 200)
#
# Option: :color
#
# This option is used to set the background colour of cell comment box.
# You can use one of the named colours recognised by WriteExcel or a colour
# index. See "COLOURS IN EXCEL".
#
# worksheet.write_comment('C3', 'Hello', :color => 'green')
# worksheet.write_comment('C4', 'Hello', :color => 0x35) # Orange
#
# Option: :start_cell
#
# This option is used to set the cell in which the comment will appear.
# By default Excel displays comments one cell to the right and one cell
# above the cell to which the comment relates. However, you can change
# this behaviour if you wish. In the following example the comment which
# would appear by default in cell D2 is moved to E2.
#
# worksheet.write_comment('C3', 'Hello', :start_cell => 'E2')
#
# Option: :start_row
#
# This option is used to set the row in which the comment will appear.
# See the start_cell option above. The row is zero indexed.
#
# worksheet.write_comment('C3', 'Hello', :start_row => 0)
#
# Option: :start_col
#
# This option is used to set the column in which the comment will appear.
# See the start_cell option above. The column is zero indexed.
#
# worksheet.write_comment('C3', 'Hello', :start_col => 4)
#
# Option: :x_offset
#
# This option is used to change the x offset, in pixels, of a comment
# within a cell:
#
# worksheet.write_comment('C3', comment, :x_offset => 30)
#
# Option: :y_offset
#
# This option is used to change the y offset, in pixels, of a comment
# within a cell:
#
# worksheet.write_comment('C3', comment, :x_offset => 30)
#
# You can apply as many of these options as you require.
#
# ==Note about row height and comments.
#
# If you specify the height of a row that contains a comment then WriteExcel
# will adjust the height of the comment to maintain the default or user
# specified dimensions. However, the height of a row can also be adjusted
# automatically by Excel if the text wrap property is set or large fonts are
# used in the cell. This means that the height of the row is unknown to
# WriteExcel at run time and thus the comment box is stretched with the row.
# Use the set_row() method to specify the row height explicitly and avoid
# this problem.
#
def write_comment(*args)
# Check for a cell reference in A1 notation and substitute row and column
args = row_col_notation(args)
return -1 if args.size < 3 # Check the number of args
row, col, comment, params = args
# Check for pairs of optional arguments, i.e. an odd number of args.
# raise "Uneven number of additional arguments" if args.size % 2 == 0
# Check that row and col are valid and store max and min values
return -2 unless check_dimensions(row, col) == 0
if params && params[:start_cell]
params[:start_row], params[:start_col] = substitute_cellref(params[:start_cell])
end
# We have to avoid duplicate comments in cells or else Excel will complain.
@comments << Comment.new(self, *args)
end
#
# :call-seq:
# write_url(row, col , url[, label, , format]) -> int
# write_url(A1_notation, url[, label, , format]) -> int
#
# Write a hyperlink. This is comprised of two elements: the visible _label_ and
# the invisible link. The visible _label_ is the same as the link unless an
# alternative string is specified.
#
# The parameters _label_ and _format_ are optional.
#
# The _url_ can be to a http, ftp, mail, internal sheet, or external
# directory url.
#
# Returns 0 : normal termination
# -1 : insufficient number of arguments
# -2 : row or column out of range
# -3 : long string truncated to 255 chars
#
# Write a hyperlink to a URL in the cell specified by row and column. The
# hyperlink is comprised of two elements: the visible _label_ and the
# invisible link. The visible _label_ is the same as the link unless an
# alternative label is specified. The parameters _label_ and the _format_
# are optional.
#
# The _label_ is written using the write() method. Therefore it is possible
# to write strings, numbers or formulas as labels.
#
# There are four web style URI's supported: http://, https://, ftp:// and
# mailto::
#
# worksheet.write_url(0, 0, 'ftp://www.ruby.org/' )
# worksheet.write_url(1, 0, 'http://www.ruby.com/', 'Ruby home' )
# worksheet.write_url('A3', 'http://www.ruby.com/', format )
# worksheet.write_url('A4', 'http://www.ruby.com/', 'Perl', format)
# worksheet.write_url('A5', 'mailto:<EMAIL>' )
#
# There are two local URIs supported: internal: and external:. These are used
# for hyperlinks to internal worksheet references or external workbook and
# worksheet references:
#
# worksheet.write_url('A6', 'internal:Sheet2!A1' )
# worksheet.write_url('A7', 'internal:Sheet2!A1', format )
# worksheet.write_url('A8', 'internal:Sheet2!A1:B2' )
# worksheet.write_url('A9', q{internal:'Sales Data'!A1} )
# worksheet.write_url('A10', 'external:c:\temp\foo.xls' )
# worksheet.write_url('A11', 'external:c:\temp\foo.xls#Sheet2!A1' )
# worksheet.write_url('A12', 'external:..\..\..\foo.xls' )
# worksheet.write_url('A13', 'external:..\..\..\foo.xls#Sheet2!A1' )
# worksheet.write_url('A13', 'external:\\\\NETWORK\share\foo.xls' )
#
# All of the these URI types are recognised by the write() method, see above.
#
# Worksheet references are typically of the form Sheet1!A1. You can also refer
# to a worksheet range using the standard Excel notation: Sheet1!A1:B2.
#
# In external links the workbook and worksheet name must be separated by the
# # character: external:Workbook.xls#Sheet1!A1'.
#
# You can also link to a named range in the target worksheet. For example say
# you have a named range called my_name in the workbook c:\temp\foo.xls you
# could link to it as follows:
#
# worksheet.write_url('A14', 'external:c:\temp\foo.xls#my_name')
#
# Note, you cannot currently create named ranges with WriteExcel.
#
# Links to network files are also supported. MS/Novell Network files normally
# begin with two back slashes as follows \\NETWORK\etc. In order to generate
# this in a single or double quoted string you will have to escape the
# backslashes, '\\\\NETWORK\etc'.
#
# If you are using double quote strings then you should be careful to escape
# anything that looks like a metacharacter. Why can't I use "C:\temp\foo" in
# DOS paths?.
#
# Finally, you can avoid most of these quoting problems by using forward
# slashes. These are translated internally to backslashes:
#
# worksheet.write_url('A14', "external:c:/temp/foo.xls" )
# worksheet.write_url('A15', 'external://NETWORK/share/foo.xls' )
#
# See also, the note about "Cell notation".
#
def write_url(*args)
# Check for a cell reference in A1 notation and substitute row and column
args = row_col_notation(args)
# Check the number of args
return -1 if args.size < 3
# Add start row and col to arg list
write_url_range(args[0], args[1], *args)
end
#
# :call-seq:
# write_url_range(row1, col1, row2, col2, url[, string, , format]) -> Fixnum
# write_url_range('A1:D2', url[, string, , format]) -> Fixnum
#
# This is the more general form of write_url(). It allows a hyperlink to be
# written to a range of cells. This function also decides the type of hyperlink
# to be written. These are either, Web (http, ftp, mailto), Internal
# (Sheet1!A1) or external ('c:\temp\foo.xls#Sheet1!A1').
#
# See also write_url() above for a general description and return values.
#
# This method is essentially the same as the write_url() method described
# above. The main difference is that you can specify a link for a range of
# cells:
#
# worksheet.write_url(0, 0, 0, 3, 'ftp://www.ruby.org/' )
# worksheet.write_url(1, 0, 0, 3, 'http://www.ruby.com/', 'Ruby home')
# worksheet.write_url('A3:D3', 'internal:Sheet2!A1' )
# worksheet.write_url('A4:D4', 'external:c:\temp\foo.xls' )
#
# This method is generally only required when used in conjunction with merged
# cells. See the merge_range() method and the merge property of a Format
# object, "CELL FORMATTING".
#
# There is no way to force this behaviour through the write() method.
#
# The parameters _string_ and the $format are optional and their position is
# interchangeable. However, they are applied only to the first cell in the
# range.
#
# See also, the note about "Cell notation".
#
def write_url_range(*args)
# Check for a cell reference in A1 notation and substitute row and column
args = row_col_notation(args)
# Check the number of args
return -1 if args.size < 5
# Reverse the order of _string_ and _format_ if necessary. We work on a copy
# in order to protect the callers args.
#
args[5], args[6] = [ args[6], args[5] ] if args[5].respond_to?(:xf_index)
url = args[4]
# Check for internal/external sheet links or default to web link
return write_url_internal(*args) if url =~ /^internal:/
return write_url_external(*args) if url =~ /^external:/
write_url_web(*args)
end
#
# :call-seq:
# insert_chart(row, col, chart, x, y, scale_x, scale_y)
#
# Insert a chart into a worksheet. The $chart argument should be a Chart
# object or else it is assumed to be a filename of an external binary file.
# The latter is for backwards compatibility.
#
# This method can be used to insert a Chart object into a worksheet.
# The Chart must be created by the add_chart() Workbook method and it must
# have the embedded option set.
#
# chart = workbook.add_chart(:type => 'Chart::Line', :embedded => true )
#
# # Configure the chart.
# ...
#
# # Insert the chart into the a worksheet.
# worksheet.insert_chart('E2', chart)
#
# See add_chart() for details on how to create the Chart object and
# WriteExcel::Chart for details on how to configure it. See also the
# chart_*.pl programs in the examples directory of the distro.
#
# The _x_, _y_, _scale_x_ and _scale_y_ parameters are optional.
#
# The parameters _x_ and _y_ can be used to specify an offset from the top
# left hand corner of the cell specified by _row_ and _col_. The offset values
# are in pixels. See the insert_image method above for more information on sizes.
#
# worksheet1.insert_chart('E2', chart, 3, 3)
#
# The parameters _scale_x_ and _scale_y_ can be used to scale the inserted
# image horizontally and vertically:
#
# Scale the width by 120% and the height by 150%
# worksheet.insert_chart('E2', chart, 0, 0, 1.2, 1.5)
#
# The easiest way to calculate the required scaling is to create a test
# chart worksheet with WriteExcel. Then open the file, select the chart
# and drag the corner to get the required size. While holding down the
# mouse the scale of the resized chart is shown to the left of the formula
# bar.
#
# Note: you must call set_row() or set_column() before insert_chart()
# if you wish to change the default dimensions of any of the rows or columns
# that the chart occupies. The height of a row can also change if you use
# a font that is larger than the default. This in turn will affect the
# scaling of your chart. To avoid this you should explicitly set the height
# of the row using set_row() if it contains a font size that will change
# the row height.
#
def insert_chart(*args)
# Check for a cell reference in A1 notation and substitute row and column
args = row_col_notation(args)
chart = args[2]
if chart.respond_to?(:embedded)
print "Not a embedded style Chart object in insert_chart()" unless chart.embedded
else
# Assume an external bin filename.
print "Couldn't locate #{chart} in insert_chart()" unless FileTest.exist?(chart)
end
@charts << EmbeddedChart.new(self, *args)
end
#
# :call-seq:
# insert_image(row, col, filename, x, y, scale_x, scale_y)
# insert_image(A1_notation, filename, x, y, scale_x, scale_y)
#
# Insert an image into the worksheet.
#
# This method can be used to insert a image into a worksheet. The image can
# be in PNG, JPEG or BMP format. The _x_, _y_, _scale_x_ and _scale_y_
# parameters are optional.
#
# worksheet1.insert_image('A1', 'ruby.bmp')
# worksheet2.insert_image('A1', '../images/ruby.bmp')
# worksheet3.insert_image('A1', 'c:\images\ruby.bmp')
#
# The parameters _x_ and _y_ can be used to specify an offset from the top
# left hand corner of the cell specified by _row_ and _col_. The offset
# values are in pixels.
#
# worksheet1.insert_image('A1', 'ruby.bmp', 32, 10)
#
# The default width of a cell is 63 pixels. The default height of a cell is
# 17 pixels. The pixels offsets can be calculated using the following
# relationships:
#
# Wp = int(12We) if We < 1
# Wp = int(7We +5) if We >= 1
# Hp = int(4/3He)
#
# where:
# We is the cell width in Excels units
# Wp is width in pixels
# He is the cell height in Excels units
# Hp is height in pixels
#
# The offsets can be greater than the width or height of the underlying cell.
# This can be occasionally useful if you wish to align two or more images
# relative to the same cell.
#
# The parameters _scale_x_ and _scale_y_ can be used to scale the inserted
# image horizontally and vertically:
#
# # Scale the inserted image: width x 2.0, height x 0.8
# worksheet.insert_image('A1', 'ruby.bmp', 0, 0, 2, 0.8)
#
# See also the images.rb program in the examples directory of the distro.
#
# Note:
#
# you must call set_row() or set_column() before insert_image() if you wish
# to change the default dimensions of any of the rows or columns that the
# image occupies. The height of a row can also change if you use a font that
# is larger than the default. This in turn will affect the scaling of your
# image. To avoid this you should explicitly set the height of the row using
# set_row() if it contains a font size that will change the row height.
#
# BMP images must be 24 bit, true colour, bitmaps. In general it is best to
# avoid BMP images since they aren't compressed.
#
def insert_image(*args)
# Check for a cell reference in A1 notation and substitute row and column
args = row_col_notation(args)
# args = [row, col, filename, x_offset, y_offset, scale_x, scale_y]
image = Image.new(self, *args)
raise "Insufficient arguments in insert_image()" unless args.size >= 3
raise "Couldn't locate #{image.filename}: $!" unless test(?e, image.filename)
@images << image
end
# Older method name for backwards compatibility.
# *insert_bitmap = *insert_image;
#
# DATA VALIDATION
#
#
# :call-seq:
# data_validation(row, col, params)
# data_validation(first_row, first_col, last_row, last_col, params)
#
# This method handles the interface to Excel data validation.
# Somewhat ironically the this requires a lot of validation code since the
# interface is flexible and covers a several types of data validation.
#
# We allow data validation to be called on one cell or a range of cells. The
# hashref contains the validation parameters and must be the last param:
#
# Returns 0 : normal termination
# -1 : insufficient number of arguments
# -2 : row or column out of range
# -3 : incorrect parameter.
#
# The data_validation() method is used to construct an Excel data validation
# or to limit the user input to a dropdown list of values.
#
# worksheet.data_validation('B3',
# {
# :validate => 'integer',
# :criteria => '>',
# :value => 100,
# })
#
# worksheet.data_validation('B5:B9',
# {
# :validate => 'list',
# :value => ['open', 'high', 'close'],
# })
#
# This method contains a lot of parameters and is described in detail in a
# separate section "DATA VALIDATION IN EXCEL".
#
# See also the data_validate.rb program in the examples directory of the distro
#
# The data_validation() method is used to construct an Excel data validation.
#
# It can be applied to a single cell or a range of cells. You can pass 3
# parameters such as (_row_, _col_, {...}) or 5 parameters such as
# (_first_row_, _first_col_, _last_row_, _last_col_, {...}). You can also
# use A1 style notation. For example:
#
# worksheet.data_validation(0, 0, {...})
# worksheet.data_validation(0, 0, 4, 1, {...})
#
# # Which are the same as:
#
# $worksheet.data_validation('A1', {...})
# $worksheet.data_validation('A1:B5', {...})
#
# See also the note about "Cell notation" for more information.
#
# The last parameter in data_validation() must be a hash ref containing the
# parameters that describe the type and style of the data validation. The
# allowable parameters are:
#
# validate
# criteria
# value | minimum | source
# maximum
# ignore_blank
# dropdown
#
# input_title
# input_message
# show_input
#
# error_title
# error_message
# error_type
# show_error
#
# These parameters are explained in the following sections. Most of the
# parameters are optional, however, you will generally require the three main
# options validate, criteria and value.
#
# worksheet.data_validation('B3',
# {
# :validate => 'integer',
# :criteria => '>',
# :value => 100
# })
#
# The data_validation method returns:
#
# 0 for success.
# -1 for insufficient number of arguments.
# -2 for row or column out of bounds.
# -3 for incorrect parameter or value.
#
# ===validate
#
# This parameter is passed in a hash ref to data_validation().
#
# The validate parameter is used to set the type of data that you wish to
# validate. It is always required and it has no default value. Allowable
# values are:
#
# any
# integer
# decimal
# list
# date
# time
# length
# custom
#
# * any is used to specify that the type of data is unrestricted. This
# is the same as not applying a data validation. It is only provided for
# completeness and isn't used very often in the context of WriteExcel.
#
# * integer restricts the cell to integer values. Excel refers to this
# as 'whole number'.
#
# :validate => 'integer',
# :criteria => '>',
# :value => 100,
#
# * decimal restricts the cell to decimal values.
#
# :validate => 'decimal',
# :criteria => '>',
# :value => 38.6,
#
# * list restricts the cell to a set of user specified values. These
# can be passed in an array ref or as a cell range (named ranges aren't
# currently supported):
#
# :validate => 'list',
# :value => ['open', 'high', 'close'],
# # Or like this:
# :value => 'B1:B3',
#
# Excel requires that range references are only to cells on the
# same worksheet.
#
# * date restricts the cell to date values. Dates in Excel are expressed
# as integer values but you can also pass an ISO860 style string as used in
# write_date_time(). See also "DATES AND TIME IN EXCEL" for more information
# about working with Excel's dates.
#
# :validate => 'date',
# :criteria => '>',
# :value => 39653, # 24 July 2008
# # Or like this:
# :value => '2008-07-24T',
#
# * time restricts the cell to time values. Times in Excel are expressed
# as decimal values but you can also pass an ISO860 style string as used in
# write_date_time(). See also "DATES AND TIME IN EXCEL" for more information
# about working with Excel's times.
#
# :validate => 'time',
# :criteria => '>',
# :value => 0.5, # Noon
# # Or like this:
# :value => 'T12:00:00',
#
# * length restricts the cell data based on an integer string length.
# Excel refers to this as 'Text length'.
#
# :validate => 'length',
# :criteria => '>',
# :value => 10,
#
# * custom restricts the cell based on an external Excel formula that
# returns a TRUE/FALSE value.
#
# :validate => 'custom',
# :value => '=IF(A10>B10,TRUE,FALSE)',
#
# ===criteria
#
# This parameter is passed in a hash ref to data_validation().
#
# The criteria parameter is used to set the criteria by which the data in
# the cell is validated. It is almost always required except for the list and
# custom validate options. It has no default value. Allowable values are:
#
# 'between'
# 'not between'
# 'equal to' | '==' | '='
# 'not equal to' | '!=' | '<>'
# 'greater than' | '>'
# 'less than' | '<'
# 'greater than or equal to' | '>='
# 'less than or equal to' | '<='
#
# You can either use Excel's textual description strings, in the first
# column above, or the more common operator alternatives. The following
# are equivalent:
#
# :validate => 'integer',
# :criteria => 'greater than',
# :value => 100,
#
# :validate => 'integer',
# :criteria => '>',
# :value => 100,
#
# The list and custom validate options don't require a criteria. If you
# specify one it will be ignored.
#
# :validate => 'list',
# :value => ['open', 'high', 'close'],
#
# :validate => 'custom',
# :value => '=IF(A10>B10,TRUE,FALSE)',
#
# ===value | minimum | source
#
# This parameter is passed in a hash ref to data_validation().
#
# The value parameter is used to set the limiting value to which the criteria
# is applied. It is always required and it has no default value. You can also
# use the synonyms minimum or source to make the validation a little clearer
# and closer to Excel's description of the parameter:
#
# # Use 'value'
# :validate => 'integer',
# :criteria => '>',
# :value => 100,
#
# # Use 'minimum'
# :validate => 'integer',
# :criteria => 'between',
# :minimum => 1,
# :maximum => 100,
#
# # Use 'source'
# :validate => 'list',
# :source => 'B1:B3',
#
# ===maximum
#
# This parameter is passed in a hash ref to data_validation().
#
# The maximum parameter is used to set the upper limiting value when the
# criteria is either 'between' or 'not between':
#
# :validate => 'integer',
# :criteria => 'between',
# :minimum => 1,
# :maximum => 100,
#
# ===ignore_blank
#
# This parameter is passed in a hash ref to data_validation().
#
# The ignore_blank parameter is used to toggle on and off the
# 'Ignore blank' option in the Excel data validation dialog. When the option
# is on the data validation is not applied to blank data in the cell. It is
# on by default.
#
# :ignore_blank => 0, # Turn the option off
#
# ===dropdown
#
# This parameter is passed in a hash ref to data_validation().
#
# The dropdown parameter is used to toggle on and off the 'In-cell dropdown'
# option in the Excel data validation dialog. When the option is on a
# dropdown list will be shown for list validations. It is on by default.
#
# :dropdown => 0, # Turn the option off
#
# ===input_title
#
# This parameter is passed in a hash ref to data_validation().
#
# The input_title parameter is used to set the title of the input message
# that is displayed when a cell is entered. It has no default value and is
# only displayed if the input message is displayed. See the input_message
# parameter below.
#
# :input_title => 'This is the input title',
#
# The maximum title length is 32 characters. UTF8 strings are handled
# automatically.
#
# ===input_message
#
# This parameter is passed in a hash ref to data_validation().
#
# The input_message parameter is used to set the input message that is
# displayed when a cell is entered. It has no default value.
#
# :validate => 'integer',
# :criteria => 'between',
# :minimum => 1,
# :maximum => 100,
# :input_title => 'Enter the applied discount:',
# :input_message => 'between 1 and 100',
#
# The message can be split over several lines using newlines, "\n" in double
# quoted strings.
#
# :input_message => "This is\na test.",
#
# The maximum message length is 255 characters. UTF8 strings are handled
# automatically.
#
# ===show_input
#
# This parameter is passed in a hash ref to data_validation().
#
# The show_input parameter is used to toggle on and off the 'Show input
# message when cell is selected' option in the Excel data validation dialog.
# When the option is off an input message is not displayed even if it has
# been set using input_message. It is on by default.
#
# :show_input => 0, # Turn the option off
#
# ===error_title
#
# This parameter is passed in a hash ref to data_validation().
#
# The error_title parameter is used to set the title of the error message
# that is displayed when the data validation criteria is not met. The default
# error title is 'Microsoft Excel'.
#
# :error_title => 'Input value is not valid',
#
# The maximum title length is 32 characters. UTF8 strings are handled
# automatically.
#
# ===error_message
#
# This parameter is passed in a hash ref to data_validation().
#
# The error_message parameter is used to set the error message that is
# displayed when a cell is entered. The default error message is
# "The value you entered is not valid.\nA user has restricted values that can
# be entered into the cell.".
#
# :validate => 'integer',
# :criteria => 'between',
# :minimum => 1,
# :maximum => 100,
# :error_title => 'Input value is not valid',
# :error_message => 'It should be an integer between 1 and 100',
#
# The message can be split over several lines using newlines, "\n" in double
# quoted strings.
#
# :input_message => "This is\na test.",
#
# The maximum message length is 255 characters. UTF8 strings are handled
# automatically.
#
# ===error_type
#
# This parameter is passed in a hash ref to data_validation().
#
# The error_type parameter is used to specify the type of error dialog that
# is displayed. There are 3 options:
#
# 'stop'
# 'warning'
# 'information'
#
# The default is 'stop'.
#
# ===show_error
#
# This parameter is passed in a hash ref to data_validation().
#
# The show_error parameter is used to toggle on and off the 'Show error alert
# after invalid data is entered' option in the Excel data validation dialog.
# When the option is off an error message is not displayed even if it has been
# set using error_message. It is on by default.
#
# :show_error => 0, # Turn the option off
#
# ===Examples
#
# Example 1. Limiting input to an integer greater than a fixed value.
#
# worksheet.data_validation('A1',
# {
# :validate => 'integer',
# :criteria => '>',
# :value => 0,
# })
#
# Example 2. Limiting input to an integer greater than a fixed value where
# the value is referenced from a cell.
#
# worksheet.data_validation('A2',
# {
# :validate => 'integer',
# :criteria => '>',
# :value => '=E3',
# })
#
# Example 3. Limiting input to a decimal in a fixed range.
#
# worksheet.data_validation('A3',
# {
# :validate => 'decimal',
# :criteria => 'between',
# :minimum => 0.1,
# :maximum => 0.5,
# })
#
# Example 4. Limiting input to a value in a dropdown list.
#
# worksheet.data_validation('A4',
# {
# :validate => 'list',
# :source => ['open', 'high', 'close'],
# })
#
# Example 5. Limiting input to a value in a dropdown list where the list
# is specified as a cell range.
#
# worksheet.data_validation('A5',
# {
# :validate => 'list',
# :source => '=E4:G4',
# })
#
# Example 6. Limiting input to a date in a fixed range.
#
# worksheet.data_validation('A6',
# {
# :validate => 'date',
# :criteria => 'between',
# :minimum => '2008-01-01T',
# :maximum => '2008-12-12T',
# })
#
# Example 7. Displaying a message when the cell is selected.
#
# worksheet.data_validation('A7',
# {
# :validate => 'integer',
# :criteria => 'between',
# :minimum => 1,
# :maximum => 100,
# :input_title => 'Enter an integer:',
# :input_message => 'between 1 and 100',
# })
#
# See also the data_validate.rb program in the examples directory of the distro.
#
def data_validation(*args)
# Check for a cell reference in A1 notation and substitute row and column
args = row_col_notation(args)
# Make the last row/col the same as the first if not defined.
row1, col1, row2, col2 = args
return -2 if check_dimensions(row1, col1, 1, 1) != 0
return -2 if !row2.kind_of?(Hash) && check_dimensions(row2, col2, 1, 1) != 0
validation = DataValidation.factory(parser, date_1904?, *args)
return validation if (-3..-1).include?(validation)
# Store the validation information until we close the worksheet.
@validations << validation
end
def is_name_utf16be? # :nodoc:
if @name_utf16be == 0
false
elsif @name_utf16be == 1
true
else
!!@name_utf16be
end
end
def index # :nodoc:
@workbook.worksheets.index(self)
end
def type # :nodoc:
@type
end
def images_array # :nodoc:
@images.array
end
def offset # :nodoc:
@offset
end
def offset=(val) # :nodoc:
@offset = val
end
def selected? # :nodoc:
@selected
end
def selected=(val) # :nodoc:
@selected = val
end
def hidden? # :nodoc:
@hidden
end
def hidden=(val) # :nodoc:
@hidden = val
end
def num_images # :nodoc:
@num_images
end
def num_images=(val) # :nodoc:
@num_images = val
end
def image_mso_size # :nodoc:
@image_mso_size
end
def image_mso_size=(val) # :nodoc:
@image_mso_size = val
end
def images_size #:nodoc:
@images.array.size
end
def comments_size #:nodoc:
@comments.array.size
end
def charts_size #:nodoc:
@charts.array.size
end
def print_title_name_record_long #:nodoc:
@title_range.name_record_long(@workbook.ext_refs["#{index}:#{index}"])
end
def name_record_short(cell_range, hidden = nil)
cell_range.name_record_short(@workbook.ext_refs["#{index}:#{index}"], hidden)
end
def print_title_name_record_short(hidden = nil) #:nodoc:
name_record_short(@title_range, hidden)
end
def autofilter_name_record_short(hidden = nil) #:nodoc:
name_record_short(@filter_area, hidden) if @filter_area.count != 0
end
def print_area_name_record_short(hidden = nil) #:nodoc:
name_record_short(@print_range, hidden) if @print_range.row_min
end
#
# Calculate the vertices that define the position of a graphical object within
# the worksheet.
#
# +------------+------------+
# | A | B |
# +-----+------------+------------+
# | |(x1,y1) | |
# | 1 |(A1)._______|______ |
# | | | | |
# | | | | |
# +-----+----| BITMAP |-----+
# | | | | |
# | 2 | |______________. |
# | | | (B2)|
# | | | (x2,y2)|
# +---- +------------+------------+
#
# Example of a bitmap that covers some of the area from cell A1 to cell B2.
#
# Based on the width and height of the bitmap we need to calculate 8 vars:
# $col_start, $row_start, $col_end, $row_end, $x1, $y1, $x2, $y2.
# The width and height of the cells are also variable and have to be taken into
# account.
# The values of $col_start and $row_start are passed in from the calling
# function. The values of $col_end and $row_end are calculated by subtracting
# the width and height of the bitmap from the width and height of the
# underlying cells.
# The vertices are expressed as a percentage of the underlying cell width as
# follows (rhs values are in pixels):
#
# x1 = X / W *1024
# y1 = Y / H *256
# x2 = (X-1) / W *1024
# y2 = (Y-1) / H *256
#
# Where: X is distance from the left side of the underlying cell
# Y is distance from the top of the underlying cell
# W is the width of the cell
# H is the height of the cell
#
# Note: the SDK incorrectly states that the height should be expressed as a
# percentage of 1024.
#
def position_object(col_start, row_start, x1, y1, width, height) #:nodoc:
# col_start; # Col containing upper left corner of object
# x1; # Distance to left side of object
# row_start; # Row containing top left corner of object
# y1; # Distance to top of object
# col_end; # Col containing lower right corner of object
# x2; # Distance to right side of object
# row_end; # Row containing bottom right corner of object
# y2; # Distance to bottom of object
# width; # Width of image frame
# height; # Height of image frame
# Adjust start column for offsets that are greater than the col width
x1, col_start = adjust_col_position(x1, col_start)
# Adjust start row for offsets that are greater than the row height
y1, row_start = adjust_row_position(y1, row_start)
# Initialise end cell to the same as the start cell
col_end = col_start
row_end = row_start
width += x1
height += y1
# Subtract the underlying cell widths to find the end cell of the image
width, col_end = adjust_col_position(width, col_end)
# Subtract the underlying cell heights to find the end cell of the image
height, row_end = adjust_row_position(height, row_end)
# Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell
# with zero eight or width.
#
return if size_col(col_start) == 0
return if size_col(col_end) == 0
return if size_row(row_start) == 0
return if size_row(row_end) == 0
# Convert the pixel values to the percentage value expected by Excel
x1 = 1024.0 * x1 / size_col(col_start)
y1 = 256.0 * y1 / size_row(row_start)
x2 = 1024.0 * width / size_col(col_end)
y2 = 256.0 * height / size_row(row_end)
# Simulate ceil() without calling POSIX::ceil().
x1 = (x1 +0.5).to_i
y1 = (y1 +0.5).to_i
x2 = (x2 +0.5).to_i
y2 = (y2 +0.5).to_i
[
col_start, x1,
row_start, y1,
col_end, x2,
row_end, y2
]
end
def filter_count
@filter_area.count
end
def store_parent_mso_record(dg_length, spgr_length, spid) # :nodoc:
store_mso_dg_container(dg_length) +
store_mso_dg +
store_mso_spgr_container(spgr_length) +
store_mso_sp_container(40) +
store_mso_spgr() +
store_mso_sp(0x0, spid, 0x0005)
end
#
# Write the Escher SpContainer record that is part of MSODRAWING.
#
def store_mso_sp_container(length) #:nodoc:
type = 0xF004
version = 15
instance = 0
data = ''
add_mso_generic(type, version, instance, data, length)
end
#
# Write the Escher Sp record that is part of MSODRAWING.
#
def store_mso_sp(instance, spid, options) #:nodoc:
type = 0xF00A
version = 2
data = ''
length = 8
data = [spid, options].pack('VV')
add_mso_generic(type, version, instance, data, length)
end
#
# Write the Escher Opt record that is part of MSODRAWING.
#
def store_mso_opt_image(spid) #:nodoc:
type = 0xF00B
version = 3
instance = 3
data = ''
length = nil
data = [0x4104].pack('v') +
[spid].pack('V') +
[0x01BF].pack('v') +
[0x00010000].pack('V') +
[0x03BF].pack( 'v') +
[0x00080000].pack( 'V')
add_mso_generic(type, version, instance, data, length)
end
#
# Write the Escher ClientAnchor record that is part of MSODRAWING.
# flag
# col_start # Col containing upper left corner of object
# x1 # Distance to left side of object
#
# row_start # Row containing top left corner of object
# y1 # Distance to top of object
#
# col_end # Col containing lower right corner of object
# x2 # Distance to right side of object
#
# row_end # Row containing bottom right corner of object
# y2 # Distance to bottom of object
#
def store_mso_client_anchor(flag, col_start, x1, row_start, y1, col_end, x2, row_end, y2) #:nodoc:
type = 0xF010
version = 0
instance = 0
data = ''
length = 18
data = [flag, col_start, x1, row_start, y1, col_end, x2, row_end, y2].pack('v9')
add_mso_generic(type, version, instance, data, length)
end
#
# Write the Escher ClientData record that is part of MSODRAWING.
#
def store_mso_client_data #:nodoc:
type = 0xF011
version = 0
instance = 0
data = ''
length = 0
add_mso_generic(type, version, instance, data, length)
end
def comments_visible?
@comments.visible?
end
#
# Excel BIFF BOUNDSHEET record.
#
# sheetname # Worksheet name
# offset # Location of worksheet BOF
# type # Worksheet type
# hidden # Worksheet hidden flag
# encoding # Sheet name encoding
#
def boundsheet #:nodoc:
hidden = self.hidden? ? 1 : 0
encoding = self.is_name_utf16be? ? 1 : 0
record = 0x0085 # Record identifier
length = 0x08 + @name.bytesize # Number of bytes to follow
cch = @name.bytesize # Length of sheet name
# Character length is num of chars not num of bytes
cch /= 2 if is_name_utf16be?
# Change the UTF-16 name from BE to LE
sheetname = is_name_utf16be? ? @name.unpack('v*').pack('n*') : @name
grbit = @type | hidden
header = [record, length].pack("vv")
data = [@offset, grbit, cch, encoding].pack("VvCC")
header + data + sheetname
end
def num_shapes
1 + num_images + comments_size + charts_size + filter_count
end
def push_object_ids(mso_size, drawings_saved, max_spid, start_spid, clusters)
mso_size += image_mso_size
# Add a drawing object for each sheet with comments.
drawings_saved += 1
# For each sheet start the spids at the next 1024 interval.
max_spid = 1024 * (1 + Integer((max_spid -1)/1024.0))
start_spid = max_spid
# Max spid for each sheet and eventually for the workbook.
max_spid += num_shapes
# Store the cluster ids
mso_size += 8 * (num_shapes / 1024 + 1)
push_cluster(num_shapes, drawings_saved, clusters)
# Pass calculated values back to the worksheet
@object_ids = ObjectIds.new(start_spid, drawings_saved, num_shapes, max_spid -1)
[mso_size, drawings_saved, max_spid, start_spid]
end
def push_cluster(num_shapes, drawings_saved, clusters)
i = num_shapes
while i > 0
size = i > 1024 ? 1024 : i
clusters << [drawings_saved, size]
i -= 1024
end
end
###############################################################################
#
# Internal methods
#
private
def update_workbook_str_table(str)
@workbook.update_str_table(str)
end
def active?
self == @workbook.worksheets.activesheet
end
def frozen?
@frozen
end
def display_zeros?
!@hide_zeros
end
def set_header_footer_common(type, string, margin, encoding) # :nodoc:
ruby_19 { string = convert_to_ascii_if_ascii(string) }
limit = encoding != 0 ? 255 *2 : 255
# Handle utf8 strings
if is_utf8?(string)
string = utf8_to_16be(string)
encoding = 1
end
if string.bytesize >= limit
# carp 'Header string must be less than 255 characters';
return
end
if type == :header
@header = string
@margin_header = margin
@header_encoding = encoding
else
@footer = string
@margin_footer = margin
@footer_encoding = encoding
end
end
def merge_range_core(rwFirst, colFirst, rwLast, colLast, string, format, encoding)
# Temp code to prevent merged formats in non-merged cells.
error = "Error: refer to merge_range() in the documentation. " +
"Can't use previously non-merged format in merged cells"
raise error if format.used_merge == -1
format.used_merge = 0 # Until the end of this function.
# Set the merge_range property of the format object. For BIFF8+.
format.set_merge_range
# Excel doesn't allow a single cell to be merged
raise "Can't merge single cell" if rwFirst == rwLast and
colFirst == colLast
# Swap last row/col with first row/col as necessary
rwFirst, rwLast = rwLast, rwFirst if rwFirst > rwLast
colFirst, colLast = colLast, colFirst if colFirst > colLast
# Write the first cell
yield(rwFirst, colFirst, string, format, encoding)
# Pad out the rest of the area with formatted blank cells.
(rwFirst .. rwLast).each do |row|
(colFirst .. colLast).each do |col|
next if row == rwFirst and col == colFirst
write_blank(row, col, format)
end
end
merge_cells(rwFirst, colFirst, rwLast, colLast)
# Temp code to prevent merged formats in non-merged cells.
format.used_merge = 1
end
#
# Extract the tokens from the filter expression. The tokens are mainly non-
# whitespace groups. The only tricky part is to extract string tokens that
# contain whitespace and/or quoted double quotes (Excel's escaped quotes).
#
# Examples: 'x < 2000'
# 'x > 2000 and x < 5000'
# 'x = "foo"'
# 'x = "foo bar"'
# 'x = "foo "" bar"'
#
def extract_filter_tokens(expression = nil) #:nodoc:
return [] unless expression
tokens = []
str = expression
while str =~ /"(?:[^"]|"")*"|\S+/
tokens << $&
str = $~.post_match
end
# Remove leading and trailing quotes and unescape other quotes
tokens.map! do |token|
token.sub!(/^"/, '')
token.sub!(/"$/, '')
token.gsub!(/""/, '"')
# if token is number, convert to numeric.
if token =~ /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/
token.to_f == token.to_i ? token.to_i : token.to_f
else
token
end
end
tokens
end
#
# Converts the tokens of a possibly conditional expression into 1 or 2
# sub expressions for further parsing.
#
# Examples:
# ('x', '==', 2000) -> exp1
# ('x', '>', 2000, 'and', 'x', '<', 5000) -> exp1 and exp2
#
def parse_filter_expression(expression, tokens) #:nodoc:
# The number of tokens will be either 3 (for 1 expression)
# or 7 (for 2 expressions).
#
if (tokens.size == 7)
conditional = tokens[3]
if conditional =~ /^(and|&&)$/
conditional = 0
elsif conditional =~ /^(or|\|\|)$/
conditional = 1
else
raise "Token '#{conditional}' is not a valid conditional " +
"in filter expression '#{expression}'"
end
expression_1 = parse_filter_tokens(expression, tokens[0..2])
expression_2 = parse_filter_tokens(expression, tokens[4..6])
[expression_1, conditional, expression_2].flatten
else
parse_filter_tokens(expression, tokens)
end
end
#
# Parse the 3 tokens of a filter expression and return the operator and token.
#
def parse_filter_tokens(expression, tokens) #:nodoc:
operators = {
'==' => 2,
'=' => 2,
'=~' => 2,
'eq' => 2,
'!=' => 5,
'!~' => 5,
'ne' => 5,
'<>' => 5,
'<' => 1,
'<=' => 3,
'>' => 4,
'>=' => 6,
}
operator = operators[tokens[1]]
token = tokens[2]
# Special handling of "Top" filter expressions.
if tokens[0] =~ /^top|bottom$/i
value = tokens[1]
if (value =~ /\D/ or value.to_i < 1 or value.to_i > 500)
raise "The value '#{value}' in expression '#{expression}' " +
"must be in the range 1 to 500"
end
token.downcase!
if (token != 'items' and token != '%')
raise "The type '#{token}' in expression '#{expression}' " +
"must be either 'items' or '%'"
end
if (tokens[0] =~ /^top$/i)
operator = 30
else
operator = 32
end
if (tokens[2] == '%')
operator += 1
end
token = value
end
if (not operator and tokens[0])
raise "Token '#{tokens[1]}' is not a valid operator " +
"in filter expression '#{expression}'"
end
# Special handling for Blanks/NonBlanks.
if (token =~ /^blanks|nonblanks$/i)
# Only allow Equals or NotEqual in this context.
if (operator != 2 and operator != 5)
raise "The operator '#{tokens[1]}' in expression '#{expression}' " +
"is not valid in relation to Blanks/NonBlanks'"
end
token.downcase!
# The operator should always be 2 (=) to flag a "simple" equality in
# the binary record. Therefore we convert <> to =.
if (token == 'blanks')
if (operator == 5)
operator = 2
token = 'nonblanks'
end
else
if (operator == 5)
operator = 2
token = 'blanks'
end
end
end
# if the string token contains an Excel match character then change the
# operator type to indicate a non "simple" equality.
if (operator == 2 and token =~ /[*?]/)
operator = 22
end
[operator, token]
end
def store_with_compatibility(row, col, data) # :nodoc:
if compatibility?
store_to_table(row, col, data)
else
append(data)
end
end
def store_to_table(row, col, data) # :nodoc:
if @table[row]
@table[row][col] = data
else
tmp = []
tmp[col] = data
@table[row] = tmp
end
end
def compatibility?
compatibility = @workbook.compatibility
if compatibility == 0 || !compatibility
false
else
true
end
end
#
# Returns an index to the XF record in the workbook.
#
# Note: this is a function, not a method.
#
def xf_record_index(row, col, xf=nil) #:nodoc:
if xf.respond_to?(:xf_index)
xf.xf_index
elsif @row_formats.has_key?(row)
@row_formats[row].xf_index
elsif @col_formats.has_key?(col)
@col_formats[col].xf_index
else
0x0F
end
end
#
# Substitute an Excel cell reference in A1 notation for zero based row and
# column values in an argument list.
#
# Ex: ("A4", "Hello") is converted to (3, 0, "Hello").
#
def substitute_cellref(cell, *args) #:nodoc:
return [cell, *args] if cell.respond_to?(:coerce) # Numeric
cell.upcase!
# Convert a column range: 'A:A' or 'B:G'.
# A range such as A:A is equivalent to A1:65536, so add rows as required
if cell =~ /\$?([A-I]?[A-Z]):\$?([A-I]?[A-Z])/
row1, col1 = cell_to_rowcol($1 +'1')
row2, col2 = cell_to_rowcol($2 +'65536')
return [row1, col1, row2, col2, *args]
end
# Convert a cell range: 'A1:B7'
if cell =~ /\$?([A-I]?[A-Z]\$?\d+):\$?([A-I]?[A-Z]\$?\d+)/
row1, col1 = cell_to_rowcol($1)
row2, col2 = cell_to_rowcol($2)
return [row1, col1, row2, col2, *args]
end
# Convert a cell reference: 'A1' or 'AD2000'
if (cell =~ /\$?([A-I]?[A-Z]\$?\d+)/)
row1, col1 = cell_to_rowcol($1)
return [row1, col1, *args]
end
raise("Unknown cell reference #{cell}")
end
#
# Convert an Excel cell reference in A1 notation to a zero based row and column
# reference; converts C1 to (0, 2).
#
# Returns: row, column
#
def cell_to_rowcol(cell) #:nodoc:
cell =~ /\$?([A-I]?[A-Z])\$?(\d+)/
col = $1
row = $2.to_i
col = chars_to_col($1.split(//))
# Convert 1-index to zero-index
row -= 1
col -= 1
[row, col]
end
#
# This is an internal method that is used to filter elements of the array of
# pagebreaks used in the store_hbreak() and store_vbreak() methods. It:
# 1. Removes duplicate entries from the list.
# 2. Sorts the list.
# 3. Removes 0 from the list if present.
#
def sort_pagebreaks(breaks) #:nodoc:
breaks.uniq.sort!
breaks.shift if breaks[0] == 0
# 1000 vertical pagebreaks appears to be an internal Excel 5 limit.
# It is slightly higher in Excel 97/200, approx. 1026
breaks.size > 1000 ? breaks[0..999] : breaks
end
#
# Based on the algorithm provided by <NAME> of OpenOffice.
#
def encode_password(password)
i = 0
chars = password.split(//)
count = chars.size
chars.collect! do |char|
i += 1
char = char.ord << i
low_15 = char & 0x7fff
high_15 = char & 0x7fff << 15
high_15 = high_15 >> 15
char = low_15 | high_15
end
encoded_password = <PASSWORD>
chars.each { |c| encoded_password ^= c }
encoded_password ^= count
encoded_password ^= <PASSWORD>
end
#
# value # Result to be encoded.
#
# Encode the user supplied result for a formula.
#
def encode_formula_result(value = nil) #:nodoc:
is_string = 0 # Formula evaluates to str.
# my $num; # Current value of formula.
# my $grbit; # Option flags.
unless value
grbit = 0x03
num = [0].pack("d")
else
# The user specified the result of the formula. We turn off the recalc
# flag and check the result type.
grbit = 0x00
if value.to_s =~ /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/
# Value is a number.
num = [value].pack("d")
else
bools = {
'TRUE' => [1, 1],
'FALSE' => [1, 0],
'#NULL!' => [2, 0],
'#DIV/0!' => [2, 7],
'#VALUE!' => [2, 15],
'#REF!' => [2, 23],
'#NAME?' => [2, 29],
'#NUM!' => [2, 36],
'#N/A' => [2, 42]
}
if bools[value]
# Value is a boolean.
num = [bools[value][0], bools[value][1], 0, 0xFFFF].pack("vvvv")
else
# Value is a string.
num = [0, 0, 0, 0xFFFF].pack("vvvv")
is_string = 1
end
end
end
[num, grbit, is_string]
end
#
# Pack the string value when a formula evaluates to a string. The value cannot
# be calculated by the module and thus must be supplied by the user.
#
def get_formula_string(string) #:nodoc:
ruby_19 { string = convert_to_ascii_if_ascii(string) }
record = 0x0207 # Record identifier
length = 0x00 # Bytes to follow
# string # Formula string.
strlen = string.bytesize # Length of the formula string (chars).
encoding = 0 # String encoding.
# Handle utf8 strings.
if is_utf8?(string)
string = utf8_to_16be(string)
encoding = 1
end
length = 0x03 + string.bytesize # Length of the record data
header = [record, length].pack("vv")
data = [strlen, encoding].pack("vC")
header + data + string
end
def store_formula_common(row, col, xf, value, formula) # :nodoc:
# Excel normally stores the last calculated value of the formula in $num.
# Clearly we are not in a position to calculate this "a priori". Instead
# we set $num to zero and set the option flags in $grbit to ensure
# automatic calculation of the formula when the file is opened.
# As a workaround for some non-Excel apps we also allow the user to
# specify the result of the formula.
#
# is_string # Formula evaluates to str
# num # Current value of formula
# grbit # Option flags
num, grbit, is_string = encode_formula_result(value)
record = 0x0006 # Record identifier
chn = 0x0000 # Must be zero
formlen = formula.bytesize # Length of the binary string
length = 0x16 + formlen # Length of the record data
header = [record, length].pack("vv")
data = [row, col, xf].pack("vvv") +
num +
[grbit, chn, formlen].pack('vVv')
# The STRING record if the formula evaluates to a string.
string = ''
string = get_formula_string(value) if is_string != 0
# Store the data or write immediately depending on the compatibility mode.
store_with_compatibility(row, col, header + data + formula + string)
end
# row1 # Start row
# col1 # Start column
# row2 # End row
# col2 # End column
# url # URL string
# str # Alternative label
#
# Used to write http, ftp and mailto hyperlinks.
# The link type ($options) is 0x03 is the same as absolute dir ref without
# sheet. However it is differentiated by the $unknown2 data stream.
#
# See also write_url() above for a general description and return values.
#
def write_url_web(row1, col1, row2, col2, url, str = nil, format = nil) #:nodoc:
ruby_19 { url = convert_to_ascii_if_ascii(url) }
record = 0x01B8 # Record identifier
length = 0x00000 # Bytes to follow
xf = format || url_format # The cell format
# Write the visible label but protect against url recursion in write().
str = url unless str
error = write_string(row1, col1, str, xf)
return error if error == -2
# Pack the undocumented parts of the hyperlink stream
unknown1 = ["D0C9EA79F9BACE118C8200AA004BA90B02000000"].pack("H*")
unknown2 = ["E0C9EA79F9BACE118C8200AA004BA90B"].pack("H*")
# Pack the option flags
options = [0x03].pack("V")
# URL encoding.
encoding = 0
# Convert an Utf8 URL type and to a null terminated wchar string.
if is_utf8?(url)
url = utf8_to_16be(url)
# URL is null terminated.
ruby_18 { url += "\0\0" } ||
ruby_19 { url += "\0\0".force_encoding('UTF-16BE') }
encoding = 1
end
# Convert an Ascii URL type and to a null terminated wchar string.
if encoding == 0
url =
ruby_18 { url + "\0" } ||
ruby_19 { url.force_encoding('BINARY') + "\0".force_encoding('BINARY') }
url = url.unpack('c*').pack('v*')
end
# Pack the length of the URL
url_len = [url.bytesize].pack("V")
# Calculate the data length
length = 0x34 + url.bytesize
# Pack the header data
header = [record, length].pack("vv")
data = [row1, row2, col1, col2].pack("vvvv")
# Write the packed data
append( header, data,unknown1,options,unknown2,url_len,url)
error
end
# row1 # Start row
# col1 # Start column
# row2 # End row
# col2 # End column
# url # URL string
# str # Alternative label
#
# Used to write internal reference hyperlinks such as "Sheet1!A1".
#
# See also write_url() above for a general description and return values.
#
def write_url_internal(row1, col1, row2, col2, url, str = nil, format = nil) #:nodoc:
record = 0x01B8 # Record identifier
length = 0x00000 # Bytes to follow
xf = format || url_format # The cell format
# Strip URL type
url = url.sub(/^internal:/, '')
# Write the visible label but protect against url recursion in write().
str = url.dup unless str
error = write_string(row1, col1, str, xf)
return error if error == -2
# Pack the undocumented parts of the hyperlink stream
unknown1 = ["D0C9EA79F9BACE118C8200AA004BA90B02000000"].pack("H*")
# Pack the option flags
options = [0x08].pack("V")
# URL encoding.
encoding = 0
# Convert an Utf8 URL type and to a null terminated wchar string.
ruby_18 do
if is_utf8?(url)
# Quote sheet name if not already, i.e., Sheet!A1 to 'Sheet!A1'.
url = "'#{sheetname_from_url(url)}'!#{cell_from_url(url)}" if not url =~ /^'/
# URL is null terminated.
ruby_18 { url = utf8_to_16be(url) + "\0\0" } ||
encoding = 1
end
end
# Convert an Ascii URL type and to a null terminated wchar string.
if encoding == 0
url += "\0"
url = url.unpack('c*').pack('v*')
end
# Pack the length of the URL as chars (not wchars)
url_len = [(url.bytesize/2).to_i].pack("V")
# Calculate the data length
length = 0x24 + url.bytesize
# Pack the header data
header = [record, length].pack("vv")
data = [row1, row2, col1, col2].pack("vvvv")
# Write the packed data
append( header, data, unknown1, options, url_len, url)
error
end
def sheetname_from_url(url)
sheetname, cell = url.split('!')
sheetname
end
def cell_from_url(url)
sheetname, cell = url.split('!')
cell
end
#
# Write links to external directory names such as 'c:\foo.xls',
# c:\foo.xls#Sheet1!A1', '../../foo.xls'. and '../../foo.xls#Sheet1!A1'.
#
# Note: Excel writes some relative links with the $dir_long string. We ignore
# these cases for the sake of simpler code.
#
# See also write_url() above for a general description and return values.
#
def write_url_external(row1, col1, row2, col2, url, str = nil, format = nil) #:nodoc:
# Network drives are different. We will handle them separately
# MS/Novell network drives and shares start with \\
if url =~ /^external:(\\\\|\/\/)/
return write_url_external_net(row1, col1, row2, col2, url, str, format)
end
record = 0x01B8 # Record identifier
length = 0x00000 # Bytes to follow
xf = format || url_format # The cell format
# Strip URL type and change Unix dir separator to Dos style (if needed)
#
url = url.sub(/^external:/, '').gsub(%r|/|, '\\')
# Write the visible label but protect against url recursion in write().
str = url.sub(/\#/, ' - ') unless str
error = write_string(row1, col1, str, xf)
return error if error == -2
# Determine if the link is relative or absolute:
# Absolute if link starts with DOS drive specifier like C:
# Otherwise default to 0x00 for relative link.
#
absolute = 0x00
absolute = 0x02 if url =~ /^[A-Za-z]:/
dir_long, link_type, sheet_len, sheet = analyze_link(url, absolute)
# Pack the link type
link_type = [link_type].pack("V")
# Calculate the up-level dir count e.g. (..\..\..\ == 3)
up_count = 0
while dir_long.sub!(/^\.\.\\/, '')
up_count += 1
end
up_count = [up_count].pack("v")
# Store the short dos dir name (null terminated)
dir_short = dir_long + "\0"
# Store the long dir name as a wchar string (non-null terminated)
dir_long = dir_long.split('').join("\0") + "\0"
# Pack the lengths of the dir strings
dir_short_len = [dir_short.bytesize].pack("V")
dir_long_len = [dir_long.bytesize].pack("V")
stream_len = [dir_long.bytesize + 0x06].pack("V")
# Pack the undocumented parts of the hyperlink stream
unknown1 = ['D0C9EA79F9BACE118C8200AA004BA90B02000000'].pack("H*")
unknown2 = ['0303000000000000C000000000000046'].pack("H*")
unknown3 = ['FFFFADDE000000000000000000000000000000000000000'].pack("H*")
unknown4 = [0x03].pack("v")
# Pack the main data stream
data = [row1, row2, col1, col2].pack("vvvv") +
unknown1 +
link_type +
unknown2 +
up_count +
dir_short_len+
dir_short +
unknown3 +
stream_len +
dir_long_len +
unknown4 +
dir_long +
sheet_len +
sheet
# Pack the header data
length = data.bytesize
header = [record, length].pack("vv")
# Write the packed data
append(header, data)
error
end
#
# Write links to external MS/Novell network drives and shares such as
# '//NETWORK/share/foo.xls' and '//NETWORK/share/foo.xls#Sheet1!A1'.
#
# See also write_url() above for a general description and return values.
#
def write_url_external_net(row1, col1, row2, col2, url, str, format) #:nodoc:
record = 0x01B8 # Record identifier
length = 0x00000 # Bytes to follow
xf = format || url_format # The cell format
# Strip URL type and change Unix dir separator to Dos style (if needed)
#
url = url.sub(/^external:/, '').gsub!(%r|/|, '\\')
# Write the visible label but protect against url recursion in write().
str = url.sub(/\#/, ' - ') unless str
error = write_string(row1, col1, str, xf)
return error if error == -2
dir_long, link_type, sheet_len, sheet = analyze_link(url)
# Pack the link type
link_type = [link_type].pack("V")
# Make the string null terminated
dir_long += "\0"
# Pack the lengths of the dir string
dir_long_len = [dir_long.bytesize].pack("V")
# Store the long dir name as a wchar string (non-null terminated)
dir_long = dir_long.split('').join("\0") + "\0"
# Pack the undocumented part of the hyperlink stream
unknown1 = ['D0C9EA79F9BACE118C8200AA004BA90B02000000'].pack("H*")
# Pack the main data stream
data = [row1, row2, col1, col2].pack("vvvv") +
unknown1 +
link_type +
dir_long_len +
dir_long +
sheet_len +
sheet
# Pack the header data
length = data.bytesize
header = [record, length].pack("vv")
# Write the packed data
append(header, data)
error
end
def url_format
@workbook.url_format
end
# Determine if the link contains a sheet reference and change some of the
# parameters accordingly.
# Split the dir name and sheet name (if it exists)
#
def analyze_link(url, absolute = nil) # :nodoc:
dir_long , sheet = url.split(/\#/)
link_type = absolute ? (0x01 | absolute) : 0x0103
if sheet
link_type |= 0x08
sheet_len = [sheet.bytesize + 0x01].pack("V")
sheet = sheet.split('').join("\0") + "\0\0\0"
else
sheet_len = ''
sheet = ''
end
[dir_long, link_type, sheet_len, sheet]
end
def date_1904? # :nodoc:
@workbook.date_1904
end
# row : Row Number
# colMic : First defined column
# colMac : Last defined column
#
# Write a default row record, in compatibility mode, for rows that don't have
# user specified values..
#
def write_row_default(row, colMic, colMac) #:nodoc:
record = 0x0208 # Record identifier
length = 0x0010 # Number of bytes to follow
miyRw = 0xFF # Row height
irwMac = 0x0000 # Used by Excel to optimise loading
reserved = 0x0000 # Reserved
grbit = 0x0100 # Option flags
ixfe = 0x0F # XF index
store_simple(record, length,
row, colMic, colMac, miyRw, irwMac, reserved, grbit, ixfe)
end
#
# Check that $row and $col are valid and store max and min values for use in
# DIMENSIONS record. See, store_dimensions().
#
# The $ignore_row/$ignore_col flags is used to indicate that we wish to
# perform the dimension check without storing the value.
#
# The ignore flags are use by set_row() and data_validate.
#
def check_dimensions(row, col, ignore_row = 0, ignore_col = 0) #:nodoc:
return -2 unless row
return -2 if row >= RowMax
return -2 unless col
return -2 if col >= ColMax
@dimension.row(row) if ignore_row == 0
@dimension.col(col) if ignore_col == 0
0
end
#
# Writes Excel DIMENSIONS to define the area in which there is cell data.
#
# Notes:
# Excel stores the max row/col as row/col +1.
# Max and min values of 0 are used to indicate that no cell data.
# We set the undef member data to 0 since it is used by store_table().
# Inserting images or charts doesn't change the DIMENSION data.
#
def store_dimensions #:nodoc:
record = 0x0200 # Record identifier
length = 0x000E # Number of bytes to follow
reserved = 0x0000 # Reserved by Excel
@dimension.increment_row_max
@dimension.increment_col_max
header = [record, length].pack("vv")
fields = [@dimension.row_min, @dimension.row_max, @dimension.col_min, @dimension.col_max, reserved]
data = fields.pack("VVvvv")
prepend(header, data)
end
#
# Write BIFF record Window2.
#
def store_window2 #:nodoc:
record = 0x023E # Record identifier
length = 0x0012 # Number of bytes to follow
grbit = 0x00B6 # Option flags
rwTop = @first_row # Top visible row
colLeft = @first_col # Leftmost visible column
rgbHdr = 0x00000040 # Row/col heading, grid color
wScaleSLV = 0x0000 # Zoom in page break preview
wScaleNormal = 0x0000 # Zoom in normal view
reserved = 0x00000000
# The options flags that comprise $grbit
fDspFmla = @display_formulas # 0 - bit
fDspGrid = @screen_gridlines # 1
fDspRwCol = @display_headers # 2
fFrozen = frozen? ? 1 : 0 # 3
fDspZeros = display_zeros? ? 1 : 0 # 4
fDefaultHdr = 1 # 5
fArabic = @display_arabic || 0 # 6
fDspGuts = @outline.visible? ? 1 : 0 # 7
fFrozenNoSplit = @frozen_no_split # 0 - bit
fSelected = selected? ? 1 : 0 # 1
fPaged = active? ? 1 : 0 # 2
fBreakPreview = 0 # 3
grbit = fDspFmla
grbit |= fDspGrid << 1
grbit |= fDspRwCol << 2
grbit |= fFrozen << 3
grbit |= fDspZeros << 4
grbit |= fDefaultHdr << 5
grbit |= fArabic << 6
grbit |= fDspGuts << 7
grbit |= fFrozenNoSplit << 8
grbit |= fSelected << 9
grbit |= fPaged << 10
grbit |= fBreakPreview << 11
header = [record, length].pack("vv")
data =[grbit, rwTop, colLeft, rgbHdr, wScaleSLV, wScaleNormal, reserved].pack("vvvVvvV")
append(header, data)
end
#
# Set page view mode. Only applicable to Mac Excel.
#
def store_page_view #:nodoc:
return if @page_view == 0
data = ['C8081100C808000000000040000000000900000000'].pack("H*")
append(data)
end
#
# Write the Tab Color BIFF record.
#
def store_tab_color #:nodoc:
color = @tab_color
return if color == 0
record = 0x0862 # Record identifier
length = 0x0014 # Number of bytes to follow
zero = 0x0000
unknown = 0x0014
store_simple(record, length, record, zero, zero, zero, zero,
zero, unknown, zero, color, zero)
end
#
# Write BIFF record DEFROWHEIGHT.
#
def store_defrow #:nodoc:
record = 0x0225 # Record identifier
length = 0x0004 # Number of bytes to follow
grbit = 0x0000 # Options.
height = 0x00FF # Default row height
header = [record, length].pack("vv")
data = [grbit, height].pack("vv")
prepend(header, data)
end
#
# Write BIFF record DEFCOLWIDTH.
#
def store_defcol #:nodoc:
record = 0x0055 # Record identifier
length = 0x0002 # Number of bytes to follow
colwidth = 0x0008 # Default column width
header = [record, length].pack("vv")
data = [colwidth].pack("v")
prepend(header, data)
end
def store_colinfo(colinfo) # :nodoc:
prepend(*colinfo.biff_record)
end
#
# Write BIFF record FILTERMODE to indicate that the worksheet contains
# AUTOFILTER record, ie. autofilters with a filter set.
#
def store_filtermode #:nodoc:
# Only write the record if the worksheet contains a filtered autofilter.
return '' if @filter_on == 0
record = 0x009B # Record identifier
length = 0x0000 # Number of bytes to follow
header = [record, length].pack('vv')
prepend(header)
end
#
# Write BIFF record AUTOFILTERINFO.
#
def store_autofilterinfo #:nodoc:
# Only write the record if the worksheet contains an autofilter.
return '' if @filter_area.count == 0
record = 0x009D # Record identifier
length = 0x0002 # Number of bytes to follow
num_filters = @filter_area.count
header = [record, length].pack('vv')
data = [num_filters].pack('v')
prepend(header, data)
end
#
# Write BIFF record SELECTION.
#
def store_selection(first_row=0, first_col=0, last_row = nil, last_col =nil) #:nodoc:
record = 0x001D # Record identifier
length = 0x000F # Number of bytes to follow
pane_position = @active_pane # Pane position
row_active = first_row # Active row
col_active = first_col # Active column
irefAct = 0 # Active cell ref
cref = 1 # Number of refs
row_first = first_row # First row in reference
col_first = first_col # First col in reference
row_last = last_row || row_first # Last row in reference
col_last = last_col || col_first # Last col in reference
# Swap last row/col for first row/col as necessary
row_first, row_last = row_last, row_first if row_first > row_last
col_first, col_last = col_last, col_first if col_first > col_last
header = [record, length].pack('vv')
data = [pane_position, row_active, col_active, irefAct, cref,
row_first, row_last, col_first, col_last].pack('CvvvvvvCC')
append(header, data)
end
#
# Write BIFF record EXTERNCOUNT to indicate the number of external sheet
# references in a worksheet.
#
# Excel only stores references to external sheets that are used in formulas.
# For simplicity we store references to all the sheets in the workbook
# regardless of whether they are used or not. This reduces the overall
# complexity and eliminates the need for a two way dialogue between the formula
# parser the worksheet objects.
#
def store_externcount(count) #:nodoc:
record = 0x0016 # Record identifier
length = 0x0002 # Number of bytes to follow
cxals = count # Number of external references
header = [record, length].pack('vv')
data = [cxals].pack('v')
prepend(header, data)
end
# sheetname : Worksheet name
#
# Writes the Excel BIFF EXTERNSHEET record. These references are used by
# formulas. A formula references a sheet name via an index. Since we store a
# reference to all of the external worksheets the EXTERNSHEET index is the same
# as the worksheet index.
#
def store_externsheet(sheetname) #:nodoc:
record = 0x0017 # Record identifier
# length; # Number of bytes to follow
# cch # Length of sheet name
# rgch # Filename encoding
# References to the current sheet are encoded differently to references to
# external sheets.
#
if @name == sheetname
sheetname = ''
length = 0x02 # The following 2 bytes
cch = 1 # The following byte
rgch = 0x02 # Self reference
else
length = 0x02 + sheetname.bytesize
cch = sheetname.bytesize
rgch = 0x03 # Reference to a sheet in the current workbook
end
header = [record, length].pack('vv')
data = [cch, rgch].pack('CC')
prepend(header, data, sheetname)
end
# y = args[0] || 0 # Vertical split position
# x = $_[1] || 0; # Horizontal split position
# rwTop = $_[2]; # Top row visible
# my $colLeft = $_[3]; # Leftmost column visible
# my $no_split = $_[4]; # No used here.
# my $pnnAct = $_[5]; # Active pane
#
#
# Writes the Excel BIFF PANE record.
# The panes can either be frozen or thawed (unfrozen).
# Frozen panes are specified in terms of a integer number of rows and columns.
# Thawed panes are specified in terms of Excel's units for rows and columns.
#
def store_panes(y=0, x=0, rwtop=nil, colleft=nil, no_split=nil, pnnAct=nil) #:nodoc:
record = 0x0041 # Record identifier
length = 0x000A # Number of bytes to follow
# Code specific to frozen or thawed panes.
if frozen?
# Set default values for $rwTop and $colLeft
rwtop = y unless rwtop
colleft = x unless colleft
else
# Set default values for $rwTop and $colLeft
rwtop = 0 unless rwtop
colleft = 0 unless colleft
# Convert Excel's row and column units to the internal units.
# The default row height is 12.75
# The default column width is 8.43
# The following slope and intersection values were interpolated.
#
y = 20*y + 255
x = 113.879*x + 390
end
# Determine which pane should be active. There is also the undocumented
# option to override this should it be necessary: may be removed later.
#
unless pnnAct
pnnAct = 0 if (x != 0 && y != 0) # Bottom right
pnnAct = 1 if (x != 0 && y == 0) # Top right
pnnAct = 2 if (x == 0 && y != 0) # Bottom left
pnnAct = 3 if (x == 0 && y == 0) # Top left
end
@active_pane = pnnAct # Used in store_selection
store_simple(record, length, x, y, rwtop, colleft, pnnAct)
end
#
# Store the page setup SETUP BIFF record.
#
def store_setup #:nodoc:
record = 0x00A1 # Record identifier
length = 0x0022 # Number of bytes to follow
iPaperSize = @paper_size # Paper size
iScale = @print_scale # Print scaling factor
iPageStart = @page_start # Starting page number
iFitWidth = @fit_width # Fit to number of pages wide
iFitHeight = @fit_height # Fit to number of pages high
grbit = 0x00 # Option flags
iRes = 0x0258 # Print resolution
iVRes = 0x0258 # Vertical print resolution
numHdr = @margin_header # Header Margin
numFtr = @margin_footer # Footer Margin
iCopies = 0x01 # Number of copies
fLeftToRight = @page_order # Print over then down
fLandscape = @orientation # Page orientation
fNoPls = 0x0 # Setup not read from printer
fNoColor = @black_white # Print black and white
fDraft = @draft_quality # Print draft quality
fNotes = @print_comments# Print notes
fNoOrient = 0x0 # Orientation not set
fUsePage = @custom_start # Use custom starting page
grbit = fLeftToRight
grbit |= fLandscape << 1
grbit |= fNoPls << 2
grbit |= fNoColor << 3
grbit |= fDraft << 4
grbit |= fNotes << 5
grbit |= fNoOrient << 6
grbit |= fUsePage << 7
numHdr = [numHdr].pack('d')
numFtr = [numFtr].pack('d')
if @byte_order
numHdr.reverse!
numFtr.reverse!
end
header = [record, length].pack('vv')
data1 = [iPaperSize, iScale, iPageStart,
iFitWidth, iFitHeight, grbit, iRes, iVRes].pack("vvvvvvvv")
data2 = numHdr + numFtr
data3 = [iCopies].pack('v')
prepend(header, data1, data2, data3)
end
#
# Store the header caption BIFF record.
#
def store_header #:nodoc:
store_header_footer_common(:header)
end
#
# Store the footer caption BIFF record.
#
def store_footer #:nodoc:
store_header_footer_common(:footer)
end
#
# type : :header / :footer
#
def store_header_footer_common(type) # :nodoc:
if type == :header
record = 0x0014
str = @header || ''
encoding = @header_encoding || 0
else
record = 0x0015
str = @footer || ''
encoding = @footer_encoding || 0
end
cch = str.bytesize # Length of header/footer string
# Character length is num of chars not num of bytes
cch /= 2 if encoding != 0
# Change the UTF-16 name from BE to LE
str = str.unpack('v*').pack('n*') if encoding != 0
length = 3 + str.bytesize
header = [record, length].pack('vv')
data = [cch, encoding].pack('vC')
prepend(header, data, str)
end
#
# Store the horizontal centering HCENTER BIFF record.
#
def store_hcenter #:nodoc:
store_biff_common(:hcenter)
end
#
# Store the vertical centering VCENTER BIFF record.
#
def store_vcenter #:nodoc:
store_biff_common(:vcenter)
end
#
# Store the LEFTMARGIN BIFF record.
#
def store_margin_left #:nodoc:
store_margin_common(0x0026, 0x0008, @margin_left)
end
#
# Store the RIGHTMARGIN BIFF record.
#
def store_margin_right #:nodoc:
store_margin_common(0x0027, 0x0008, @margin_right)
end
#
# Store the TOPMARGIN BIFF record.
#
def store_margin_top #:nodoc:
store_margin_common(0x0028, 0x0008, @margin_top)
end
#
# Store the BOTTOMMARGIN BIFF record.
#
def store_margin_bottom #:nodoc:
store_margin_common(0x0029, 0x0008, @margin_bottom)
end
#
# record : Record identifier
# length : bytes to follow
# margin : Margin in inches
#
def store_margin_common(record, length, margin) # :nodoc:
header = [record, length].pack('vv')
data = [margin].pack('d')
data.reverse! if @byte_order
prepend(header, data)
end
#
# :call-seq:
# merge_cells(first_row, first_col, last_row, last_col)
#
# This is an Excel97/2000 method. It is required to perform more complicated
# merging than the normal align merge in Format.pm
#
def merge_cells(*args) #:nodoc:
# Check for a cell reference in A1 notation and substitute row and column
args = row_col_notation(args)
record = 0x00E5 # Record identifier
length = 0x000A # Bytes to follow
cref = 1 # Number of refs
rwFirst = args[0] # First row in reference
colFirst = args[1] # First col in reference
rwLast = args[2] || rwFirst # Last row in reference
colLast = args[3] || colFirst # Last col in reference
# Excel doesn't allow a single cell to be merged
return if rwFirst == rwLast and colFirst == colLast
# Swap last row/col with first row/col as necessary
rwFirst, rwLast = rwLast, rwFirst if rwFirst > rwLast
colFirst, colLast = colLast, colFirst if colFirst > colLast
store_simple(record, length, cref, rwFirst, rwLast, colFirst, colLast)
end
#
# Write the PRINTHEADERS BIFF record.
#
def store_print_headers #:nodoc:
store_biff_common(:print_headers)
end
#
# Write the PRINTGRIDLINES BIFF record. Must be used in conjunction with the
# GRIDSET record.
#
def store_print_gridlines #:nodoc:
store_biff_common(:print_gridlines)
end
def store_biff_common(type) # :nodoc:
case type
when :hcenter
record = 0x0083
flag = @hcenter || 0
when :vcenter
record = 0x0084
flag = @vcenter || 0
when :print_headers
record = 0x002a
flag = @print_headers || 0
when :print_gridlines
record = 0x002b
flag = @print_gridlines
end
length = 0x0002
header = [record, length].pack("vv")
data = [flag].pack("v")
prepend(header, data)
end
#
# Write the GRIDSET BIFF record. Must be used in conjunction with the
# PRINTGRIDLINES record.
#
def store_gridset #:nodoc:
record = 0x0082 # Record identifier
length = 0x0002 # Bytes to follow
fGridSet = @print_gridlines == 0 ? 1 : 0 # Boolean flag
header = [record, length].pack("vv")
data = [fGridSet].pack("v")
prepend(header, data)
end
#
# Write the GUTS BIFF record. This is used to configure the gutter margins
# where Excel outline symbols are displayed. The visibility of the gutters is
# controlled by a flag in WSBOOL. See also store_wsbool().
#
# We are all in the gutter but some of us are looking at the stars.
#
def store_guts #:nodoc:
record = 0x0080 # Record identifier
length = 0x0008 # Bytes to follow
dxRwGut = 0x0000 # Size of row gutter
dxColGut = 0x0000 # Size of col gutter
row_level = @outline.row_level
# Calculate the maximum column outline level. The equivalent calculation
# for the row outline level is carried out in set_row().
#
col_level = @colinfo.collect {|colinfo| colinfo.level}.max || 0
# Set the limits for the outline levels (0 <= x <= 7).
col_level = 0 if col_level < 0
col_level = 7 if col_level > 7
# The displayed level is one greater than the max outline levels
row_level += 1 if row_level > 0
col_level += 1 if col_level > 0
header = [record, length].pack("vv")
data = [dxRwGut, dxColGut, row_level, col_level].pack("vvvv")
prepend(header, data)
end
#
# Write the WSBOOL BIFF record, mainly for fit-to-page. Used in conjunction
# with the SETUP record.
#
def store_wsbool #:nodoc:
record = 0x0081 # Record identifier
length = 0x0002 # Bytes to follow
grbit = 0x0000 # Option flags
# Set the option flags
grbit |= 0x0001 # Auto page breaks visible
grbit |= 0x0020 if @outline.style != 0 # Auto outline styles
grbit |= 0x0040 if @outline.below != 0 # Outline summary below
grbit |= 0x0080 if @outline.right != 0 # Outline summary right
grbit |= 0x0100 if @fit_page != 0 # Page setup fit to page
grbit |= 0x0400 if @outline.visible? # Outline symbols displayed
header = [record, length].pack("vv")
data = [grbit].pack('v')
prepend(header, data)
end
#
# Write the HORIZONTALPAGEBREAKS BIFF record.
#
def store_hbreak #:nodoc:
store_breaks_common(@hbreaks)
end
#
# Write the VERTICALPAGEBREAKS BIFF record.
#
def store_vbreak #:nodoc:
store_breaks_common(@vbreaks)
end
def store_breaks_common(breaks) # :nodoc:
unless breaks.empty?
record = breaks == @vbreaks ? 0x001a : 0x001b # Record identifier
cbrk = breaks.size # Number of page breaks
length = 2 + 6 * cbrk # Bytes to follow
header = [record, length].pack("vv")
data = [cbrk].pack("v")
# Append each sorted page break
sort_pagebreaks(breaks).each do |brk|
data += [brk, 0x0000, 0x00ff].pack("vvv")
end
prepend(header, data)
end
end
#
# Set the Biff PROTECT record to indicate that the worksheet is protected.
#
def store_protect #:nodoc:
store_protect_common
end
def protect?
@protect
end
#
# Set the Biff OBJPROTECT record to indicate that objects are protected.
#
def store_obj_protect #:nodoc:
store_protect_common(:obj)
end
def store_protect_common(type = nil) # :nodoc:
if protect?
record = if type == :obj # Record identifier
0x0063 # store_obj_protect
else
0x0012 # store_protect
end
length = 0x0002 # Bytes to follow
fLock = protect? ? 1 : 0 # Worksheet is protected
header = [record, length].pack("vv")
data = [fLock].pack("v")
prepend(header, data)
end
end
#
# Write the worksheet PASSWORD record.
#
def store_password #:nodoc:
# Exit unless sheet protection and password have been specified
return unless protect? && @password
record = 0x0013 # Record identifier
length = 0x0002 # Bytes to follow
wPassword = <PASSWORD> # Encoded password
header = [record, length].pack("vv")
data = [wPassword].pack("v")
prepend(header, data)
end
#
# Note about compatibility mode.
#
# Excel doesn't require every possible Biff record to be present in a file.
# In particular if the indexing records INDEX, ROW and DBCELL aren't present
# it just ignores the fact and reads the cells anyway. This is also true of
# the EXTSST record. Gnumeric and OOo also take this approach. This allows
# WriteExcel to ignore these records in order to minimise the amount of data
# stored in memory. However, other third party applications that read Excel
# files often expect these records to be present. In "compatibility mode"
# WriteExcel writes these records and tries to be as close to an Excel
# generated file as possible.
#
# This requires additional data to be stored in memory until the file is
# about to be written. This incurs a memory and speed penalty and may not be
# suitable for very large files.
#
#
# Write cell data stored in the worksheet row/col table.
#
# This is only used when compatibity_mode() is in operation.
#
# This method writes ROW data, then cell data (NUMBER, LABELSST, etc) and then
# DBCELL records in blocks of 32 rows. This is explained in detail (for a
# change) in the Excel SDK and in the OOo Excel file format doc.
#
def store_table #:nodoc:
return unless compatibility?
# Offset from the DBCELL record back to the first ROW of the 32 row block.
row_offset = 0
# Track rows that have cell data or modified by set_row().
written_rows = []
# Write the ROW records with updated max/min col fields.
#
(0 .. @dimension.row_max-1).each do |row|
# Skip unless there is cell data in row or the row has been modified.
next unless @table[row] or @row_data[row]
# Store the rows with data.
written_rows.push(row)
# Increase the row offset by the length of a ROW record;
row_offset += 20
# The max/min cols in the ROW records are the same as in DIMENSIONS.
col_min = @dimension.col_min
col_max = @dimension.col_max
# Write a user specified ROW record (modified by set_row()).
if @row_data[row]
# Rewrite the min and max cols for user defined row record.
packed_row = @row_data[row]
packed_row[6..9] = [col_min, col_max].pack('vv')
append(packed_row)
else
# Write a default Row record if there isn't a user defined ROW.
write_row_default(row, col_min, col_max)
end
# If 32 rows have been written or we are at the last row in the
# worksheet then write the cell data and the DBCELL record.
#
if written_rows.size == 32 || row == @dimension.row_max - 1
# Offsets to the first cell of each row.
cell_offsets = []
cell_offsets.push(row_offset - 20)
# Write the cell data in each row and sum their lengths for the
# cell offsets.
#
written_rows.each do |rw|
cell_offset = 0
if @table[rw]
@table[rw].each do |clm|
next unless clm
append(clm)
length = clm.bytesize
row_offset += length
cell_offset += length
end
end
cell_offsets.push(cell_offset)
end
# The last offset isn't required.
cell_offsets.pop
# Stores the DBCELL offset for use in the INDEX record.
@db_indices.push(@datasize)
# Write the DBCELL record.
store_dbcell(row_offset, cell_offsets)
# Clear the variable for the next block of rows.
written_rows = []
cell_offsets = []
row_offset = 0
end
end
end
#
# Store the DBCELL record using the offset calculated in store_table().
#
# This is only used when compatibity_mode() is in operation.
#
def store_dbcell(row_offset, cell_offsets) #:nodoc:
record = 0x00D7 # Record identifier
length = 4 + 2 * cell_offsets.size # Bytes to follow
header = [record, length].pack('vv')
data = [row_offset].pack('V')
cell_offsets.each do |co|
data += [co].pack('v')
end
append(header, data)
end
#
# Store the INDEX record using the DBCELL offsets calculated in store_table().
#
# This is only used when compatibity_mode() is in operation.
#
def store_index #:nodoc:
return unless compatibility?
indices = @db_indices
reserved = 0x00000000
row_min = @dimension.row_min
row_max = @dimension.row_max
record = 0x020B # Record identifier
length = 16 + 4 * indices.size # Bytes to follow
header = [record, length].pack('vv')
data = [reserved, row_min, row_max, reserved].pack('VVVV')
indices.each do |index|
data += [index + @offset + 20 + length + 4].pack('V')
end
prepend(header, data)
end
def adjust_col_position(x, col) # :nodoc:
while x >= size_col(col)
x -= size_col(col)
col += 1
end
[x, col]
end
def adjust_row_position(y, row) # :nodoc:
while y >= size_row(row)
y -= size_row(row)
row += 1
end
[y, row]
end
#
# Convert the width of a cell from user's units to pixels. Excel rounds the
# column width to the nearest pixel. If the width hasn't been set by the user
# we use the default value. If the column is hidden we use a value of zero.
#
def size_col(col) #:nodoc:
# Look up the cell value to see if it has been changed
if @col_sizes[col]
width = @col_sizes[col]
# The relationship is different for user units less than 1.
if width < 1
(width *12).to_i
else
(width *7 +5 ).to_i
end
else
64
end
end
#
# Convert the height of a cell from user's units to pixels. By interpolation
# the relationship is: y = 4/3x. If the height hasn't been set by the user we
# use the default value. If the row is hidden we use a value of zero. (Not
# possible to hide row yet).
#
def size_row(row) #:nodoc:
# Look up the cell value to see if it has been changed
if @row_sizes[row]
if @row_sizes[row] == 0
0
else
(4/3.0 * @row_sizes[row]).to_i
end
else
17
end
end
#
# Store the window zoom factor. This should be a reduced fraction but for
# simplicity we will store all fractions with a numerator of 100.
#
def store_zoom #:nodoc:
# If scale is 100 we don't need to write a record
return if @zoom == 100
record = 0x00A0 # Record identifier
length = 0x0004 # Bytes to follow
store_simple(record, length, @zoom, 100)
end
# Older method name for backwards compatibility.
# *write_unicode = *write_utf16be_string;
# *write_unicode_le = *write_utf16le_string;
#
# Function to iterate through the columns that form part of an autofilter
# range and write Biff AUTOFILTER records if a filter expression has been set.
#
def store_autofilters #:nodoc:
# Skip all columns if no filter have been set.
return '' if @filter_on == 0
col1 = @filter_area.col_min
col2 = @filter_area.col_max
col1.upto(col2) do |i|
# Reverse order since records are being pre-pended.
col = col2 -i
# Skip if column doesn't have an active filter.
next unless @filter_cols[col]
# Retrieve the filter tokens and write the autofilter records.
store_autofilter(col, *@filter_cols[col])
end
end
#
# Function to write worksheet AUTOFILTER records. These contain 2 Biff Doper
# structures to represent the 2 possible filter conditions.
#
def store_autofilter(index, operator_1, token_1, #:nodoc:
join = nil, operator_2 = nil, token_2 = nil)
record = 0x009E
length = 0x0000
top10_active = 0
top10_direction = 0
top10_percent = 0
top10_value = 101
grbit = join || 0
optimised_1 = 0
optimised_2 = 0
doper_1 = ''
doper_2 = ''
string_1 = ''
string_2 = ''
# Excel used an optimisation in the case of a simple equality.
optimised_1 = 1 if operator_1 == 2
optimised_2 = 1 if operator_2 && operator_2 == 2
# Convert non-simple equalities back to type 2. See parse_filter_tokens().
operator_1 = 2 if operator_1 == 22
operator_2 = 2 if operator_2 && operator_2 == 22
# Handle a "Top" style expression.
if operator_1 >= 30
# Remove the second expression if present.
operator_2 = nil
token_2 = nil
# Set the active flag.
top10_active = 1
if (operator_1 == 30 or operator_1 == 31)
top10_direction = 1
end
if (operator_1 == 31 or operator_1 == 33)
top10_percent = 1
end
if (top10_direction == 1)
operator_1 = 6
else
operator_1 = 3
end
top10_value = token_1.to_i
token_1 = 0
end
grbit |= optimised_1 << 2
grbit |= optimised_2 << 3
grbit |= top10_active << 4
grbit |= top10_direction << 5
grbit |= top10_percent << 6
grbit |= top10_value << 7
doper_1, string_1 = pack_doper(operator_1, token_1)
doper_2, string_2 = pack_doper(operator_2, token_2)
doper_1 = '' unless doper_1
doper_2 = '' unless doper_2
string_1 = '' unless string_1
string_2 = '' unless string_2
data = [index].pack('v')
data += [grbit].pack('v')
data += doper_1 + doper_2 + string_1 + string_2
length = data.bytesize
header = [record, length].pack('vv')
prepend(header, data)
end
#
# Create a Biff Doper structure that represents a filter expression. Depending
# on the type of the token we pack an Empty, String or Number doper.
#
def pack_doper(operator, token) #:nodoc:
doper = ''
string = ''
# Return default doper for non-defined filters.
unless operator
return pack_unused_doper, string
end
if token.to_s =~ /^blanks|nonblanks$/i
doper = pack_blanks_doper(operator, token)
elsif operator == 2 or
!(token.to_s =~ /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/)
# Excel treats all tokens as strings if the operator is equality, =.
string = token.to_s
ruby_19 { string = convert_to_ascii_if_ascii(string) }
encoding = 0
length = string.bytesize
# Handle utf8 strings
if is_utf8?(string)
string = utf8_to_16be(string)
encodign = 1
end
string =
ruby_18 { [encoding].pack('C') + string } ||
ruby_19 { [encoding].pack('C') + string.force_encoding('BINARY') }
doper = pack_string_doper(operator, length)
else
string = ''
doper = pack_number_doper(operator, token)
end
[doper, string]
end
#
# Pack an empty Doper structure.
#
def pack_unused_doper #:nodoc:
[0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0].pack('C10')
end
#
# Pack an Blanks/NonBlanks Doper structure.
#
def pack_blanks_doper(operator, token) #:nodoc:
if token == 'blanks'
type = 0x0C
operator = 2
else
type = 0x0E
operator = 5
end
[type, # Data type
operator,
0x0000, 0x0000 # Reserved
].pack('CCVV')
end
#
# Pack an string Doper structure.
#
def pack_string_doper(operator, length) #:nodoc:
[0x06, # Data type
operator,
0x0000, #Reserved
length, # String char length
0x0, 0x0, 0x0 # Reserved
].pack('CCVCCCC')
end
#
# Pack an IEEE double number Doper structure.
#
def pack_number_doper(operator, number) #:nodoc:
number = [number].pack('d')
number.reverse! if @byte_order
[0x04, operator].pack('CC') + number
end
#
# Store the collections of records that make up images.
#
def store_images #:nodoc:
# Skip this if there aren't any images.
return if @images.array.empty?
spid = @object_ids.spid
@images.array.each_index do |i|
@images.array[i].store_image_record(i, @images.array.size, charts_size, @filter_area.count, comments_size, spid)
store_obj_image(i + 1)
end
@object_ids.spid = spid
end
def store_child_mso_record(spid, *vertices) # :nodoc:
store_mso_sp_container(88) +
store_mso_sp(201, spid, 0x0A00) +
store_mso_opt_filter +
store_mso_client_anchor(1, *vertices) +
store_mso_client_data
end
#
# Store the collections of records that make up charts.
#
def store_charts #:nodoc:
# Skip this if there aren't any charts.
return if charts_size == 0
record = 0x00EC # Record identifier
charts = @charts.array
charts.each_index do |i|
data = ''
if i == 0 && images_size == 0
dg_length = 192 + 120 * (charts_size - 1) + 96 * filter_count + 128 * comments_size
spgr_length = dg_length - 24
# Write the parent MSODRAWIING record.
data += store_parent_mso_record(dg_length, spgr_length, @object_ids.spid)
@object_ids.spid += 1
end
data += store_mso_sp_container_sp(@object_ids.spid)
data += store_mso_opt_chart_client_anchor_client_data(*charts[i].vertices)
length = data.bytesize
header = [record, length].pack("vv")
append(header, data)
store_obj_chart(images_size + i + 1)
store_chart_binary(charts[i].chart)
@object_ids.spid += 1
end
# Simulate the EXTERNSHEET link between the chart and data using a formula
# such as '=Sheet1!A1'.
# TODO. Won't work for external data refs. Also should use a more direct
# method.
#
store_formula("='#{@name}'!A1")
end
def store_mso_sp_container_sp(spid) # :nodoc:
store_mso_sp_container(112) + store_mso_sp(201, spid, 0x0A00)
end
def store_mso_opt_chart_client_anchor_client_data(*vertices) # :nodoc:
store_mso_opt_chart +
store_mso_client_anchor(0, *vertices) +
store_mso_client_data
end
#
# Add the binary data for a chart. This could either be from a Chart object
# or from an external binary file (for backwards compatibility).
#
def store_chart_binary(chart) #:nodoc:
if chart.respond_to?(:to_str)
filehandle = File.open(chart, "rb")
# die "Couldn't open $filename in add_chart_ext(): $!.\n";
while tmp = filehandle.read(4096)
append(tmp)
end
else
chart.close
tmp = chart.get_data
append(tmp)
end
end
#
# Store the collections of records that make up filters.
#
def store_filters #:nodoc:
# Skip this if there aren't any filters.
return if @filter_area.count == 0
@object_ids.spid = @filter_area.store
# Simulate the EXTERNSHEET link between the filter and data using a formula
# such as '=Sheet1!A1'.
# TODO. Won't work for external data refs. Also should use a more direct
# method.
#
formula = "='#{@name}'!A1"
store_formula(formula)
end
#
# Store the collections of records that make up cell comments.
#
# NOTE: We write the comment objects last since that makes it a little easier
# to write the NOTE records directly after the MSODRAWIING records.
#
def store_comments #:nodoc:
return if @comments.array.empty?
spid = @object_ids.spid
num_comments = comments_size
# Number of objects written so far.
num_objects = images_size + @filter_area.count + charts_size
@comments.array.each_index { |i| spid = @comments.array[i].store_comment_record(i, num_objects, num_comments, spid) }
# Write the NOTE records after MSODRAWIING records.
@comments.array.each_index { |i| @comments.array[i].store_note_record(num_objects + i + 1) }
end
#
# Write the Escher DgContainer record that is part of MSODRAWING.
#
def store_mso_dg_container(length) #:nodoc:
type = 0xF002
version = 15
instance = 0
data = ''
add_mso_generic(type, version, instance, data, length)
end
#
# Write the Escher Dg record that is part of MSODRAWING.
#
def store_mso_dg #:nodoc:
type = 0xF008
version = 0
length = 8
data = [@object_ids.num_shapes, @object_ids.max_spid].pack("VV")
add_mso_generic(type, version, @object_ids.drawings_saved, data, length)
end
#
# Write the Escher SpgrContainer record that is part of MSODRAWING.
#
def store_mso_spgr_container(length) #:nodoc:
type = 0xF003
version = 15
instance = 0
data = ''
add_mso_generic(type, version, instance, data, length)
end
#
# Write the Escher Spgr record that is part of MSODRAWING.
#
def store_mso_spgr #:nodoc:
type = 0xF009
version = 1
instance = 0
data = [0, 0, 0, 0].pack("VVVV")
length = 16
add_mso_generic(type, version, instance, data, length)
end
#
# Write the Escher Opt record that is part of MSODRAWING.
#
def store_mso_opt_chart #:nodoc:
type = 0xF00B
version = 3
instance = 9
data = ''
length = nil
data = store_mso_protection_and_text
data += [0x0181].pack('v') + # Fill Style -> fillColor
[0x0800004E].pack('V') +
[0x0183].pack('v') + # Fill Style -> fillBackColor
[0x0800004D].pack('V') +
[0x01BF].pack('v') + # Fill Style -> fNoFillHitTest
[0x00110010].pack('V') +
[0x01C0].pack('v') + # Line Style -> lineColor
[0x0800004D].pack('V') +
[0x01FF].pack('v') + # Line Style -> fNoLineDrawDash
[0x00080008].pack('V') +
[0x023F].pack('v') + # Shadow Style -> fshadowObscured
[0x00020000].pack('V') +
[0x03BF].pack('v') + # Group Shape -> fPrint
[0x00080000].pack('V')
add_mso_generic(type, version, instance, data, length)
end
#
# Write the Escher Opt record that is part of MSODRAWING.
#
def store_mso_opt_filter #:nodoc:
type = 0xF00B
version = 3
instance = 5
data = ''
length = nil
data = store_mso_protection_and_text
data += [0x01BF].pack('v') + # Fill Style -> fNoFillHitTest
[0x00010000].pack('V') +
[0x01FF].pack('v') + # Line Style -> fNoLineDrawDash
[0x00080000].pack('V') +
[0x03BF].pack('v') + # Group Shape -> fPrint
[0x000A0000].pack('V')
add_mso_generic(type, version, instance, data, length)
end
def store_mso_protection_and_text # :nodoc:
[0x007F].pack('v') + # Protection -> fLockAgainstGrouping
[0x01040104].pack('V') +
[0x00BF].pack('v') + # Text -> fFitTextToShape
[0x00080008].pack('V')
end
#
# Write the OBJ record that is part of image records.
# obj_id # Object ID number.
#
def store_obj_image(obj_id) #:nodoc:
record = 0x005D # Record identifier
length = 0x0026 # Bytes to follow
obj_type = 0x0008 # Object type (Picture).
data = '' # Record data.
sub_record = 0x0000 # Sub-record identifier.
sub_length = 0x0000 # Length of sub-record.
sub_data = '' # Data of sub-record.
options = 0x6011
reserved = 0x0000
# Add ftCmo (common object data) subobject
sub_record = 0x0015 # ftCmo
sub_length = 0x0012
sub_data = [obj_type, obj_id, options, reserved, reserved, reserved].pack('vvvVVV')
data = [sub_record, sub_length].pack('vv') + sub_data
# Add ftCf (Clipboard format) subobject
sub_record = 0x0007 # ftCf
sub_length = 0x0002
sub_data = [0xFFFF].pack( 'v')
data += [sub_record, sub_length].pack('vv') + sub_data
# Add ftPioGrbit (Picture option flags) subobject
sub_record = 0x0008 # ftPioGrbit
sub_length = 0x0002
sub_data = [0x0001].pack('v')
data += [sub_record, sub_length].pack('vv') + sub_data
# Add ftEnd (end of object) subobject
sub_record = 0x0000 # ftNts
sub_length = 0x0000
data += [sub_record, sub_length].pack('vv')
# Pack the record.
header = [record, length].pack('vv')
append(header, data)
end
#
# Write the OBJ record that is part of chart records.
# obj_id # Object ID number.
#
def store_obj_chart(obj_id) #:nodoc:
obj_type = 0x0005 # Object type (chart).
options = 0x6011
reserved = 0x0000
# Add ftCmo (common object data) subobject
sub_record = 0x0015 # ftCmo
sub_length = 0x0012
sub_data = [obj_type, obj_id, options, reserved, reserved, reserved].pack('vvvVVV')
data = [sub_record, sub_length].pack('vv') + sub_data
# Add ftEnd (end of object) subobject
sub_record = 0x0000 # ftNts
sub_length = 0x0000
data += [sub_record, sub_length].pack('vv')
# Pack the record.
record = 0x005D # Record identifier
length = 0x001A # Bytes to follow
header = [record, length].pack('vv')
append(header, data)
end
#
# Store the count of the DV records to follow.
#
# Note, this could be wrapped into store_dv() but we may require separate
# handling of the object id at a later stage.
#
def store_validation_count #:nodoc:
append(@validations.count_dv_record)
end
#
# Store the data_validation records.
#
def store_validations #:nodoc:
return if @validations.size == 0
@validations.each do |data_validation|
append(data_validation.dv_record)
end
end
def parser # :nodoc:
@workbook.parser
end
# Check for a cell reference in A1 notation and substitute row and column
def row_col_notation(args) # :nodoc:
if args[0] =~ /^\D/
substitute_cellref(*args)
else
args
end
end
end # class Worksheet
end # module Writeexcel
|
Radanisk/writeexcel
|
lib/writeexcel/outline.rb
|
module Writeexcel
class Worksheet < BIFFWriter
require 'writeexcel/helper'
class Outline
attr_accessor :row_level, :style, :below, :right
attr_writer :visible
def initialize
@row_level = 0
@style = 0
@below = 1
@right = 1
@visible = true
end
def visible?
!!@visible
end
end
end
end
|
Radanisk/writeexcel
|
examples/write_arrays.rb
|
<reponame>Radanisk/writeexcel
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
#######################################################################
#
# Example of how to use the WriteExcel module to
# write 1D and 2D arrays of data.
#
require 'writeexcel'
workbook = WriteExcel.new("write_arrays.xls")
worksheet1 = workbook.add_worksheet('Example 1')
worksheet2 = workbook.add_worksheet('Example 2')
worksheet3 = workbook.add_worksheet('Example 3')
worksheet4 = workbook.add_worksheet('Example 4')
worksheet5 = workbook.add_worksheet('Example 5')
worksheet6 = workbook.add_worksheet('Example 6')
worksheet7 = workbook.add_worksheet('Example 7')
worksheet8 = workbook.add_worksheet('Example 8')
format = workbook.add_format(:color => 'red', :bold => 1)
format_cmd = workbook.add_format(:color => 'blue', :bold => 1)
# Data arrays used in the following examples.
# undef values are written as blank cells (with format if specified).
#
array = [ 'one', 'two', nil, 'four' ]
array2d = [
['maggie', 'milly', 'molly', 'may' ],
[13, 14, 15, 16 ],
['shell', 'star', 'crab', 'stone'],
]
# 1. Write a row of data using an array.
#
# array[0] array[1] array[2]
worksheet1.write('A1', "worksheet1.write('A3', array)", format_cmd)
worksheet1.write('A3', array)
# 2. Write a data using an array of array.
#
# array[0]
# array[1]
# array[2]
worksheet2.write('A1', "worksheet2.write('A3', [ array ])", format_cmd)
worksheet2.write('A3', [ array ])
# 3. Write a row of data using an explicit write_row() method call.
# This is the same as calling write() in Ex. 1 above.
#
worksheet3.write('A1', "worksheet3.write_row('A3', array)", format_cmd)
worksheet3.write_row('A3', array)
# 4. Write a column of data using the write_col() method call.
# This is same as Ex. 2 above.
worksheet4.write('A1', "worksheet4.write_col('A3', array)", format_cmd)
worksheet4.write_col('A3', array)
# 5. Write a 2D array in col-row order.
# array[0][0] array[1][0] ...
# array[0][1] array[1][1] ...
# array[0][2] array[1][2] ...
worksheet5.write('A1', "worksheet5.write('A3', array2d)", format_cmd)
worksheet5.write('A3', array2d)
# 6. Write a 2D array in row-col order using array of 2D array.
# array[0][0] array[0][1] ...
# array[1][0] array[1][1] ...
# array[2][0] array[2][1] ...
worksheet6.write('A1', "worksheet6.write('A3', [ array2d ] )", format_cmd)
worksheet6.write('A3', [ array2d ] )
# 7. Write a 2D array in row-col order using write_col().
# This is same as Ex. 6 above.
worksheet7.write('A1', "worksheet7.write_col('A3', array2d)", format_cmd)
worksheet7.write_col('A3', array2d)
# 8. Write a row of data with formatting. The blank cell is also formatted.
worksheet8.write('A1', "worksheet8.write('A3', array, format)", format_cmd)
worksheet8.write('A3', array, format)
workbook.close
|
Radanisk/writeexcel
|
lib/writeexcel/shared_string_table.rb
|
class Workbook < BIFFWriter
require 'writeexcel/properties'
require 'writeexcel/helper'
class SharedString
attr_reader :string, :str_id
def initialize(string, str_id)
@string, @str_id = string, str_id
end
end
class SharedStringTable
attr_reader :str_total
def initialize
@shared_string_table = []
@string_to_shared_string = {}
@str_total = 0
end
def has_string?(string)
!!@string_to_shared_string[string]
end
def <<(string)
@str_total += 1
unless has_string?(string)
shared_string = SharedString.new(string, str_unique)
@shared_string_table << shared_string
@string_to_shared_string[string] = shared_string
end
id(string)
end
def strings
@shared_string_table.collect { |shared_string| shared_string.string }
end
def id(string)
@string_to_shared_string[string].str_id
end
def str_unique
@shared_string_table.size
end
def block_sizes
@block_sizes ||= calculate_block_sizes
end
#
# Handling of the SST continue blocks is complicated by the need to include an
# additional continuation byte depending on whether the string is split between
# blocks or whether it starts at the beginning of the block. (There are also
# additional complications that will arise later when/if Rich Strings are
# supported). As such we cannot use the simple CONTINUE mechanism provided by
# the add_continue() method in BIFFwriter.pm. Thus we have to make two passes
# through the strings data. The first is to calculate the required block sizes
# and the second, in store_shared_strings(), is to write the actual strings.
# The first pass through the data is also used to calculate the size of the SST
# and CONTINUE records for use in setting the BOUNDSHEET record offsets. The
# downside of this is that the same algorithm repeated in store_shared_strings.
#
def calculate_block_sizes
# Iterate through the strings to calculate the CONTINUE block sizes.
#
# The SST blocks requires a specialised CONTINUE block, so we have to
# ensure that the maximum data block size is less than the limit used by
# add_continue() in BIFFwriter.pm. For simplicity we use the same size
# for the SST and CONTINUE records:
# 8228 : Maximum Excel97 block size
# -4 : Length of block header
# -8 : Length of additional SST header information
# -8 : Arbitrary number to keep within add_continue() limit
# = 8208
#
continue_limit = 8208
block_length = 0
written = 0
block_sizes = []
continue = 0
strings.each do |string|
string_length = string.bytesize
# Block length is the total length of the strings that will be
# written out in a single SST or CONTINUE block.
#
block_length += string_length
# We can write the string if it doesn't cross a CONTINUE boundary
if block_length < continue_limit
written += string_length
next
end
# Deal with the cases where the next string to be written will exceed
# the CONTINUE boundary. If the string is very long it may need to be
# written in more than one CONTINUE record.
encoding = string.unpack("xx C")[0]
split_string = 0
while block_length >= continue_limit
header_length, space_remaining, align, split_string =
Workbook.split_string_setup(encoding, split_string, continue_limit, written, continue)
if space_remaining > header_length
# Write as much as possible of the string in the current block
written += space_remaining
# Reduce the current block length by the amount written
block_length -= continue_limit -continue -align
# Store the max size for this block
block_sizes.push(continue_limit -align)
# If the current string was split then the next CONTINUE block
# should have the string continue flag (grbit) set unless the
# split string fits exactly into the remaining space.
#
if block_length > 0
continue = 1
else
continue = 0
end
else
# Store the max size for this block
block_sizes.push(written +continue)
# Not enough space to start the string in the current block
block_length -= continue_limit -space_remaining -continue
continue = 0
end
# If the string (or substr) is small enough we can write it in the
# new CONTINUE block. Else, go through the loop again to write it in
# one or more CONTINUE blocks
#
if block_length < continue_limit
written = block_length
else
written = 0
end
end
end
# Store the max size for the last block unless it is empty
block_sizes.push(written +continue) if written +continue != 0
block_sizes
end
end
end
|
Radanisk/writeexcel
|
examples/bigfile.rb
|
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
###############################################################################
#
# Example of creating a WriteExcel that is larger than the
# default 7MB limit.
#
# It is exactly that same as any other WriteExcel program except
# that is requires that the OLE::Storage module is installed.
#
# reverse('©'), Jan 2007, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
workbook = WriteExcel.new('bigfile.xls')
worksheet = workbook.add_worksheet
worksheet.set_column(0, 50, 18)
0.upto(50) do |col|
0.upto(6000) do |row|
worksheet.write(row, col, "Row: #{row} Col: #{col}")
end
end
workbook.close
|
Radanisk/writeexcel
|
test/test_12_date_only.rb
|
# -*- coding: utf-8 -*-
###############################################################################
#
# A test for WriteExcel.
#
# Tests date and time handling. Tests dates in 1900 and 1904 format.
#
# reverse('©'), May 2004, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
############################################################################
require 'helper'
require 'stringio'
class ForTest
include ConvertDateTime
end
class TC_data_only < Test::Unit::TestCase
def setup
@obj = ForTest.new
end
def test_the_dates_generated_by_excel_1900
data_generated_excel_1900.each_line do |line|
line = line.sub(/^\s*/,'')
braak if line =~ /^\s*# stop/ # For debugging
next unless line =~ /\S/ # Ignore blank lines
next if line =~ /^\s*#/ # Ignore comments
result, number, date = analyze(line)
assert_equal(result.to_i, number,
"Testing convert_date_time: #{date} #{result}")
end
end
def test_the_dates_generated_by_excel_1904
data_generated_excel_1904.each_line do |line|
line = line.sub(/^\s*/,'')
braak if line =~ /^\s*# stop/ # For debugging
next unless line =~ /\S/ # Ignore blank lines
next if line =~ /^\s*#/ # Ignore comments
result, number, date = analyze(line, true)
assert_equal(result.to_i, number,
"Testing convert_date_time: #{date} #{result}")
end
end
def analyze(line, date_1904 = false)
count, date, result = line.split(/\s+/)
count = count.to_i
number = @obj.convert_date_time(date, date_1904)
number = -1 if number.nil?
[result, number, date]
end
def data_generated_excel_1904
return <<-__DATA_END__
#
# The following data was generated by Excel.
#
#
# Excel 1904 date system
#
201 1904-01-01T 0
202 1904-01-31T 30
203 1904-02-01T 31
204 1904-02-29T 59
205 1904-03-01T 60
206 1904-03-31T 90
207 1904-04-01T 91
208 1904-04-30T 120
209 1904-05-01T 121
210 1904-05-31T 151
211 1904-06-01T 152
212 1904-06-30T 181
213 1904-07-01T 182
214 1904-07-31T 212
215 1904-08-01T 213
216 1904-08-31T 243
217 1904-09-01T 244
218 1904-09-30T 273
219 1904-10-01T 274
220 1904-10-31T 304
221 1904-11-01T 305
222 1904-11-30T 334
223 1904-12-01T 335
224 1904-12-31T 365
225 1907-02-27T 1153
226 1907-02-28T 1154
227 1907-03-01T 1155
228 1907-03-02T 1156
229 1907-03-03T 1157
230 1907-03-04T 1158
231 1907-03-05T 1159
232 1907-03-06T 1160
233 1999-01-01T 34699
234 1999-01-31T 34729
235 1999-02-01T 34730
236 1999-02-28T 34757
237 1999-03-01T 34758
238 1999-03-31T 34788
239 1999-04-01T 34789
240 1999-04-30T 34818
241 1999-05-01T 34819
242 1999-05-31T 34849
243 1999-06-01T 34850
244 1999-06-30T 34879
245 1999-07-01T 34880
246 1999-07-31T 34910
247 1999-08-01T 34911
248 1999-08-31T 34941
249 1999-09-01T 34942
250 1999-09-30T 34971
251 1999-10-01T 34972
252 1999-10-31T 35002
253 1999-11-01T 35003
254 1999-11-30T 35032
255 1999-12-01T 35033
256 1999-12-31T 35063
257 2000-01-01T 35064
258 2000-01-31T 35094
259 2000-02-01T 35095
260 2000-02-29T 35123
261 2000-03-01T 35124
262 2000-03-31T 35154
263 2000-04-01T 35155
264 2000-04-30T 35184
265 2000-05-01T 35185
266 2000-05-31T 35215
267 2000-06-01T 35216
268 2000-06-30T 35245
269 2000-07-01T 35246
270 2000-07-31T 35276
271 2000-08-01T 35277
272 2000-08-31T 35307
273 2000-09-01T 35308
274 2000-09-30T 35337
275 2000-10-01T 35338
276 2000-10-31T 35368
277 2000-11-01T 35369
278 2000-11-30T 35398
279 2000-12-01T 35399
280 2000-12-31T 35429
281 2001-01-01T 35430
282 2001-01-31T 35460
283 2001-02-01T 35461
284 2001-02-28T 35488
285 2001-03-01T 35489
286 2001-03-31T 35519
287 2001-04-01T 35520
288 2001-04-30T 35549
289 2001-05-01T 35550
290 2001-05-31T 35580
291 2001-06-01T 35581
292 2001-06-30T 35610
293 2001-07-01T 35611
294 2001-07-31T 35641
295 2001-08-01T 35642
296 2001-08-31T 35672
297 2001-09-01T 35673
298 2001-09-30T 35702
299 2001-10-01T 35703
300 2001-10-31T 35733
301 2001-11-01T 35734
302 2001-11-30T 35763
303 2001-12-01T 35764
304 2001-12-31T 35794
305 2400-01-01T 181161
306 2400-01-31T 181191
307 2400-02-01T 181192
308 2400-02-29T 181220
309 2400-03-01T 181221
310 2400-03-31T 181251
311 2400-04-01T 181252
312 2400-04-30T 181281
313 2400-05-01T 181282
314 2400-05-31T 181312
315 2400-06-01T 181313
316 2400-06-30T 181342
317 2400-07-01T 181343
318 2400-07-31T 181373
319 2400-08-01T 181374
320 2400-08-31T 181404
321 2400-09-01T 181405
322 2400-09-30T 181434
323 2400-10-01T 181435
324 2400-10-31T 181465
325 2400-11-01T 181466
326 2400-11-30T 181495
327 2400-12-01T 181496
328 2400-12-31T 181526
329 4000-01-01T 765549
330 4000-01-31T 765579
331 4000-02-01T 765580
332 4000-02-29T 765608
333 4000-03-01T 765609
334 4000-03-31T 765639
335 4000-04-01T 765640
336 4000-04-30T 765669
337 4000-05-01T 765670
338 4000-05-31T 765700
339 4000-06-01T 765701
340 4000-06-30T 765730
341 4000-07-01T 765731
342 4000-07-31T 765761
343 4000-08-01T 765762
344 4000-08-31T 765792
345 4000-09-01T 765793
346 4000-09-30T 765822
347 4000-10-01T 765823
348 4000-10-31T 765853
349 4000-11-01T 765854
350 4000-11-30T 765883
351 4000-12-01T 765884
352 4000-12-31T 765914
353 4321-01-01T 882792
354 4321-01-31T 882822
355 4321-02-01T 882823
356 4321-02-28T 882850
357 4321-03-01T 882851
358 4321-03-31T 882881
359 4321-04-01T 882882
360 4321-04-30T 882911
361 4321-05-01T 882912
362 4321-05-31T 882942
363 4321-06-01T 882943
364 4321-06-30T 882972
365 4321-07-01T 882973
366 4321-07-31T 883003
367 4321-08-01T 883004
368 4321-08-31T 883034
369 4321-09-01T 883035
370 4321-09-30T 883064
371 4321-10-01T 883065
372 4321-10-31T 883095
373 4321-11-01T 883096
374 4321-11-30T 883125
375 4321-12-01T 883126
376 4321-12-31T 883156
377 9999-01-01T 2956639
378 9999-01-31T 2956669
379 9999-02-01T 2956670
380 9999-02-28T 2956697
381 9999-03-01T 2956698
382 9999-03-31T 2956728
383 9999-04-01T 2956729
384 9999-04-30T 2956758
385 9999-05-01T 2956759
386 9999-05-31T 2956789
387 9999-06-01T 2956790
388 9999-06-30T 2956819
389 9999-07-01T 2956820
390 9999-07-31T 2956850
391 9999-08-01T 2956851
392 9999-08-31T 2956881
393 9999-09-01T 2956882
394 9999-09-30T 2956911
395 9999-10-01T 2956912
396 9999-10-31T 2956942
397 9999-11-01T 2956943
398 9999-11-30T 2956972
399 9999-12-01T 2956973
400 9999-12-31T 2957003
#
# The following dates are invalid.
#
411 1899-12-31T -1 # Below year range.
412 1900-01-01T -1 # Below year range.
413 1903-12-31T -1 # Below year range.
414 2001-02-29T -1 # False leap-day.
415 2000-00-00T -1 # No month or day.
416 2000-01-00T -1 # No day.
417 2000-00-01T -1 # No month.
418 2000-13-01T -1 # Month out of range.
419 2000-12-32T -1 # Day out of range.
420 10000-01-01T -1 # Year out of range.
__DATA_END__
end
def data_generated_excel_1900
return <<-__DATA_END__
#
# The following data was generated by Excel.
#
#
# Excel 1900 date system
#
1 1899-12-31T 0
2 1900-01-00T 0
3 1900-01-01T 1
4 1900-02-27T 58
5 1900-02-28T 59
6 1900-02-29T 60
7 1900-03-01T 61
8 1900-03-02T 62
9 1900-03-11T 71
10 1900-04-08T 99
11 1900-09-12T 256
12 1901-05-03T 489
13 1901-10-13T 652
14 1902-02-15T 777
15 1902-06-06T 888
16 1902-09-25T 999
17 1902-09-27T 1001
18 1903-04-26T 1212
19 1903-08-05T 1313
20 1903-12-31T 1461
21 1904-01-01T 1462
22 1904-02-28T 1520
23 1904-02-29T 1521
24 1904-03-01T 1522
25 1907-02-27T 2615
26 1907-02-28T 2616
27 1907-03-01T 2617
28 1907-03-02T 2618
29 1907-03-03T 2619
30 1907-03-04T 2620
31 1907-03-05T 2621
32 1907-03-06T 2622
33 1999-01-01T 36161
34 1999-01-31T 36191
35 1999-02-01T 36192
36 1999-02-28T 36219
37 1999-03-01T 36220
38 1999-03-31T 36250
39 1999-04-01T 36251
40 1999-04-30T 36280
41 1999-05-01T 36281
42 1999-05-31T 36311
43 1999-06-01T 36312
44 1999-06-30T 36341
45 1999-07-01T 36342
46 1999-07-31T 36372
47 1999-08-01T 36373
48 1999-08-31T 36403
49 1999-09-01T 36404
50 1999-09-30T 36433
51 1999-10-01T 36434
52 1999-10-31T 36464
53 1999-11-01T 36465
54 1999-11-30T 36494
55 1999-12-01T 36495
56 1999-12-31T 36525
57 2000-01-01T 36526
58 2000-01-31T 36556
59 2000-02-01T 36557
60 2000-02-29T 36585
61 2000-03-01T 36586
62 2000-03-31T 36616
63 2000-04-01T 36617
64 2000-04-30T 36646
65 2000-05-01T 36647
66 2000-05-31T 36677
67 2000-06-01T 36678
68 2000-06-30T 36707
69 2000-07-01T 36708
70 2000-07-31T 36738
71 2000-08-01T 36739
72 2000-08-31T 36769
73 2000-09-01T 36770
74 2000-09-30T 36799
75 2000-10-01T 36800
76 2000-10-31T 36830
77 2000-11-01T 36831
78 2000-11-30T 36860
79 2000-12-01T 36861
80 2000-12-31T 36891
81 2001-01-01T 36892
82 2001-01-31T 36922
83 2001-02-01T 36923
84 2001-02-28T 36950
85 2001-03-01T 36951
86 2001-03-31T 36981
87 2001-04-01T 36982
88 2001-04-30T 37011
89 2001-05-01T 37012
90 2001-05-31T 37042
91 2001-06-01T 37043
92 2001-06-30T 37072
93 2001-07-01T 37073
94 2001-07-31T 37103
95 2001-08-01T 37104
96 2001-08-31T 37134
97 2001-09-01T 37135
98 2001-09-30T 37164
99 2001-10-01T 37165
100 2001-10-31T 37195
101 2001-11-01T 37196
102 2001-11-30T 37225
103 2001-12-01T 37226
104 2001-12-31T 37256
105 2400-01-01T 182623
106 2400-01-31T 182653
107 2400-02-01T 182654
108 2400-02-29T 182682
109 2400-03-01T 182683
110 2400-03-31T 182713
111 2400-04-01T 182714
112 2400-04-30T 182743
113 2400-05-01T 182744
114 2400-05-31T 182774
115 2400-06-01T 182775
116 2400-06-30T 182804
117 2400-07-01T 182805
118 2400-07-31T 182835
119 2400-08-01T 182836
120 2400-08-31T 182866
121 2400-09-01T 182867
122 2400-09-30T 182896
123 2400-10-01T 182897
124 2400-10-31T 182927
125 2400-11-01T 182928
126 2400-11-30T 182957
127 2400-12-01T 182958
128 2400-12-31T 182988
129 4000-01-01T 767011
130 4000-01-31T 767041
131 4000-02-01T 767042
132 4000-02-29T 767070
133 4000-03-01T 767071
134 4000-03-31T 767101
135 4000-04-01T 767102
136 4000-04-30T 767131
137 4000-05-01T 767132
138 4000-05-31T 767162
139 4000-06-01T 767163
140 4000-06-30T 767192
141 4000-07-01T 767193
142 4000-07-31T 767223
143 4000-08-01T 767224
144 4000-08-31T 767254
145 4000-09-01T 767255
146 4000-09-30T 767284
147 4000-10-01T 767285
148 4000-10-31T 767315
149 4000-11-01T 767316
150 4000-11-30T 767345
151 4000-12-01T 767346
152 4000-12-31T 767376
153 4321-01-01T 884254
154 4321-01-31T 884284
155 4321-02-01T 884285
156 4321-02-28T 884312
157 4321-03-01T 884313
158 4321-03-31T 884343
159 4321-04-01T 884344
160 4321-04-30T 884373
161 4321-05-01T 884374
162 4321-05-31T 884404
163 4321-06-01T 884405
164 4321-06-30T 884434
165 4321-07-01T 884435
166 4321-07-31T 884465
167 4321-08-01T 884466
168 4321-08-31T 884496
169 4321-09-01T 884497
170 4321-09-30T 884526
171 4321-10-01T 884527
172 4321-10-31T 884557
173 4321-11-01T 884558
174 4321-11-30T 884587
175 4321-12-01T 884588
176 4321-12-31T 884618
177 9999-01-01T 2958101
178 9999-01-31T 2958131
179 9999-02-01T 2958132
180 9999-02-28T 2958159
181 9999-03-01T 2958160
182 9999-03-31T 2958190
183 9999-04-01T 2958191
184 9999-04-30T 2958220
185 9999-05-01T 2958221
186 9999-05-31T 2958251
187 9999-06-01T 2958252
188 9999-06-30T 2958281
189 9999-07-01T 2958282
190 9999-07-31T 2958312
191 9999-08-01T 2958313
192 9999-08-31T 2958343
193 9999-09-01T 2958344
194 9999-09-30T 2958373
195 9999-10-01T 2958374
196 9999-10-31T 2958404
197 9999-11-01T 2958405
198 9999-11-30T 2958434
199 9999-12-01T 2958435
200 9999-12-31T 2958465
#
# The following dates are invalid.
#
401 0000-12-30T -1 # Below year range.
402 1000-12-30T -1 # Below year range.
403 1899-12-30T -1 # Below year range.
404 2002-02-29T -1 # False leap-day.
405 2000-00-00T -1 # No month or day.
406 2000-01-00T -1 # No day.
407 2000-00-01T -1 # No month.
408 2000-13-01T -1 # Month out of range.
409 2000-12-32T -1 # Day out of range.
410 10000-01-01T -1 # Year out of range.
__DATA_END__
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.