repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
Radanisk/writeexcel
|
test/test_worksheet.rb
|
<reponame>Radanisk/writeexcel
# -*- coding: utf-8 -*-
require 'helper'
require 'stringio'
class TC_Worksheet < Test::Unit::TestCase
TEST_DIR = File.expand_path(File.dirname(__FILE__))
PERL_OUTDIR = File.join(TEST_DIR, 'perl_output')
def setup
@test_file = StringIO.new
@workbook = WriteExcel.new(@test_file)
@sheetname = 'test'
@ws = @workbook.add_worksheet(@sheetname, 0)
@perldir = "#{PERL_OUTDIR}/"
@format = Writeexcel::Format.new(:color=>"green")
end
def teardown
if @workbook.instance_variable_get(:@filehandle)
@workbook.instance_variable_get(:@filehandle).close(true)
end
if @ws.instance_variable_get(:@filehandle)
@ws.instance_variable_get(:@filehandle).close(true)
end
end
def test_methods_exist
assert_respond_to(@ws, :write)
assert_respond_to(@ws, :write_blank)
assert_respond_to(@ws, :write_row)
assert_respond_to(@ws, :write_col)
end
def test_methods_no_error
assert_nothing_raised{ @ws.write(0,0,nil) }
assert_nothing_raised{ @ws.write(0,0,"Hello") }
assert_nothing_raised{ @ws.write(0,0,888) }
assert_nothing_raised{ @ws.write_row(0,0,["one","two","three"]) }
assert_nothing_raised{ @ws.write_row(0,0,[1,2,3]) }
assert_nothing_raised{ @ws.write_col(0,0,["one","two","three"]) }
assert_nothing_raised{ @ws.write_col(0,0,[1,2,3]) }
assert_nothing_raised{ @ws.write_blank(0,0,nil) }
assert_nothing_raised{ @ws.write_url(0,0,"http://www.ruby-lang.org") }
end
def test_write_syntax
assert_nothing_raised{@ws.write(0,0,"Hello")}
assert_nothing_raised{@ws.write(0,0,666)}
end
def test_store_dimensions
file = "delete_this"
File.open(file,"w+"){ |f| f.print @ws.__send__("store_dimensions") }
pf = @perldir + "ws_store_dimensions"
p_od = IO.readlines(pf).to_s.dump
r_od = IO.readlines(file).to_s.dump
assert_equal_filesize(pf ,file, "Invalid size for store_selection")
assert_equal(p_od, r_od,"Octal dumps are not identical")
File.delete(file)
end
def test_store_colinfo
colinfo = Writeexcel::Worksheet::ColInfo.new(0, 0, 8.43, nil, false, 0, false)
file = "delete_this"
File.open(file,"w+"){ |f| f.print @ws.__send__("store_colinfo", colinfo) }
pf = @perldir + "ws_store_colinfo"
p_od = IO.readlines(pf).to_s.dump
r_od = IO.readlines(file).to_s.dump
assert_equal_filesize(pf, file, "Invalid size for store_colinfo")
assert_equal(p_od,r_od,"Perl and Ruby octal dumps don't match")
File.delete(file)
end
def test_store_selection
file = "delete_this"
File.open(file,"w+"){ |f| f.print @ws.__send__("store_selection", 1,1,2,2) }
pf = @perldir + "ws_store_selection"
p_od = IO.readlines(pf).to_s.dump
r_od = IO.readlines(file).to_s.dump
assert_equal_filesize(pf, file, "Invalid size for store_selection")
assert_equal(p_od, r_od,"Octal dumps are not identical")
File.delete(file)
end
def test_store_filtermode
file = "delete_this"
File.open(file,"w+"){ |f| f.print @ws.__send__("store_filtermode") }
pf = @perldir + "ws_store_filtermode_off"
p_od = IO.readlines(pf).to_s.dump
r_od = IO.readlines(file).to_s.dump
assert_equal_filesize(pf, file, "Invalid size for store_filtermode_off")
assert_equal(p_od, r_od,"Octal dumps are not identical")
File.delete(file)
@ws.autofilter(1,1,2,2)
@ws.filter_column(1, 'x < 2000')
File.open(file,"w+"){ |f| f.print @ws.__send__("store_filtermode") }
pf = @perldir + "ws_store_filtermode_on"
p_od = IO.readlines(pf).to_s.dump
r_od = IO.readlines(file).to_s.dump
assert_equal_filesize(pf, file, "Invalid size for store_filtermode_off")
assert_equal(p_od, r_od,"Octal dumps are not identical")
File.delete(file)
end
def test_new
assert_equal(@sheetname, @ws.name)
end
def test_write_url_should_not_change_internal_url_string
internal_url = 'internal:Sheet2!A1'
@ws.write_url(0, 0, internal_url)
assert_equal('internal:Sheet2!A1', internal_url)
end
def test_write_url_should_not_change_external_url_string
external_url = 'external:c:\temp\foo.xls#Sheet2!A1'
@ws.write_url(1, 1, external_url)
assert_equal('external:c:\temp\foo.xls#Sheet2!A1', external_url)
end
def test_write_url_should_not_change_external_net_url_string
external_net_url = 'external://NETWORK/share/foo.xls'
@ws.write_url(1, 1, external_net_url)
assert_equal('external://NETWORK/share/foo.xls', external_net_url)
end
def assert_equal_filesize(target, test, msg = "Bad file size")
assert_equal(File.size(target),File.size(test),msg)
end
end
|
Radanisk/writeexcel
|
test/test_workbook.rb
|
# -*- coding: utf-8 -*-
require 'helper'
require "stringio"
class TC_Workbook < Test::Unit::TestCase
def setup
@test_file = StringIO.new
@workbook = Workbook.new(@test_file)
end
def test_new
assert_kind_of(Workbook, @workbook)
end
def test_add_worksheet
sheetnames = ['sheet1', 'sheet2']
(0 .. sheetnames.size-1).each do |i|
sheets = @workbook.sheets
assert_equal(i, sheets.size)
@workbook.add_worksheet(sheetnames[i])
sheets = @workbook.sheets
assert_equal(i+1, sheets.size)
end
end
def test_set_tempdir_after_sheet_added
# after shees added, call set_tempdir raise RuntimeError
@workbook.add_worksheet('name')
assert_raise(RuntimeError, "already sheet exists, but set_tempdir() doesn't raise"){
@workbook.set_tempdir
}
end
def test_set_tempdir_with_invalid_dir
# invalid dir raise RuntimeError
while true do
dir = Time.now.to_s
break unless FileTest.directory?(dir)
sleep 0.1
end
assert_raise(RuntimeError, "set_tempdir() doesn't raise invalid dir:#{dir}."){
@workbook.set_tempdir(dir)
}
end
def test_check_sheetname
worksheet1 = @workbook.add_worksheet # implicit name 'Sheet1'
worksheet2 = @workbook.add_worksheet # implicit name 'Sheet2'
worksheet3 = @workbook.add_worksheet 'Sheet3' # explicit name 'Sheet3'
worksheet4 = @workbook.add_worksheet 'Sheetz' # explicit name 'Sheetz'
valid_sheetnames.each do |test|
target = test[0]
sheetname = test[1]
caption = test[2]
assert_nothing_raised { @workbook.add_worksheet(sheetname) }
end
invalid_sheetnames.each do |test|
target = test[0]
sheetname = test[1]
caption = test[2]
assert_raise(RuntimeError, "sheetname: #{sheetname}") {
@workbook.add_worksheet(sheetname)
}
end
end
def test_check_sheetname_raise_if_same_utf16be_sheet_name
smily = [0x263a].pack('n')
@workbook.add_worksheet(smily, true)
assert_raise(RuntimeError) { @workbook.add_worksheet(smily, true)}
end
def test_check_sheetname_utf8_only
['Лист 1', 'Лист 2', 'Лист 3'].each do |sheetname|
assert_nothing_raised { @workbook.add_worksheet(sheetname) }
end
end
def test_check_unicode_bytes_even
assert_nothing_raised(RuntimeError){ @workbook.add_worksheet('ab', 1)}
assert_raise(RuntimeError){ @workbook.add_worksheet('abc', 1)}
end
def test_raise_set_compatibility_after_sheet_creation
@workbook.add_worksheet
assert_raise(RuntimeError) { @workbook.compatibility_mode }
end
def valid_sheetnames
[
# Tests for valid names
[ 'PASS', nil, 'No worksheet name' ],
[ 'PASS', '', 'Blank worksheet name' ],
[ 'PASS', 'Sheet10', 'Valid worksheet name' ],
[ 'PASS', 'a' * 31, 'Valid 31 char name' ]
]
end
def invalid_sheetnames
[
# Tests for invalid names
[ 'FAIL', 'Sheet1', 'Caught duplicate name' ],
[ 'FAIL', 'Sheet2', 'Caught duplicate name' ],
[ 'FAIL', 'Sheet3', 'Caught duplicate name' ],
[ 'FAIL', 'sheet1', 'Caught case-insensitive name'],
[ 'FAIL', 'SHEET1', 'Caught case-insensitive name'],
[ 'FAIL', 'sheetz', 'Caught case-insensitive name'],
[ 'FAIL', 'SHEETZ', 'Caught case-insensitive name'],
[ 'FAIL', 'a' * 32, 'Caught long name' ],
[ 'FAIL', '[', 'Caught invalid char' ],
[ 'FAIL', ']', 'Caught invalid char' ],
[ 'FAIL', ':', 'Caught invalid char' ],
[ 'FAIL', '*', 'Caught invalid char' ],
[ 'FAIL', '?', 'Caught invalid char' ],
[ 'FAIL', '/', 'Caught invalid char' ],
[ 'FAIL', '\\', 'Caught invalid char' ]
]
end
def test_add_format_must_accept_one_or_more_hash_params
font = {
:font => 'MS 明朝',
:size => 12,
:color => 'blue',
:bold => 1
}
shading = {
:bg_color => 'green',
:pattern => 1
}
properties = font.merge(shading)
format1 = @workbook.add_format(properties)
format2 = @workbook.add_format(font, shading)
assert(format_equal?(format1, format2))
end
def format_equal?(f1, f2)
require 'yaml'
re = /xf_index: \d+\n/
YAML.dump(f1).sub(re, '') == YAML.dump(f2).sub(re, '')
end
end
|
Radanisk/writeexcel
|
examples/indent.rb
|
<filename>examples/indent.rb
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
##############################################################################
#
# A simple formatting example using Spreadsheet::WriteExcel.
#
# This program demonstrates the indentation cell format.
#
# reverse('©'), May 2004, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
workbook = WriteExcel.new('indent.xls')
worksheet = workbook.add_worksheet()
indent1 = workbook.add_format(:indent => 1)
indent2 = workbook.add_format(:indent => 2)
worksheet.set_column('A:A', 40)
worksheet.write('A1', "This text is indented 1 level", indent1)
worksheet.write('A2', "This text is indented 2 levels", indent2)
workbook.close
|
Radanisk/writeexcel
|
lib/writeexcel/data_validations.rb
|
module Writeexcel
class Worksheet < BIFFWriter
require 'writeexcel/helper'
class DataValidations < Array
#
# 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 count_dv_record #:nodoc:
return if empty?
dval_record(-1, size) # obj_id = -1
end
private
#
# Store the DV record which contains the number of and information common to
# all DV structures.
# obj_id # Object ID number.
# dv_count # Count of DV structs to follow.
#
def dval_record(obj_id, dv_count) #:nodoc:
record = 0x01B2 # Record identifier
length = 0x0012 # Bytes to follow
flags = 0x0004 # Option flags.
x_coord = 0x00000000 # X coord of input box.
y_coord = 0x00000000 # Y coord of input box.
# Pack the record.
header = [record, length].pack('vv')
data = [flags, x_coord, y_coord, obj_id, dv_count].pack('vVVVV')
header + data
end
end
require 'writeexcel/convert_date_time'
class DataValidation
include ConvertDateTime
def initialize(parser = nil, param = {})
@parser = parser
@cells = param[:cells]
@validate = param[:validate]
@criteria = param[:criteria]
@value = param[:value]
@maximum = param[:maximum]
@input_title = param[:input_title]
@input_message = param[:input_message]
@error_title = param[:error_title]
@error_message = param[:error_message]
@error_type = param[:error_type]
@ignore_blank = param[:ignore_blank]
@dropdown = param[:dropdown]
@show_input = param[:show_input]
@show_error = param[:show_error]
end
#
# Calclate the DV record that specifies the data validation criteria and options
# for a range of cells..
# cells # Aref of cells to which DV applies.
# validate # Type of data validation.
# criteria # Validation criteria.
# value # Value/Source/Minimum formula.
# maximum # Maximum formula.
# input_title # Title of input message.
# input_message # Text of input message.
# error_title # Title of error message.
# error_message # Text of input message.
# error_type # Error dialog type.
# ignore_blank # Ignore blank cells.
# dropdown # Display dropdown with list.
# input_box # Display input box.
# error_box # Display error box.
#
def dv_record # :nodoc:
record = 0x01BE # Record identifier
flags = 0x00000000 # DV option flags.
ime_mode = 0 # IME input mode for far east fonts.
str_lookup = 0 # See below.
# Set the string lookup flag for 'list' validations with a string array.
str_lookup = @validate == 3 && @value.respond_to?(:to_ary) ? 1 : 0
# The dropdown flag is stored as a negated value.
no_dropdown = @dropdown ? 0 : 1
# Set the required flags.
flags |= @validate
flags |= @error_type << 4
flags |= str_lookup << 7
flags |= @ignore_blank << 8
flags |= no_dropdown << 9
flags |= ime_mode << 10
flags |= @show_input << 18
flags |= @show_error << 19
flags |= @criteria << 20
# Pack the DV cell data.
dv_data = @cells.inject([@cells.size].pack('v')) do |result, range|
result + [range[0], range[2], range[1], range[3]].pack('vvvv')
end
# Pack the record.
data = [flags].pack('V') +
pack_dv_string(@input_title, 32 ) +
pack_dv_string(@error_title, 32 ) +
pack_dv_string(@input_message, 255) +
pack_dv_string(@error_message, 255) +
pack_dv_formula(@value) +
pack_dv_formula(@maximum) +
dv_data
header = [record, data.bytesize].pack('vv')
header + data
end
def self.factory(parser, date_1904, *args)
# Check for a valid number of args.
return -1 if args.size != 5 && args.size != 3
# The final hashref contains the validation parameters.
param = args.pop
# 'validate' is a required parameter.
return -3 unless param.has_key?(:validate)
# Make the last row/col the same as the first if not defined.
row1, col1, row2, col2 = args
row2, col2 = row1, col1 unless row2
# List of valid input parameters.
obj = DataValidation.new
valid_parameter = obj.valid_parameter_of_data_validation
# Check for valid input parameters.
param.each_key { |param_key| return -3 unless valid_parameter.has_key?(param_key) }
# Map alternative parameter names 'source' or 'minimum' to 'value'.
param[:value] = param[:source] if param[:source]
param[:value] = param[:minimum] if param[:minimum]
# Check for valid validation types.
unless obj.valid_validation_type.has_key?(param[:validate].downcase)
return -3
else
param[:validate] = obj.valid_validation_type[param[:validate].downcase]
end
# No action is required for validation type 'any'.
# TODO: we should perhaps store 'any' for message only validations.
return 0 if param[:validate] == 0
# The list and custom validations don't have a criteria so we use a default
# of 'between'.
if param[:validate] == 3 || param[:validate] == 7
param[:criteria] = 'between'
param[:maximum] = nil
end
# 'criteria' is a required parameter.
unless param.has_key?(:criteria)
# carp "Parameter 'criteria' is required in data_validation()";
return -3
end
# Check for valid criteria types.
unless obj.valid_criteria_type.has_key?(param[:criteria].downcase)
return -3
else
param[:criteria] = obj.valid_criteria_type[param[:criteria].downcase]
end
# 'Between' and 'Not between' criteria require 2 values.
if param[:criteria] == 0 || param[:criteria] == 1
unless param.has_key?(:maximum)
return -3
end
else
param[:maximum] = nil
end
# Check for valid error dialog types.
if not param.has_key?(:error_type)
param[:error_type] = 0
elsif not obj.valid_error_type.has_key?(param[:error_type].downcase)
return -3
else
param[:error_type] = obj.valid_error_type[param[:error_type].downcase]
end
# Convert date/times value if required.
if param[:validate] == 4 || param[:validate] == 5
if param[:value] =~ /T/
param[:value] = obj.convert_date_time(param[:value], date_1904) || raise("invalid :value: #{param[:value]}")
end
if param[:maximum] && param[:maximum] =~ /T/
param[:maximum] = obj.convert_date_time(param[:maximum], date_1904) || raise("invalid :maximum: #{param[:maximum]}")
end
end
# Set some defaults if they haven't been defined by the user.
param[:ignore_blank] = 1 unless param[:ignore_blank]
param[:dropdown] = 1 unless param[:dropdown]
param[:show_input] = 1 unless param[:show_input]
param[:show_error] = 1 unless param[:show_error]
# These are the cells to which the validation is applied.
param[:cells] = [[row1, col1, row2, col2]]
# A (for now) undocumented parameter to pass additional cell ranges.
if param.has_key?(:other_cells)
param[:cells].push(param[:other_cells])
end
DataValidation.new(parser, param)
end
#
# Pack the strings used in the input and error dialog captions and messages.
# Captions are limited to 32 characters. Messages are limited to 255 chars.
#
def pack_dv_string(string, max_length) #:nodoc:
# The default empty string is "\0".
string = ruby_18 { "\0" } || ruby_19 { "\0".encode('BINARY') } unless string && string != ''
# Excel limits DV captions to 32 chars and messages to 255.
string = string[0 .. max_length-1] if string.bytesize > max_length
ruby_19 { string = convert_to_ascii_if_ascii(string) }
# Handle utf8 strings
if is_utf8?(string)
str_length = string.gsub(/[^\Wa-zA-Z_\d]/, ' ').bytesize # jlength
string = utf8_to_16le(string)
encoding = 1
else
str_length = string.bytesize
encoding = 0
end
ruby_18 { [str_length, encoding].pack('vC') + string } ||
ruby_19 { [str_length, encoding].pack('vC') + string.force_encoding('BINARY') }
end
#
# Pack the formula used in the DV record. This is the same as an cell formula
# with some additional header information. Note, DV formulas in Excel use
# relative addressing (R1C1 and ptgXxxN) however we use the Formula.pm's
# default absolute addressing (A1 and ptgXxx).
#
def pack_dv_formula(formula) #:nodoc:
unused = 0x0000
# Return a default structure for unused formulas.
return [0, unused].pack('vv') unless formula && formula != ''
# Pack a list array ref as a null separated string.
formula = %!"#{formula.join("\0")}"! if formula.respond_to?(:to_ary)
# Strip the = sign at the beginning of the formula string
formula = formula.to_s unless formula.respond_to?(:to_str)
# 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
# }
# else {
# # TODO test for non valid ptgs such as Sheet2!A1
# }
# Force 2d ranges to be a reference class.
tokens.each do |t|
t.sub!(/_range2d/, "_range2dR")
t.sub!(/_name/, "_nameR")
end
# Parse the tokens into a formula string.
formula = @parser.parse_tokens(tokens)
[formula.length, unused].pack('vv') + formula
end
def valid_parameter_of_data_validation
{
:validate => 1,
:criteria => 1,
:value => 1,
:source => 1,
:minimum => 1,
:maximum => 1,
:ignore_blank => 1,
:dropdown => 1,
:show_input => 1,
:input_title => 1,
:input_message => 1,
:show_error => 1,
:error_title => 1,
:error_message => 1,
:error_type => 1,
:other_cells => 1
}
end
def valid_validation_type
{
'any' => 0,
'any value' => 0,
'whole number' => 1,
'whole' => 1,
'integer' => 1,
'decimal' => 2,
'list' => 3,
'date' => 4,
'time' => 5,
'text length' => 6,
'length' => 6,
'custom' => 7
}
end
def valid_criteria_type
{
'between' => 0,
'not between' => 1,
'equal to' => 2,
'=' => 2,
'==' => 2,
'not equal to' => 3,
'!=' => 3,
'<>' => 3,
'greater than' => 4,
'>' => 4,
'less than' => 5,
'<' => 5,
'greater than or equal to' => 6,
'>=' => 6,
'less than or equal to' => 7,
'<=' => 7
}
end
def valid_error_type
{
'stop' => 0,
'warning' => 1,
'information' => 2
}
end
end
end
end
|
Radanisk/writeexcel
|
charts/demo2.rb
|
#!/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 pie chart extracted from the file Chart2.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("demo2.xls")
worksheet = workbook.add_worksheet
# Add the chart extracted using the chartex utility
chart = workbook.add_chart_ext('demo201.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)
chart_font_4 = workbook.add_format(:font_only => 1)
chart_font_5 = workbook.add_format(:font_only => 1)
# Add all other formats (if any).
bold = workbook.add_format(:bold => 1)
# Adjust column widths and add some headers
worksheet.set_column('A:B', 20)
worksheet.write('A1', 'Module', bold)
worksheet.write('B1', 'No. of lines', bold)
# Add data to range that the chart refers to.
data = [
['BIFFwriter.pm', 275],
['Big.pm', 99],
['Chart.pm', 269],
['Format.pm', 724],
['Formula.pm', 1410],
['OLEwriter.pm', 447],
['Utility.pm', 884],
['Workbook.pm', 1925],
['WorkbookBig.pm', 112],
['Worksheet.pm', 3945]
]
worksheet.write_col('A2', data )
workbook.close
|
Radanisk/writeexcel
|
charts/chartex.rb
|
<reponame>Radanisk/writeexcel<gh_stars>10-100
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
#######################################################################
#
# chartex - A utility to extract charts from an Excel file for
# insertion into a WriteExcel file.
#
# reverse('ゥ'), September 2007, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
# Documentation after __END__
#
require 'writeexcel'
class Chartex
attr_reader :file
def initialize(file = nil)
@file = file
@sheetnames = Array.new
@exrefs = Array.new
@buf = StringIO.new
end
def set_file(file)
@file = file
end
def get_workbook(file = nil)
file ||= @file
ole = OLEStorageLite.new(file)
book97 = 'Workbook'.unpack('C*').pack('v*')
workbook = ole.getPpsSearch([book97], 1, 1)[0]
@buf.write(workbook.data)
@buf.rewind
workbook
end
end
# main
if $0 == __FILE__
end
=begin
my $man = 0;
my $help = 0;
my $in_chart = 0;
my $chart_name = 'chart';
my $chart_index = 1;
my $sheet_index = -1;
my @sheetnames;
my @exrefs;
my $depth_count = 0;
my $max_font = 0;
#
# Do the Getopt and Pod::Usage routines.
#
GetOptions(
'help|?' => \$help,
'man' => \$man,
'chart=s' => \$chart_name,
) or pod2usage(2);
pod2usage(1) if $help;
pod2usage(-verbose => 2) if $man;
# From the Pod::Usage pod:
# If no arguments were given, then allow STDIN to be used only
# if it's not connected to a terminal (otherwise print usage)
pod2usage() if @ARGV == 0 && -t STDIN;
# Check that the file can be opened because OLE::Storage_Lite won't tell us.
# Possible race condition here. Could fix with latest OLE::Storage_Lite. TODO.
#
my $file = $ARGV[0];
open TMP, $file or die "Couldn't open $file. $!\n";
close TMP;
my $ole = OLE::Storage_Lite->new($file);
my $book97 = pack 'v*', unpack 'C*', 'Workbook';
my $workbook = ($ole->getPpsSearch([$book97], 1, 1))[0];
die "Couldn't find Excel97 data in file $file.\n" unless $workbook;
# Write the data to a file so that we can access it with read().
my $tmpfile = IO::File->new_tmpfile();
binmode $tmpfile;
my $biff = $workbook->{Data};
print {$tmpfile} $biff;
seek $tmpfile, 0, 0;
my $header;
my $data;
# Read the file record by record and look for a chart BOF record.
#
while (read $tmpfile, $header, 4) {
my ($record, $length) = unpack "vv", $header;
next unless $record;
read $tmpfile, $data, $length;
# BOUNDSHEET
if ($record == 0x0085) {
push @sheetnames, substr $data, 8;
}
# EXTERNSHEET
if ($record == 0x0017) {
my $count = unpack 'v', $data;
for my $i (1 .. $count) {
my @tmp = unpack 'vvv', substr($data, 2 +6*($i-1));
push @exrefs, [@tmp];
}
}
# BOF
if ($record == 0x0809) {
my $type = unpack 'xx v', $data;
if ($type == 0x0020) {
my $filename = sprintf "%s%02d.bin", $chart_name, $chart_index;
open CHART, ">$filename" or die "Couldn't open $filename: $!";
binmode CHART;
my $sheet_name = $sheetnames[$sheet_index];
$sheet_name .= ' embedded' if $depth_count;
printf "\nExtracting \%s\ to %s", $sheet_name, $filename;
$in_chart = 1;
$chart_index++;
}
$depth_count++;
}
# FBI, Chart fonts
if ($record == 0x1060) {
my $index = substr $data, 8, 2, '';
$index = unpack 'v', $index;
# Ignore the inbuilt fonts.
if ($index >= 5) {
$max_font = $index if $index > $max_font;
# Shift index past S::WE fonts
$index += 2;
}
$data .= pack 'v', $index;
}
# FONTX, Chart fonts
if ($record == 0x1026) {
my $index = unpack 'v', $data;
# Ignore the inbuilt fonts.
if ($index >= 5) {
$max_font = $index if $index > $max_font;
# Shift index past S::WE fonts
$index += 2;
}
$data = pack 'v', $index;
}
if ($in_chart) {
print CHART $header, $data;
}
# EOF
if ($record == 0x000A) {
$in_chart = 0;
$depth_count--;
$sheet_index++ if $depth_count == 0;
;
}
}
if ($chart_index > 1) {
print "\n\n";
print "Add the following near the start of your program\n";
print "and change the variable names if required.\n\n";
}
else {
print "\nNo charts found in workbook\n";
}
for my $aref (@exrefs) {
my $sheet1 = $sheetnames[$aref->[1]];
my $sheet2 = $sheetnames[$aref->[2]];
my $range;
if ($sheet1 ne $sheet2) {
$range = $sheet1 . ":" . $sheet2;
}
else {
$range = $sheet1;
}
$range = "'$range'" if $range =~ /[^\w:]/;
print " \$worksheet->store_formula('=$range!A1');\n";
}
print "\n";
for my $i (5 .. $max_font) {
printf " my \$chart_font_%d = \$workbook->add_format(font_only => 1);\n",
$i -4;
}
__END__
=head1 NAME
chartex - A utility to extract charts from an Excel file for insertion into a Spreadsheet::WriteExcel file.
=head1 DESCRIPTION
This program is used for extracting one or more charts from an Excel file in binary format. The charts can then be included in a C<Spreadsheet::WriteExcel> file.
See the C<add_chart_ext()> section of the Spreadsheet::WriteExcel documentation for more details.
=head1 SYNOPSIS
chartex [--chartname --help --man] file.xls
Options:
--chartname -c The root name for the extracted charts,
defaults to "chart".
=head1 OPTIONS
=over 4
=item B<--chartname or -c>
This sets the root name for the extracted charts, defaults to "chart". For example:
$ chartex file.xls
Extracting "Chart1" to chart01.bin
$ chartex -c mychart file.xls
Extracting "Chart1" to mychart01.bin
=item B<--help or -h>
Print a brief help message and exits.
=item B<--man or -m>
Prints the manual page and exits.
=back
=head1 AUTHOR
<NAME> <EMAIL>
=head1 VERSION
Version 0.02.
=head1 COPYRIGHT
ゥ MMV, <NAME>.
All Rights Reserved. This program is free software. It may be used, redistributed and/or modified under the same terms as Perl itself.
=cut
=end
|
Radanisk/writeexcel
|
test/test_biff.rb
|
# -*- coding: utf-8 -*-
require 'helper'
require 'stringio'
class TC_BIFFWriter < Test::Unit::TestCase
TEST_DIR = File.expand_path(File.dirname(__FILE__))
PERL_OUTDIR = File.join(TEST_DIR, 'perl_output')
def setup
@biff = BIFFWriter.new
@ruby_file = StringIO.new
end
def test_append_no_error
assert_nothing_raised{ @biff.append("World") }
end
def test_prepend_no_error
assert_nothing_raised{ @biff.prepend("Hello") }
end
def test_data_added
assert_nothing_raised{ @biff.append("Hello", "World") }
data = ''
while d = @biff.get_data
data += d
end
assert_equal("HelloWorld", data, "Bad data contents")
assert_equal(10, @biff.datasize, "Bad data size")
end
def test_data_prepended
assert_nothing_raised{ @biff.append("Hello") }
assert_nothing_raised{ @biff.prepend("World") }
data = ''
while d = @biff.get_data
data += d
end
assert_equal("WorldHello", data, "Bad data contents")
assert_equal(10, @biff.datasize, "Bad data size")
end
def test_store_bof_length
assert_nothing_raised{ @biff.store_bof }
assert_equal(20, @biff.datasize, "Bad data size after store_bof call")
end
def test_store_eof_length
assert_nothing_raised{ @biff.store_eof }
assert_equal(4, @biff.datasize, "Bad data size after store_eof call")
end
def test_datasize_mixed
assert_nothing_raised{ @biff.append("Hello") }
assert_nothing_raised{ @biff.prepend("World") }
assert_nothing_raised{ @biff.store_bof }
assert_nothing_raised{ @biff.store_eof }
assert_equal(34, @biff.datasize, "Bad data size for mixed data")
end
def test_add_continue
perl_file = "#{PERL_OUTDIR}/biff_add_continue_testdata"
size = File.size(perl_file)
@ruby_file.print(@biff.add_continue('testdata'))
rsize = @ruby_file.size
assert_equal(size, rsize, "File sizes not the same")
compare_file(perl_file, @ruby_file)
end
end
|
Radanisk/writeexcel
|
examples/autofilter.rb
|
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
#######################################################################
#
# Example of how to create autofilters with WriteExcel.
#
# reverse('©'), September 2007, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
def get_data
[
['East', 'Apple', 9000, 'July'],
['East', 'Apple', 5000, 'July'],
['South', 'Orange', 9000, 'September'],
['North', 'Apple', 2000, 'November'],
['West', 'Apple', 9000, 'November'],
['South', 'Pear', 7000, 'October'],
['North', 'Pear', 9000, 'August'],
['West', 'Orange', 1000, 'December'],
['West', 'Grape', 1000, 'November'],
['South', 'Pear', 10000, 'April'],
['West', 'Grape', 6000, 'January'],
['South', 'Orange', 3000, 'May'],
['North', 'Apple', 3000, 'December'],
['South', 'Apple', 7000, 'February'],
['West', 'Grape', 1000, 'December'],
['East', 'Grape', 8000, 'February'],
['South', 'Grape', 10000, 'June'],
['West', 'Pear', 7000, 'December'],
['South', 'Apple', 2000, 'October'],
['East', 'Grape', 7000, 'December'],
['North', 'Grape', 6000, 'April'],
['East', 'Pear', 8000, 'February'],
['North', 'Apple', 7000, 'August'],
['North', 'Orange', 7000, 'July'],
['North', 'Apple', 6000, 'June'],
['South', 'Grape', 8000, 'September'],
['West', 'Apple', 3000, 'October'],
['South', 'Orange', 10000, 'November'],
['West', 'Grape', 4000, 'July'],
['North', 'Orange', 5000, 'August'],
['East', 'Orange', 1000, 'November'],
['East', 'Orange', 4000, 'October'],
['North', 'Grape', 5000, 'August'],
['East', 'Apple', 1000, 'December'],
['South', 'Apple', 10000, 'March'],
['East', 'Grape', 7000, 'October'],
['West', 'Grape', 1000, 'September'],
['East', 'Grape', 10000, 'October'],
['South', 'Orange', 8000, 'March'],
['North', 'Apple', 4000, 'July'],
['South', 'Orange', 5000, 'July'],
['West', 'Apple', 4000, 'June'],
['East', 'Apple', 5000, 'April'],
['North', 'Pear', 3000, 'August'],
['East', 'Grape', 9000, 'November'],
['North', 'Orange', 8000, 'October'],
['East', 'Apple', 10000, 'June'],
['South', 'Pear', 1000, 'December'],
['North', 'Grape', 10000, 'July'],
['East', 'Grape', 6000, 'February'],
]
end
#######################################################################
#
# Main
#
xlsfile = 'autofilter.xls'
workbook = WriteExcel.new(xlsfile)
worksheet1 = workbook.add_worksheet
worksheet2 = workbook.add_worksheet
worksheet3 = workbook.add_worksheet
worksheet4 = workbook.add_worksheet
worksheet5 = workbook.add_worksheet
worksheet6 = workbook.add_worksheet
bold = workbook.add_format(:bold => 1)
# Extract the data embedded at the end of this file.
headings = %w(Region Item Volume Month)
data = get_data
# Set up several sheets with the same data.
workbook.sheets.each do |worksheet|
worksheet.set_column('A:D', 12)
worksheet.set_row(0, 20, bold)
worksheet.write('A1', headings)
end
###############################################################################
#
# Example 1. Autofilter without conditions.
#
worksheet1.autofilter('A1:D51')
worksheet1.write('A2', [data])
###############################################################################
#
#
# Example 2. Autofilter with a filter condition in the first column.
#
# The range in this example is the same as above but in row-column notation.
worksheet2.autofilter(0, 0, 50, 3)
# The placeholder "Region" in the filter is ignored and can be any string
# that adds clarity to the expression.
#
worksheet2.filter_column(0, 'Region eq East')
#
# Hide the rows that don't match the filter criteria.
#
row = 1
data.each do |row_data|
region = row_data[0]
if region == 'East'
# Row is visible.
else
# Hide row.
worksheet2.set_row(row, nil, nil, 1)
end
worksheet2.write(row, 0, row_data)
row += 1
end
###############################################################################
#
#
# Example 3. Autofilter with a dual filter condition in one of the columns.
#
worksheet3.autofilter('A1:D51')
worksheet3.filter_column('A', 'x eq East or x eq South')
#
# Hide the rows that don't match the filter criteria.
#
row = 1
data.each do |row_data|
region = row_data[0]
if region == 'East' || region == 'South'
# Row is visible.
else
# Hide row.
worksheet3.set_row(row, nil, nil, 1)
end
worksheet3.write(row, 0, row_data)
row += 1
end
###############################################################################
#
#
# Example 4. Autofilter with filter conditions in two columns.
#
worksheet4.autofilter('A1:D51')
worksheet4.filter_column('A', 'x eq East')
worksheet4.filter_column('C', 'x > 3000 and x < 8000' )
#
# Hide the rows that don't match the filter criteria.
#
row = 1
data.each do |row_data|
region = row_data[0]
volume = row_data[2]
if region == 'East' && volume > 3000 && volume < 8000
# Row is visible.
else
# Hide row.
worksheet4.set_row(row, nil, nil, 1)
end
worksheet4.write(row, 0, row_data)
row += 1
end
###############################################################################
#
#
# Example 5. Autofilter with filter for blanks.
#
# Create a blank cell in our test data.
data[5][0] = ''
worksheet5.autofilter('A1:D51')
worksheet5.filter_column('A', 'x == Blanks')
#
# Hide the rows that don't match the filter criteria.
#
row = 1
data.each do |row_data|
region = row_data[0]
if region == ''
# Row is visible.
else
# Hide row.
worksheet5.set_row(row, nil, nil, 1)
end
worksheet5.write(row, 0, row_data)
row += 1
end
###############################################################################
#
#
# Example 6. Autofilter with filter for non-blanks.
#
worksheet6.autofilter('A1:D51')
worksheet6.filter_column('A', 'x == NonBlanks')
#
# Hide the rows that don't match the filter criteria.
#
row = 1
data.each do |row_data|
region = row_data[0]
if region != ''
# Row is visible.
else
# Hide row.
worksheet6.set_row(row, nil, nil, 1)
end
worksheet6.write(row, 0, row_data)
row += 1
end
workbook.close
|
Radanisk/writeexcel
|
lib/writeexcel/excelformulaparser.rb
|
# -*- coding: utf-8 -*-
#
# DO NOT MODIFY!!!!
# This file is automatically generated by Racc 1.4.11
# from Racc grammer file "".
#
require 'racc/parser.rb'
class ExcelFormulaParser < Racc::Parser # :nodoc:
##### State transition tables begin ###
racc_action_table = [
16, 54, 26, 28, 30, 32, 34, 21, 20, 3,
nil, nil, 53, 19, 23, 4, 5, 6, 7, 10,
13, 14, 15, 17, 18, 16, nil, 26, 28, 30,
32, 34, 8, nil, nil, nil, nil, 16, 19, nil,
4, 5, 6, 7, 10, 13, 14, 15, 17, 18,
19, 16, 4, 5, 6, 7, 10, 13, 14, 15,
17, 18, nil, 16, 19, nil, 4, 5, 6, 7,
10, 13, 14, 15, 17, 18, 19, 16, 4, 5,
6, 7, 10, 13, 14, 15, 17, 18, nil, 16,
19, nil, 4, 5, 6, 7, 10, 13, 14, 15,
17, 18, 19, 16, 4, 5, 6, 7, 10, 13,
14, 15, 17, 18, nil, 16, 19, 37, 4, 5,
6, 7, 10, 13, 14, 15, 17, 18, 19, 16,
4, 5, 6, 7, 10, 13, 14, 15, 17, 18,
nil, 16, 19, nil, 4, 5, 6, 7, 10, 13,
14, 15, 17, 18, 19, 16, 4, 5, 6, 7,
10, 13, 14, 15, 17, 18, nil, 16, 19, nil,
4, 5, 6, 7, 10, 13, 14, 15, 17, 18,
19, 16, 4, 5, 6, 7, 10, 13, 14, 15,
17, 18, nil, 16, 19, nil, 4, 5, 6, 7,
10, 13, 14, 15, 17, 18, 19, 16, 4, 5,
6, 7, 10, 13, 14, 15, 17, 18, nil, 16,
19, nil, 4, 5, 6, 7, 10, 13, 14, 15,
17, 18, 19, nil, 4, 5, 6, 7, 10, 13,
14, 15, 17, 18, 23, 24, 27, 29, 31, 33,
nil, nil, nil, nil, nil, 22, nil, 26, 28, 30,
32, 34, nil, 52, 23, 24, 27, 29, 31, 33,
23, 24, 27, 29, nil, nil, nil, 26, 28, 30,
32, 34, nil, 26, 28, 30, 32, 34, 23, 24,
27, 29, nil, nil, nil, 23, 24, 27, 29, 31,
33, 26, 28, 30, 32, 34, 22, 25, 26, 28,
30, 32, 34, 23, 24, 27, 29, 31, 33, nil,
nil, nil, nil, nil, 22, nil, 26, 28, 30, 32,
34, 23, 24, 27, 29, 31, 33, nil, nil, nil,
nil, nil, 22, nil, 26, 28, 30, 32, 34, 23,
24, 27, 29, 31, 33, 23, nil, nil, nil, nil,
22, nil, 26, 28, 30, 32, 34, nil, 26, 28,
30, 32, 34, 23, 24, 27, 29, 31, 33, 23,
24, nil, nil, nil, 22, nil, 26, 28, 30, 32,
34, nil, 26, 28, 30, 32, 34, 23, 24, 27,
29, 31, 33, 23, 24, nil, nil, nil, 22, nil,
26, 28, 30, 32, 34, nil, 26, 28, 30, 32,
34, 23, 24, 27, 29, 31, 33, nil, nil, nil,
nil, nil, 22, nil, 26, 28, 30, 32, 34, 23,
24, 27, 29, 31, 33, nil, nil, nil, nil, nil,
22, nil, 26, 28, 30, 32, 34 ]
racc_action_check = [
34, 39, 35, 35, 35, 35, 35, 4, 3, 1,
nil, nil, 39, 34, 41, 34, 34, 34, 34, 34,
34, 34, 34, 34, 34, 2, nil, 41, 41, 41,
41, 41, 2, nil, nil, nil, nil, 53, 2, nil,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
53, 33, 53, 53, 53, 53, 53, 53, 53, 53,
53, 53, nil, 32, 33, nil, 33, 33, 33, 33,
33, 33, 33, 33, 33, 33, 32, 16, 32, 32,
32, 32, 32, 32, 32, 32, 32, 32, nil, 19,
16, nil, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 19, 21, 19, 19, 19, 19, 19, 19,
19, 19, 19, 19, nil, 22, 21, 21, 21, 21,
21, 21, 21, 21, 21, 21, 21, 21, 22, 23,
22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
nil, 24, 23, nil, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 24, 26, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, nil, 27, 26, nil,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
27, 28, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, nil, 29, 28, nil, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 29, 30, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, nil, 31,
30, nil, 30, 30, 30, 30, 30, 30, 30, 30,
30, 30, 31, nil, 31, 31, 31, 31, 31, 31,
31, 31, 31, 31, 36, 36, 36, 36, 36, 36,
nil, nil, nil, nil, nil, 36, nil, 36, 36, 36,
36, 36, nil, 36, 40, 40, 40, 40, 40, 40,
48, 48, 48, 48, nil, nil, nil, 40, 40, 40,
40, 40, nil, 48, 48, 48, 48, 48, 50, 50,
50, 50, nil, nil, nil, 9, 9, 9, 9, 9,
9, 50, 50, 50, 50, 50, 9, 9, 9, 9,
9, 9, 9, 38, 38, 38, 38, 38, 38, nil,
nil, nil, nil, nil, 38, nil, 38, 38, 38, 38,
38, 49, 49, 49, 49, 49, 49, nil, nil, nil,
nil, nil, 49, nil, 49, 49, 49, 49, 49, 51,
51, 51, 51, 51, 51, 42, nil, nil, nil, nil,
51, nil, 51, 51, 51, 51, 51, nil, 42, 42,
42, 42, 42, 43, 43, 43, 43, 43, 43, 44,
44, nil, nil, nil, 43, nil, 43, 43, 43, 43,
43, nil, 44, 44, 44, 44, 44, 45, 45, 45,
45, 45, 45, 46, 46, nil, nil, nil, 45, nil,
45, 45, 45, 45, 45, nil, 46, 46, 46, 46,
46, 47, 47, 47, 47, 47, 47, nil, nil, nil,
nil, nil, 47, nil, 47, 47, 47, 47, 47, 55,
55, 55, 55, 55, 55, nil, nil, nil, nil, nil,
55, nil, 55, 55, 55, 55, 55 ]
racc_action_pointer = [
nil, 9, 17, 8, -14, nil, nil, nil, nil, 292,
nil, nil, nil, nil, nil, nil, 69, nil, nil, 81,
nil, 95, 107, 121, 133, nil, 147, 159, 173, 185,
199, 211, 55, 43, -8, -14, 241, nil, 310, -21,
261, 11, 352, 370, 376, 394, 400, 418, 267, 328,
285, 346, nil, 29, nil, 436 ]
racc_action_default = [
-2, -35, -1, -35, -20, -21, -22, -23, -4, -35,
-24, -17, -30, -25, -26, -27, -35, -28, -29, -35,
56, -35, -35, -35, -35, -3, -35, -35, -35, -35,
-35, -35, -35, -35, -35, -19, -35, -32, -33, -35,
-16, -9, -10, -11, -7, -12, -8, -13, -5, -14,
-6, -15, -18, -35, -31, -34 ]
racc_goto_table = [
9, 1, 2, 39, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, 35, nil, nil, 36, nil, 38,
40, 41, 42, nil, 43, 44, 45, 46, 47, 48,
49, 50, 51, nil, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
nil, 55 ]
racc_goto_check = [
3, 1, 2, 6, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, 3, nil, nil, 3, nil, 3,
3, 3, 3, nil, 3, 3, 3, 3, 3, 3,
3, 3, 3, nil, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
nil, 3 ]
racc_goto_pointer = [
nil, 1, 2, -2, nil, nil, -18 ]
racc_goto_default = [
nil, nil, nil, nil, 11, 12, nil ]
racc_reduce_table = [
0, 0, :racc_error,
1, 35, :_reduce_none,
0, 36, :_reduce_2,
3, 36, :_reduce_3,
2, 36, :_reduce_none,
3, 37, :_reduce_5,
3, 37, :_reduce_6,
3, 37, :_reduce_7,
3, 37, :_reduce_8,
3, 37, :_reduce_9,
3, 37, :_reduce_10,
3, 37, :_reduce_11,
3, 37, :_reduce_12,
3, 37, :_reduce_13,
3, 37, :_reduce_14,
3, 37, :_reduce_15,
3, 37, :_reduce_16,
1, 37, :_reduce_none,
3, 38, :_reduce_18,
2, 38, :_reduce_19,
1, 38, :_reduce_none,
1, 38, :_reduce_21,
1, 38, :_reduce_22,
1, 38, :_reduce_23,
1, 38, :_reduce_24,
1, 38, :_reduce_25,
1, 38, :_reduce_26,
1, 38, :_reduce_27,
1, 38, :_reduce_28,
1, 38, :_reduce_29,
1, 38, :_reduce_none,
4, 39, :_reduce_31,
3, 39, :_reduce_32,
1, 40, :_reduce_33,
3, 40, :_reduce_34 ]
racc_reduce_n = 35
racc_shift_n = 56
racc_token_table = {
false => 0,
:error => 1,
:UMINUS => 2,
"^" => 3,
"&" => 4,
"*" => 5,
"/" => 6,
"+" => 7,
"-" => 8,
"<" => 9,
">" => 10,
"<=" => 11,
">=" => 12,
"<>" => 13,
"=" => 14,
:EOL => 15,
:LT => 16,
:GT => 17,
:LE => 18,
:GE => 19,
:NE => 20,
"(" => 21,
")" => 22,
:FUNC => 23,
:NUMBER => 24,
:STRING => 25,
:REF2D => 26,
:REF3D => 27,
:RANGE2D => 28,
:RANGE3D => 29,
:NAME => 30,
:TRUE => 31,
:FALSE => 32,
"," => 33 }
racc_nt_base = 34
racc_use_result_var = true
Racc_arg = [
racc_action_table,
racc_action_check,
racc_action_default,
racc_action_pointer,
racc_goto_table,
racc_goto_check,
racc_goto_default,
racc_goto_pointer,
racc_nt_base,
racc_reduce_table,
racc_token_table,
racc_shift_n,
racc_reduce_n,
racc_use_result_var ]
Racc_token_to_s_table = [
"$end",
"error",
"UMINUS",
"\"^\"",
"\"&\"",
"\"*\"",
"\"/\"",
"\"+\"",
"\"-\"",
"\"<\"",
"\">\"",
"\"<=\"",
"\">=\"",
"\"<>\"",
"\"=\"",
"EOL",
"LT",
"GT",
"LE",
"GE",
"NE",
"\"(\"",
"\")\"",
"FUNC",
"NUMBER",
"STRING",
"REF2D",
"REF3D",
"RANGE2D",
"RANGE3D",
"NAME",
"TRUE",
"FALSE",
"\",\"",
"$start",
"formula",
"expr_list",
"expr",
"primary",
"funcall",
"args" ]
Racc_debug_parser = false
##### State transition tables end #####
# reduce 0 omitted
# reduce 1 omitted
module_eval(<<'.,.,', 'excelformula.y', 20)
def _reduce_2(val, _values, result)
result = []
result
end
.,.,
module_eval(<<'.,.,', 'excelformula.y', 21)
def _reduce_3(val, _values, result)
result.push val[1], '_arg', '1'
result
end
.,.,
# reduce 4 omitted
module_eval(<<'.,.,', 'excelformula.y', 24)
def _reduce_5(val, _values, result)
result = [ val[0], val[2], 'ptgAdd' ]
result
end
.,.,
module_eval(<<'.,.,', 'excelformula.y', 25)
def _reduce_6(val, _values, result)
result = [ val[0], val[2], 'ptgSub' ]
result
end
.,.,
module_eval(<<'.,.,', 'excelformula.y', 26)
def _reduce_7(val, _values, result)
result = [ val[0], val[2], 'ptgMul' ]
result
end
.,.,
module_eval(<<'.,.,', 'excelformula.y', 27)
def _reduce_8(val, _values, result)
result = [ val[0], val[2], 'ptgDiv' ]
result
end
.,.,
module_eval(<<'.,.,', 'excelformula.y', 28)
def _reduce_9(val, _values, result)
result = [ val[0], val[2], 'ptgPower' ]
result
end
.,.,
module_eval(<<'.,.,', 'excelformula.y', 29)
def _reduce_10(val, _values, result)
result = [ val[0], val[2], 'ptgConcat' ]
result
end
.,.,
module_eval(<<'.,.,', 'excelformula.y', 30)
def _reduce_11(val, _values, result)
result = [ val[0], val[2], 'ptgLT' ]
result
end
.,.,
module_eval(<<'.,.,', 'excelformula.y', 31)
def _reduce_12(val, _values, result)
result = [ val[0], val[2], 'ptgGT' ]
result
end
.,.,
module_eval(<<'.,.,', 'excelformula.y', 32)
def _reduce_13(val, _values, result)
result = [ val[0], val[2], 'ptgLE' ]
result
end
.,.,
module_eval(<<'.,.,', 'excelformula.y', 33)
def _reduce_14(val, _values, result)
result = [ val[0], val[2], 'ptgGE' ]
result
end
.,.,
module_eval(<<'.,.,', 'excelformula.y', 34)
def _reduce_15(val, _values, result)
result = [ val[0], val[2], 'ptgNE' ]
result
end
.,.,
module_eval(<<'.,.,', 'excelformula.y', 35)
def _reduce_16(val, _values, result)
result = [ val[0], val[2], 'ptgEQ' ]
result
end
.,.,
# reduce 17 omitted
module_eval(<<'.,.,', 'excelformula.y', 38)
def _reduce_18(val, _values, result)
result = [ val[1], '_arg', '1', 'ptgParen']
result
end
.,.,
module_eval(<<'.,.,', 'excelformula.y', 39)
def _reduce_19(val, _values, result)
result = [ '_num', '-1', val[1], 'ptgMul' ]
result
end
.,.,
# reduce 20 omitted
module_eval(<<'.,.,', 'excelformula.y', 41)
def _reduce_21(val, _values, result)
result = [ '_num', val[0] ]
result
end
.,.,
module_eval(<<'.,.,', 'excelformula.y', 42)
def _reduce_22(val, _values, result)
result = [ '_str', val[0] ]
result
end
.,.,
module_eval(<<'.,.,', 'excelformula.y', 43)
def _reduce_23(val, _values, result)
result = [ '_ref2d', val[0] ]
result
end
.,.,
module_eval(<<'.,.,', 'excelformula.y', 44)
def _reduce_24(val, _values, result)
result = [ '_ref3d', val[0] ]
result
end
.,.,
module_eval(<<'.,.,', 'excelformula.y', 45)
def _reduce_25(val, _values, result)
result = [ '_range2d', val[0] ]
result
end
.,.,
module_eval(<<'.,.,', 'excelformula.y', 46)
def _reduce_26(val, _values, result)
result = [ '_range3d', val[0] ]
result
end
.,.,
module_eval(<<'.,.,', 'excelformula.y', 47)
def _reduce_27(val, _values, result)
result = [ '_name', val[0] ]
result
end
.,.,
module_eval(<<'.,.,', 'excelformula.y', 48)
def _reduce_28(val, _values, result)
result = [ 'ptgBool', '1' ]
result
end
.,.,
module_eval(<<'.,.,', 'excelformula.y', 49)
def _reduce_29(val, _values, result)
result = [ 'ptgBool', '0' ]
result
end
.,.,
# reduce 30 omitted
module_eval(<<'.,.,', 'excelformula.y', 52)
def _reduce_31(val, _values, result)
result = [ '_class', val[0], val[2], '_arg', val[2].size.to_s, '_func', val[0] ]
result
end
.,.,
module_eval(<<'.,.,', 'excelformula.y', 53)
def _reduce_32(val, _values, result)
result = [ '_func', val[0] ]
result
end
.,.,
module_eval(<<'.,.,', 'excelformula.y', 55)
def _reduce_33(val, _values, result)
result = val
result
end
.,.,
module_eval(<<'.,.,', 'excelformula.y', 56)
def _reduce_34(val, _values, result)
result.push val[2]
result
end
.,.,
def _reduce_none(val, _values, result)
val[0]
end
end # class ExcelFormulaParser
class ExcelFormulaParserError < StandardError #:nodoc:
end
module Writeexcel
class Node # :nodoc:
def exec_list(nodes)
v = nil
nodes.each { |i| v = i.evaluate }
v
end
def excelformulaparser_error(msg)
raise ExcelFormulaParserError,
"in #{fname}:#{lineno}: #{msg}"
end
end
class RootNode < Node # :nodoc:
def initialize(tree)
@tree = tree
end
def evaluate
exec_list @tree
end
end
class FuncallNode < Node # :nodoc:
def initialize(func, args)
@func = func
@args = args
end
def evaluate
arg = @args.collect {|i| i.evaluate }
out = []
arg.each { |i| o.push i }
o.push @func
p o
end
end
class NumberNode < Node # :nodoc:
def initialize(val)
@val = val
end
def evaluate
p @val
end
end
class OperateNode < Node # :nodoc:
def initialize(op, left, right)
@op = op
@left = left
@right = right
end
def evaluate
o = []
o.push @left
o.push @right
o.push @op
p o
end
end
end
|
Radanisk/writeexcel
|
lib/writeexcel/charts/pie.rb
|
# -*- coding: utf-8 -*-
###############################################################################
#
# Pie - A writer class for Excel Pie 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 Pie chart using WriteExcel:
#
# #!/usr/bin/ruby -w
#
# require 'writeexcel'
#
# workbook = WriteExcel.new('chart.xls')
# worksheet = workbook.add_worksheet
#
# chart = workbook.add_chart(:type => 'Chart::Pie')
#
# # 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 Pie charts for WriteExcel. The chart
# object is created via the Workbook add_chart() method:
#
# chart = workbook.add_chart(:type => 'Chart::Pie')
#
# 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_title
#
# These methods are explained in detail in Chart section of WriteExcel.
# Class specific methods or settings, if any, are explained below.
#
# ==Pie Chart Methods
#
# There aren't currently any pie chart specific methods. See the TODO
# section of Chart section in WriteExcel.
#
# A Pie chart doesn't have an X or Y axis so the following common chart
# methods are ignored.
#
# chart.set_x_axis
# chart.set_y_axis
#
# ==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_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)
#
# # Create a new chart object. In this case an embedded chart.
# chart = workbook.add_chart(:type => 'Chart::Pie', :embedded => 1)
#
# # Configure the series.
# chart.add_series(
# :name => 'Pie sales data',
# :categories => '=Sheet1!$A$2:$A$4',
# :values => '=Sheet1!$B$2:$B$4',
# )
#
# # Add a title.
# chart.set_title(:name => 'Popular Pie Types')
#
#
# # Insert the chart into the worksheet (with an offset).
# worksheet.insert_chart('C2', chart, 25, 10)
#
# workbook.close
#
class Pie < Chart
###############################################################################
#
# new()
#
#
def initialize(*args) # :nodoc:
super
@vary_data_color = 1
end
###############################################################################
#
# _store_chart_type()
#
# Implementation of the abstract method from the specific chart class.
#
# Write the Pie chart BIFF record.
#
def store_chart_type # :nodoc:
record = 0x1019 # Record identifier.
length = 0x0006 # Number of bytes to follow.
angle = 0x0000 # Angle.
donut = 0x0000 # Donut hole size.
grbit = 0x0002 # Option flags.
store_simple(record, length, angle, donut, grbit)
end
###############################################################################
#
# _store_axisparent_stream(). Overridden.
#
# Write the AXISPARENT chart substream.
#
# A Pie chart has no X or Y axis so we override this method to remove them.
#
def store_axisparent_stream # :nodoc:
store_axisparent(*@config[:axisparent])
store_begin
store_pos(*@config[:axisparent_pos])
store_chartformat_stream
store_end
end
end
end # class Chart
end # module Writeexcel
|
Radanisk/writeexcel
|
examples/row_wrap.rb
|
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
##############################################################################
#
# Demonstrates how to wrap data from one worksheet onto another.
#
# Excel has a row limit of 65536 rows. Sometimes the amount of row data to be
# written to a file is greater than this limit. In this case it is a useful
# technique to wrap the data from one worksheet onto the next so that we get
# something like the following:
#
# Sheet1 Row 1 - 65536
# Sheet2 Row 65537 - 131072
# Sheet3 Row 131073 - ...
#
# In order to achieve this we use a single worksheet reference and
# reinitialise it to point to a new worksheet when required.
#
# reverse('©'), May 2006, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
workbook = WriteExcel.new('row_wrap.xls')
worksheet = workbook.add_worksheet
# Worksheet formatting.
worksheet.set_column('A:A', 20)
# For the sake of this example we will use a small row limit. In order to use
# the entire row range set the row_limit to 65536.
row_limit = 10
row = 0
(1 .. 2 * row_limit + 10).each do |count|
# When we hit the row limit we redirect the output
# to a new worksheet and reset the row number.
if row == row_limit
worksheet = workbook.add_worksheet
row = 0
# Repeat any worksheet formatting.
worksheet.set_column('A:A', 20)
end
worksheet.write(row, 0, "This is row #{count}")
row += 1
end
workbook.close
|
Radanisk/writeexcel
|
test/test_29_process_jpg.rb
|
# -*- coding: utf-8 -*-
##########################################################################
# test_29_process_jpg.rb
#
# Tests for the JPEG width and height processing.
#
# reverse('©'), September 2005, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
#########################################################################
require 'helper'
require 'stringio'
class TC_29_process_jpg < Test::Unit::TestCase
def setup
@image = Writeexcel::Image.new(nil, nil, nil, nil)
@type = 5 # Excel Blip type (MSOBLIPTYPE).
end
def test_valid_jpg_image_1
testname = '3w x 5h jpeg image.'
data = %w(
FF D8 FF E0 00 10 4A 46 49 46 00 01 01 01 00 60
00 60 00 00 FF DB 00 43 00 06 04 05 06 05 04 06
06 05 06 07 07 06 08 0A 10 0A 0A 09 09 0A 14 0E
0F 0C 10 17 14 18 18 17 14 16 16 1A 1D 25 1F 1A
1B 23 1C 16 16 20 2C 20 23 26 27 29 2A 29 19 1F
2D 30 2D 28 30 25 28 29 28 FF DB 00 43 01 07 07
07 0A 08 0A 13 0A 0A 13 28 1A 16 1A 28 28 28 28
28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28
28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28
28 28 28 28 28 28 28 28 28 28 28 28 28 28 FF C0
00 11 08 00 05 00 03 03 01 22 00 02 11 01 03 11
01 FF C4 00 15 00 01 01 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 07 FF C4 00 14 10 01 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 FF C4
00 15 01 01 01 00 00 00 00 00 00 00 00 00 00 00
00 00 00 06 08 FF C4 00 14 11 01 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 FF DA 00 0C 03
01 00 02 11 03 11 00 3F 00 9D 00 1C A4 5F FF D9
)
@image.__send__("process_jpg", [data.join('')].pack('H*'))
assert_equal(@type, @image.type)
assert_equal(3, @image.width)
assert_equal(5, @image.height)
end
def test_valid_jpg_image_2
testname = '5w x 3h jpeg image.'
data = %w(
FF D8 FF E0 00 10 4A 46 49 46 00 01 01 01 00 60
00 60 00 00 FF DB 00 43 00 06 04 05 06 05 04 06
06 05 06 07 07 06 08 0A 10 0A 0A 09 09 0A 14 0E
0F 0C 10 17 14 18 18 17 14 16 16 1A 1D 25 1F 1A
1B 23 1C 16 16 20 2C 20 23 26 27 29 2A 29 19 1F
2D 30 2D 28 30 25 28 29 28 FF DB 00 43 01 07 07
07 0A 08 0A 13 0A 0A 13 28 1A 16 1A 28 28 28 28
28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28
28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28
28 28 28 28 28 28 28 28 28 28 28 28 28 28 FF C0
00 11 08 00 03 00 05 03 01 22 00 02 11 01 03 11
01 FF C4 00 15 00 01 01 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 07 FF C4 00 14 10 01 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 FF C4
00 15 01 01 01 00 00 00 00 00 00 00 00 00 00 00
00 00 00 06 08 FF C4 00 14 11 01 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 FF DA 00 0C 03
01 00 02 11 03 11 00 3F 00 9D 00 1C A4 5F FF D9
)
@image.__send__("process_jpg", [data.join('')].pack('H*'))
assert_equal(@type, @image.type)
assert_equal(5, @image.width)
assert_equal(3, @image.height)
end
def test_valid_jpg_image_3_ffco_marker_missing
testname = 'FFCO marker missing in image.'
data = %w(
FF D8 FF E0 00 10 4A 46 49 46 00 01 01 01 00 60
00 60 00 00 FF DB 00 43 00 06 04 05 06 05 04 06
06 05 06 07 07 06 08 0A 10 0A 0A 09 09 0A 14 0E
0F 0C 10 17 14 18 18 17 14 16 16 1A 1D 25 1F 1A
1B 23 1C 16 16 20 2C 20 23 26 27 29 2A 29 19 1F
2D 30 2D 28 30 25 28 29 28 FF DB 00 43 01 07 07
07 0A 08 0A 13 0A 0A 13 28 1A 16 1A 28 28 28 28
28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28
28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28
28 28 28 28 28 28 28 28 28 28 28 28 28 28 FF C1
00 11 08 00 03 00 05 03 01 22 00 02 11 01 03 11
01 FF C4 00 15 00 01 01 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 07 FF C4 00 14 10 01 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 FF C4
00 15 01 01 01 00 00 00 00 00 00 00 00 00 00 00
00 00 00 06 08 FF C4 00 14 11 01 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 FF DA 00 0C 03
01 00 02 11 03 11 00 3F 00 9D 00 1C A4 5F FF D9
)
assert_raise(RuntimeError, " \t" + testname) {
@image.__send__("process_jpg", [data.join('')].pack('H*'))
}
end
def test_invalid_jpeg_image
testname = 'empty image'
image = ''
assert_raise(RuntimeError, " \t" + testname) {
@image.__send__("process_jpg", image)
}
end
###############################################################################
#
# Test 5. Progressive DCT-based JPEG image.
#
def test_progressive_dct_based_jpeg_image
testname = '35w x 35h progressive jpeg image.'
data = %w(
FF D8 FF E0 00 10 4A 46 49 46 00 01 02 01 00 96
00 96 00 00 FF E1 04 E7 45 78 69 66 00 00 4D 4D
00 2A 00 00 00 08 00 07 01 12 00 03 00 00 00 01
00 01 00 00 01 1A 00 05 00 00 00 01 00 00 00 62
01 1B 00 05 00 00 00 01 00 00 00 6A 01 28 00 03
00 00 00 01 00 02 00 00 01 31 00 02 00 00 00 14
00 00 00 72 01 32 00 02 00 00 00 14 00 00 00 86
87 69 00 04 00 00 00 01 00 00 00 9C 00 00 00 C8
00 00 00 96 00 00 00 01 00 00 00 96 00 00 00 01
41 64 6F 62 65 20 50 68 6F 74 6F 73 68 6F 70 20
37 2E 30 00 32 30 30 38 3A 30 39 3A 30 39 20 32
32 3A 32 33 3A 31 32 00 00 00 00 03 A0 01 00 03
00 00 00 01 FF FF 00 00 A0 02 00 04 00 00 00 01
00 00 00 23 A0 03 00 04 00 00 00 01 00 00 00 23
00 00 00 00 00 00 00 06 01 03 00 03 00 00 00 01
00 06 00 00 01 1A 00 05 00 00 00 01 00 00 01 16
01 1B 00 05 00 00 00 01 00 00 01 1E 01 28 00 03
00 00 00 01 00 02 00 00 02 01 00 04 00 00 00 01
00 00 01 26 02 02 00 04 00 00 00 01 00 00 03 B9
00 00 00 00 00 00 00 48 00 00 00 01 00 00 00 48
00 00 00 01 FF D8 FF E0 00 10 4A 46 49 46 00 01
02 01 00 48 00 48 00 00 FF ED 00 0C 41 64 6F 62
65 5F 43 4D 00 02 FF EE 00 0E 41 64 6F 62 65 00
64 80 00 00 00 01 FF DB 00 84 00 0C 08 08 08 09
08 0C 09 09 0C 11 0B 0A 0B 11 15 0F 0C 0C 0F 15
18 13 13 15 13 13 18 11 0C 0C 0C 0C 0C 0C 11 0C
0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C
0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 01 0D 0B 0B 0D
0E 0D 10 0E 0E 10 14 0E 0E 0E 14 14 0E 0E 0E 0E
14 11 0C 0C 0C 0C 0C 11 11 0C 0C 0C 0C 0C 0C 11
0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C
0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C FF C0 00 11
08 00 23 00 23 03 01 22 00 02 11 01 03 11 01 FF
DD 00 04 00 03 FF C4 01 3F 00 00 01 05 01 01 01
01 01 01 00 00 00 00 00 00 00 03 00 01 02 04 05
06 07 08 09 0A 0B 01 00 01 05 01 01 01 01 01 01
00 00 00 00 00 00 00 01 00 02 03 04 05 06 07 08
09 0A 0B 10 00 01 04 01 03 02 04 02 05 07 06 08
05 03 0C 33 01 00 02 11 03 04 21 12 31 05 41 51
61 13 22 71 81 32 06 14 91 A1 B1 42 23 24 15 52
C1 62 33 34 72 82 D1 43 07 25 92 53 F0 E1 F1 63
73 35 16 A2 B2 83 26 44 93 54 64 45 C2 A3 74 36
17 D2 55 E2 65 F2 B3 84 C3 D3 75 E3 F3 46 27 94
A4 85 B4 95 C4 D4 E4 F4 A5 B5 C5 D5 E5 F5 56 66
76 86 96 A6 B6 C6 D6 E6 F6 37 47 57 67 77 87 97
A7 B7 C7 D7 E7 F7 11 00 02 02 01 02 04 04 03 04
05 06 07 07 06 05 35 01 00 02 11 03 21 31 12 04
41 51 61 71 22 13 05 32 81 91 14 A1 B1 42 23 C1
52 D1 F0 33 24 62 E1 72 82 92 43 53 15 63 73 34
F1 25 06 16 A2 B2 83 07 26 35 C2 D2 44 93 54 A3
17 64 45 55 36 74 65 E2 F2 B3 84 C3 D3 75 E3 F3
46 94 A4 85 B4 95 C4 D4 E4 F4 A5 B5 C5 D5 E5 F5
56 66 76 86 96 A6 B6 C6 D6 E6 F6 27 37 47 57 67
77 87 97 A7 B7 C7 FF DA 00 0C 03 01 00 02 11 03
11 00 3F 00 F5 54 0B 33 71 AB 79 AC BF 75 83 53
5B 01 7B 84 F1 B9 95 EE 73 54 F2 1C E6 D1 63 9B
F4 9A C7 16 FC 40 5C F7 49 B7 1A FA 19 51 BF 23
1B 2C B4 3A EC 7B 2D 65 76 6E 23 DC FD 06 FB 58
FF 00 A4 CB 92 53 1E B9 F5 9B 3E 96 DB 8D 83 D3
B2 85 A7 DB 56 53 D8 1B 5C E9 EE 0F 7E E6 37 FE
B8 AF FD 5B FD AA 71 9E EE A2 CB 6A 26 36 D7 7B
C5 8F 07 5D EE DE 27 F4 7F 43 E9 21 E5 D5 85 8D
59 39 B9 04 56 EE 45 D9 6F F7 79 7A 6D 1E FF 00
EA AB 9D 0A C3 67 4D AC 9A AC C7 01 CF 0C A6 D2
4B DA D0 E7 7A 61 FE A4 BF E8 7E FA 4A 74 12 49
24 94 FF 00 FF D0 F5 2B DA 5D 4D 8D 1C B9 A4 7D
E1 66 F4 FB BA 7F 50 C3 C7 17 D4 CF 59 B5 33 F4
57 06 97 00 47 2D 9F CC 74 7D 26 2D 55 CC 7D 61
CD 7F 40 38 66 BA 99 76 16 4D CE AD EC B8 4B 69
2E 06 C6 7A 76 0F 73 37 D9 EC D8 EF EC 24 A7 61
95 74 7C 70 6F 6B 28 AF 61 FE 72 1B 20 8F DD 77
D2 44 E9 97 8C 8C 63 7B 5A E6 36 CB 2C 21 AE D1
D0 1E EA F5 1F D8 58 1F 57 FA 95 DD 6B 23 25 B5
D5 5E 23 31 F6 13 63 1A 1E F9 70 73 76 56 F7 7B
6A FE 6F 7F D0 FC F5 D3 63 D1 56 3D 2C A6 A6 ED
AD 82 1A 12 52 44 92 49 25 3F FF D1 F5 55 47 AD
C7 EC AC AD DE 84 7A 6E 9F B5 4F A3 11 FE 1B 67
BF 67 F5 17 CC 69 24 A7 E9 6F AB BB 7F 66 55 B7
EC BB 60 47 D8 B7 7A 5C 7F C2 7E 93 FC F5 A8 BE
55 49 25 3F 55 24 BE 55 49 25 3F FF D9 FF ED 09
94 50 68 6F 74 6F 73 68 6F 70 20 33 2E 30 00 38
42 49 4D 04 25 00 00 00 00 00 10 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 38 42 49 4D 03
ED 00 00 00 00 00 10 00 96 00 00 00 01 00 01 00
96 00 00 00 01 00 01 38 42 49 4D 04 26 00 00 00
00 00 0E 00 00 00 00 00 00 00 00 00 00 3F 80 00
00 38 42 49 4D 04 0D 00 00 00 00 00 04 00 00 00
1E 38 42 49 4D 04 19 00 00 00 00 00 04 00 00 00
1E 38 42 49 4D 03 F3 00 00 00 00 00 09 00 00 00
00 00 00 00 00 01 00 38 42 49 4D 04 0A 00 00 00
00 00 01 00 00 38 42 49 4D 27 10 00 00 00 00 00
0A 00 01 00 00 00 00 00 00 00 01 38 42 49 4D 03
F5 00 00 00 00 00 48 00 2F 66 66 00 01 00 6C 66
66 00 06 00 00 00 00 00 01 00 2F 66 66 00 01 00
A1 99 9A 00 06 00 00 00 00 00 01 00 32 00 00 00
01 00 5A 00 00 00 06 00 00 00 00 00 01 00 35 00
00 00 01 00 2D 00 00 00 06 00 00 00 00 00 01 38
42 49 4D 03 F8 00 00 00 00 00 70 00 00 FF FF FF
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF
FF FF FF 03 E8 00 00 00 00 FF FF FF FF FF FF FF
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 03
E8 00 00 00 00 FF FF FF FF FF FF FF FF FF FF FF
FF FF FF FF FF FF FF FF FF FF FF 03 E8 00 00 00
00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF
FF FF FF FF FF FF FF 03 E8 00 00 38 42 49 4D 04
08 00 00 00 00 00 10 00 00 00 01 00 00 02 40 00
00 02 40 00 00 00 00 38 42 49 4D 04 1E 00 00 00
00 00 04 00 00 00 00 38 42 49 4D 04 1A 00 00 00
00 03 59 00 00 00 06 00 00 00 00 00 00 00 00 00
00 00 23 00 00 00 23 00 00 00 12 00 54 00 43 00
50 00 5F 00 43 00 69 00 72 00 63 00 6C 00 65 00
5F 00 42 00 61 00 6C 00 6C 00 61 00 73 00 74 00
00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00
00 00 23 00 00 00 23 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 10 00 00 00 01
00 00 00 00 00 00 6E 75 6C 6C 00 00 00 02 00 00
00 06 62 6F 75 6E 64 73 4F 62 6A 63 00 00 00 01
00 00 00 00 00 00 52 63 74 31 00 00 00 04 00 00
00 00 54 6F 70 20 6C 6F 6E 67 00 00 00 00 00 00
00 00 4C 65 66 74 6C 6F 6E 67 00 00 00 00 00 00
00 00 42 74 6F 6D 6C 6F 6E 67 00 00 00 23 00 00
00 00 52 67 68 74 6C 6F 6E 67 00 00 00 23 00 00
00 06 73 6C 69 63 65 73 56 6C 4C 73 00 00 00 01
4F 62 6A 63 00 00 00 01 00 00 00 00 00 05 73 6C
69 63 65 00 00 00 12 00 00 00 07 73 6C 69 63 65
49 44 6C 6F 6E 67 00 00 00 00 00 00 00 07 67 72
6F 75 70 49 44 6C 6F 6E 67 00 00 00 00 00 00 00
06 6F 72 69 67 69 6E 65 6E 75 6D 00 00 00 0C 45
53 6C 69 63 65 4F 72 69 67 69 6E 00 00 00 0D 61
75 74 6F 47 65 6E 65 72 61 74 65 64 00 00 00 00
54 79 70 65 65 6E 75 6D 00 00 00 0A 45 53 6C 69
63 65 54 79 70 65 00 00 00 00 49 6D 67 20 00 00
00 06 62 6F 75 6E 64 73 4F 62 6A 63 00 00 00 01
00 00 00 00 00 00 52 63 74 31 00 00 00 04 00 00
00 00 54 6F 70 20 6C 6F 6E 67 00 00 00 00 00 00
00 00 4C 65 66 74 6C 6F 6E 67 00 00 00 00 00 00
00 00 42 74 6F 6D 6C 6F 6E 67 00 00 00 23 00 00
00 00 52 67 68 74 6C 6F 6E 67 00 00 00 23 00 00
00 03 75 72 6C 54 45 58 54 00 00 00 01 00 00 00
00 00 00 6E 75 6C 6C 54 45 58 54 00 00 00 01 00
00 00 00 00 00 4D 73 67 65 54 45 58 54 00 00 00
01 00 00 00 00 00 06 61 6C 74 54 61 67 54 45 58
54 00 00 00 01 00 00 00 00 00 0E 63 65 6C 6C 54
65 78 74 49 73 48 54 4D 4C 62 6F 6F 6C 01 00 00
00 08 63 65 6C 6C 54 65 78 74 54 45 58 54 00 00
00 01 00 00 00 00 00 09 68 6F 72 7A 41 6C 69 67
6E 65 6E 75 6D 00 00 00 0F 45 53 6C 69 63 65 48
6F 72 7A 41 6C 69 67 6E 00 00 00 07 64 65 66 61
75 6C 74 00 00 00 09 76 65 72 74 41 6C 69 67 6E
65 6E 75 6D 00 00 00 0F 45 53 6C 69 63 65 56 65
72 74 41 6C 69 67 6E 00 00 00 07 64 65 66 61 75
6C 74 00 00 00 0B 62 67 43 6F 6C 6F 72 54 79 70
65 65 6E 75 6D 00 00 00 11 45 53 6C 69 63 65 42
47 43 6F 6C 6F 72 54 79 70 65 00 00 00 00 4E 6F
6E 65 00 00 00 09 74 6F 70 4F 75 74 73 65 74 6C
6F 6E 67 00 00 00 00 00 00 00 0A 6C 65 66 74 4F
75 74 73 65 74 6C 6F 6E 67 00 00 00 00 00 00 00
0C 62 6F 74 74 6F 6D 4F 75 74 73 65 74 6C 6F 6E
67 00 00 00 00 00 00 00 0B 72 69 67 68 74 4F 75
74 73 65 74 6C 6F 6E 67 00 00 00 00 00 38 42 49
4D 04 11 00 00 00 00 00 01 01 00 38 42 49 4D 04
14 00 00 00 00 00 04 00 00 00 01 38 42 49 4D 04
0C 00 00 00 00 03 D5 00 00 00 01 00 00 00 23 00
00 00 23 00 00 00 6C 00 00 0E C4 00 00 03 B9 00
18 00 01 FF D8 FF E0 00 10 4A 46 49 46 00 01 02
01 00 48 00 48 00 00 FF ED 00 0C 41 64 6F 62 65
5F 43 4D 00 02 FF EE 00 0E 41 64 6F 62 65 00 64
80 00 00 00 01 FF DB 00 84 00 0C 08 08 08 09 08
0C 09 09 0C 11 0B 0A 0B 11 15 0F 0C 0C 0F 15 18
13 13 15 13 13 18 11 0C 0C 0C 0C 0C 0C 11 0C 0C
0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C
0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 01 0D 0B 0B 0D 0E
0D 10 0E 0E 10 14 0E 0E 0E 14 14 0E 0E 0E 0E 14
11 0C 0C 0C 0C 0C 11 11 0C 0C 0C 0C 0C 0C 11 0C
0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C
0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C FF C0 00 11 08
00 23 00 23 03 01 22 00 02 11 01 03 11 01 FF DD
00 04 00 03 FF C4 01 3F 00 00 01 05 01 01 01 01
01 01 00 00 00 00 00 00 00 03 00 01 02 04 05 06
07 08 09 0A 0B 01 00 01 05 01 01 01 01 01 01 00
00 00 00 00 00 00 01 00 02 03 04 05 06 07 08 09
0A 0B 10 00 01 04 01 03 02 04 02 05 07 06 08 05
03 0C 33 01 00 02 11 03 04 21 12 31 05 41 51 61
13 22 71 81 32 06 14 91 A1 B1 42 23 24 15 52 C1
62 33 34 72 82 D1 43 07 25 92 53 F0 E1 F1 63 73
35 16 A2 B2 83 26 44 93 54 64 45 C2 A3 74 36 17
D2 55 E2 65 F2 B3 84 C3 D3 75 E3 F3 46 27 94 A4
85 B4 95 C4 D4 E4 F4 A5 B5 C5 D5 E5 F5 56 66 76
86 96 A6 B6 C6 D6 E6 F6 37 47 57 67 77 87 97 A7
B7 C7 D7 E7 F7 11 00 02 02 01 02 04 04 03 04 05
06 07 07 06 05 35 01 00 02 11 03 21 31 12 04 41
51 61 71 22 13 05 32 81 91 14 A1 B1 42 23 C1 52
D1 F0 33 24 62 E1 72 82 92 43 53 15 63 73 34 F1
25 06 16 A2 B2 83 07 26 35 C2 D2 44 93 54 A3 17
64 45 55 36 74 65 E2 F2 B3 84 C3 D3 75 E3 F3 46
94 A4 85 B4 95 C4 D4 E4 F4 A5 B5 C5 D5 E5 F5 56
66 76 86 96 A6 B6 C6 D6 E6 F6 27 37 47 57 67 77
87 97 A7 B7 C7 FF DA 00 0C 03 01 00 02 11 03 11
00 3F 00 F5 54 0B 33 71 AB 79 AC BF 75 83 53 5B
01 7B 84 F1 B9 95 EE 73 54 F2 1C E6 D1 63 9B F4
9A C7 16 FC 40 5C F7 49 B7 1A FA 19 51 BF 23 1B
2C B4 3A EC 7B 2D 65 76 6E 23 DC FD 06 FB 58 FF
00 A4 CB 92 53 1E B9 F5 9B 3E 96 DB 8D 83 D3 B2
85 A7 DB 56 53 D8 1B 5C E9 EE 0F 7E E6 37 FE B8
AF FD 5B FD AA 71 9E EE A2 CB 6A 26 36 D7 7B C5
8F 07 5D EE DE 27 F4 7F 43 E9 21 E5 D5 85 8D 59
39 B9 04 56 EE 45 D9 6F F7 79 7A 6D 1E FF 00 EA
AB 9D 0A C3 67 4D AC 9A AC C7 01 CF 0C A6 D2 4B
DA D0 E7 7A 61 FE A4 BF E8 7E FA 4A 74 12 49 24
94 FF 00 FF D0 F5 2B DA 5D 4D 8D 1C B9 A4 7D E1
66 F4 FB BA 7F 50 C3 C7 17 D4 CF 59 B5 33 F4 57
06 97 00 47 2D 9F CC 74 7D 26 2D 55 CC 7D 61 CD
7F 40 38 66 BA 99 76 16 4D CE AD EC B8 4B 69 2E
06 C6 7A 76 0F 73 37 D9 EC D8 EF EC 24 A7 61 95
74 7C 70 6F 6B 28 AF 61 FE 72 1B 20 8F DD 77 D2
44 E9 97 8C 8C 63 7B 5A E6 36 CB 2C 21 AE D1 D0
1E EA F5 1F D8 58 1F 57 FA 95 DD 6B 23 25 B5 D5
5E 23 31 F6 13 63 1A 1E F9 70 73 76 56 F7 7B 6A
FE 6F 7F D0 FC F5 D3 63 D1 56 3D 2C A6 A6 ED AD
82 1A 12 52 44 92 49 25 3F FF D1 F5 55 47 AD C7
EC AC AD DE 84 7A 6E 9F B5 4F A3 11 FE 1B 67 BF
67 F5 17 CC 69 24 A7 E9 6F AB BB 7F 66 55 B7 EC
BB 60 47 D8 B7 7A 5C 7F C2 7E 93 FC F5 A8 BE 55
49 25 3F 55 24 BE 55 49 25 3F FF D9 00 38 42 49
4D 04 21 00 00 00 00 00 55 00 00 00 01 01 00 00
00 0F 00 41 00 64 00 6F 00 62 00 65 00 20 00 50
00 68 00 6F 00 74 00 6F 00 73 00 68 00 6F 00 70
00 00 00 13 00 41 00 64 00 6F 00 62 00 65 00 20
00 50 00 68 00 6F 00 74 00 6F 00 73 00 68 00 6F
00 70 00 20 00 37 00 2E 00 30 00 00 00 01 00 38
42 49 4D 04 06 00 00 00 00 00 07 00 08 01 01 00
01 01 00 FF E1 12 48 68 74 74 70 3A 2F 2F 6E 73
2E 61 64 6F 62 65 2E 63 6F 6D 2F 78 61 70 2F 31
2E 30 2F 00 3C 3F 78 70 61 63 6B 65 74 20 62 65
67 69 6E 3D 27 EF BB BF 27 20 69 64 3D 27 57 35
4D 30 4D 70 43 65 68 69 48 7A 72 65 53 7A 4E 54
63 7A 6B 63 39 64 27 3F 3E 0A 3C 3F 61 64 6F 62
65 2D 78 61 70 2D 66 69 6C 74 65 72 73 20 65 73
63 3D 22 43 52 22 3F 3E 0A 3C 78 3A 78 61 70 6D
65 74 61 20 78 6D 6C 6E 73 3A 78 3D 27 61 64 6F
62 65 3A 6E 73 3A 6D 65 74 61 2F 27 20 78 3A 78
61 70 74 6B 3D 27 58 4D 50 20 74 6F 6F 6C 6B 69
74 20 32 2E 38 2E 32 2D 33 33 2C 20 66 72 61 6D
65 77 6F 72 6B 20 31 2E 35 27 3E 0A 3C 72 64 66
3A 52 44 46 20 78 6D 6C 6E 73 3A 72 64 66 3D 27
68 74 74 70 3A 2F 2F 77 77 77 2E 77 33 2E 6F 72
67 2F 31 39 39 39 2F 30 32 2F 32 32 2D 72 64 66
2D 73 79 6E 74 61 78 2D 6E 73 23 27 20 78 6D 6C
6E 73 3A 69 58 3D 27 68 74 74 70 3A 2F 2F 6E 73
2E 61 64 6F 62 65 2E 63 6F 6D 2F 69 58 2F 31 2E
30 2F 27 3E 0A 0A 20 3C 72 64 66 3A 44 65 73 63
72 69 70 74 69 6F 6E 20 61 62 6F 75 74 3D 27 75
75 69 64 3A 34 37 38 34 61 35 39 66 2D 37 65 64
66 2D 31 31 64 64 2D 39 61 37 39 2D 61 31 62 66
63 38 33 61 61 63 63 36 27 0A 20 20 78 6D 6C 6E
73 3A 78 61 70 4D 4D 3D 27 68 74 74 70 3A 2F 2F
6E 73 2E 61 64 6F 62 65 2E 63 6F 6D 2F 78 61 70
2F 31 2E 30 2F 6D 6D 2F 27 3E 0A 20 20 3C 78 61
70 4D 4D 3A 44 6F 63 75 6D 65 6E 74 49 44 3E 61
64 6F 62 65 3A 64 6F 63 69 64 3A 70 68 6F 74 6F
73 68 6F 70 3A 34 37 38 34 61 35 39 64 2D 37 65
64 66 2D 31 31 64 64 2D 39 61 37 39 2D 61 31 62
66 63 38 33 61 61 63 63 36 3C 2F 78 61 70 4D 4D
3A 44 6F 63 75 6D 65 6E 74 49 44 3E 0A 20 3C 2F
72 64 66 3A 44 65 73 63 72 69 70 74 69 6F 6E 3E
0A 0A 3C 2F 72 64 66 3A 52 44 46 3E 0A 3C 2F 78
3A 78 61 70 6D 65 74 61 3E 0A 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 0A 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 0A 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 0A 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 0A 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 0A 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 0A 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 0A 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 0A 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 0A 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 0A 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
0A 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 0A 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 0A 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 0A
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 0A 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 0A 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 0A 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 0A 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 0A 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 0A 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 0A 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 0A 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 0A 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 0A 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 0A 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 0A 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
0A 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 0A 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 0A 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 0A
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 0A 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 0A 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 0A 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 0A 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 0A 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 0A 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 0A 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 0A 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 0A 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 0A 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 0A 3C 3F 78 70 61 63
6B 65 74 20 65 6E 64 3D 27 77 27 3F 3E FF EE 00
21 41 64 6F 62 65 00 64 40 00 00 00 01 03 00 10
03 02 03 06 00 00 00 00 00 00 00 00 00 00 00 00
FF DB 00 84 00 01 01 01 01 01 01 01 01 01 01 01
01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01
01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01
02 02 02 02 02 02 02 02 02 02 02 03 03 03 03 03
03 03 03 03 03 01 01 01 01 01 01 01 01 01 01 01
02 02 01 02 02 03 03 03 03 03 03 03 03 03 03 03
03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03
03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03
03 03 03 03 03 03 FF C2 00 11 08 00 23 00 23 03
)
@image.__send__("process_jpg", [data.join('')].pack('H*'))
assert_equal(@type, @image.type)
assert_equal(35, @image.width)
assert_equal(35, @image.height)
end
end
|
Radanisk/writeexcel
|
charts/demo4.rb
|
<filename>charts/demo4.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 an "Open-high-low-close" stock chart extracted from the
# file Chart3.xls as follows:
#
# perl chartex.pl -c=demo4 Chart4.xls
#
#
# reverse('ゥ'), September 2004, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
workbook = WriteExcel.new("demo4.xls")
worksheet = workbook.add_worksheet
# Add the chart extracted using the chartex utility
worksheet.embed_chart('G2', 'demo401.bin', 3, 3, 1.08, 1.21)
# 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, :bold => 1)
chart_font_3 = workbook.add_format(:font_only => 1)
chart_font_4 = workbook.add_format(:font_only => 1)
# Add all other formats.
bold = workbook.add_format(:bold => 1)
date_format = workbook.add_format(:num_format => 'dd/mm/yyyy')
# Adjust column widths and add some headers
worksheet.set_column('A:A', 12)
worksheet.write('A1', 'Date', bold)
worksheet.write('B1', 'Open', bold)
worksheet.write('C1', 'High', bold)
worksheet.write('D1', 'Low', bold)
worksheet.write('E1', 'Close', bold)
# Add data to range that the chart refers to.
dates = [
"2004-08-19T",
"2004-08-20T",
"2004-08-23T",
"2004-08-24T",
"2004-08-25T",
"2004-08-26T",
"2004-08-27T",
"2004-08-30T",
"2004-08-31T",
"2004-09-01T",
"2004-09-02T",
"2004-09-03T",
"2004-09-07T",
"2004-09-08T",
"2004-09-09T",
"2004-09-10T",
"2004-09-13T",
"2004-09-14T",
"2004-09-15T",
"2004-09-16T",
"2004-09-17T",
"2004-09-20T",
"2004-09-21T"
]
# Open-High-Low-Close prices
prices = [
[100.00, 104.06, 95.96, 100.34],
[101.01, 109.08, 100.50, 108.31],
[110.75, 113.48, 109.05, 109.40],
[111.24, 111.60, 103.57, 104.87],
[104.96, 108.00, 103.88, 106.00],
[104.95, 107.95, 104.66, 107.91],
[108.10, 108.62, 105.69, 106.15],
[105.28, 105.49, 102.01, 102.01],
[102.30, 103.71, 102.16, 102.37],
[102.70, 102.97, 99.67, 100.25],
[ 99.19, 102.37, 98.94, 101.51],
[100.95, 101.74, 99.32, 100.01],
[101.01, 102.00, 99.61, 101.58],
[100.74, 103.03, 100.50, 102.30],
[102.53, 102.71, 101.00, 102.31],
[101.60, 106.56, 101.30, 105.33],
[106.63, 108.41, 106.46, 107.50],
[107.45, 112.00, 106.79, 111.49],
[110.56, 114.23, 110.20, 112.00],
[112.34, 115.80, 111.65, 113.97],
[114.42, 117.49, 113.55, 117.49],
[116.95, 121.60, 116.77, 119.36],
[119.81, 120.42, 117.51, 117.84]
]
row = 1
dates.each do |d|
worksheet.write_date_time(row, 0, d, date_format)
row += 1
end
worksheet.write_col('B2', prices)
workbook.close
|
Radanisk/writeexcel
|
examples/demo.rb
|
<reponame>Radanisk/writeexcel
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
#######################################################################
#
# Demo of some of the features of WriteExcel.
# Used to create the project screenshot for Freshmeat.
#
#
# reverse('©'), October 2001, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
# $debug = true
workbook = WriteExcel.new("demo.xls")
worksheet = workbook.add_worksheet('Demo')
worksheet2 = workbook.add_worksheet('Another sheet')
worksheet3 = workbook.add_worksheet('And another')
bold = workbook.add_format(:bold => 1)
#######################################################################
#
# Write a general heading
#
worksheet.set_column('A:A', 36, bold)
worksheet.set_column('B:B', 20 )
worksheet.set_row(0, 40 )
heading = workbook.add_format(
:bold => 1,
:color => 'blue',
:size => 16,
:merge => 1,
:align => 'vcenter'
)
headings = ['Features of Spreadsheet::WriteExcel', '']
worksheet.write_row('A1', headings, heading)
#######################################################################
#
# Some text examples
#
text_format = workbook.add_format(
:bold => 1,
:italic => 1,
:color => 'red',
:size => 18,
:font =>'Lucida Calligraphy'
)
# A phrase in Cyrillic
unicode = [
"042d0442043e002004440440043004370430002004"+
"3d043000200440044304410441043a043e043c0021"
].pack('H*')
worksheet.write('A2', "Text")
worksheet.write('B2', "Hello Excel")
worksheet.write('A3', "Formatted text")
worksheet.write('B3', "Hello Excel", text_format)
worksheet.write('A4', "Unicode text")
worksheet.write_utf16be_string('B4', unicode)
#######################################################################
#
# Some numeric examples
#
num1_format = workbook.add_format(:num_format => '$#,##0.00')
num2_format = workbook.add_format(:num_format => ' d mmmm yyy')
worksheet.write('A5', "Numbers")
worksheet.write('B5', 1234.56)
worksheet.write('A6', "Formatted numbers")
worksheet.write('B6', 1234.56, num1_format)
worksheet.write('A7', "Formatted numbers")
worksheet.write('B7', 37257, num2_format)
#######################################################################
#
# Formulae
#
worksheet.set_selection('B8')
worksheet.write('A8', 'Formulas and functions, "=SIN(PI()/4)"')
worksheet.write('B8', '=SIN(PI()/4)')
#######################################################################
#
# Hyperlinks
#
worksheet.write('A9', "Hyperlinks")
worksheet.write('B9', 'http://www.perl.com/' )
#######################################################################
#
# Images
#
worksheet.write('A10', "Images")
worksheet.insert_image('B10',
File.join(File.dirname(File.expand_path(__FILE__)), 'republic.png'),
16, 8
)
#######################################################################
#
# Misc
#
worksheet.write('A18', "Page/printer setup")
worksheet.write('A19', "Multiple worksheets")
workbook.close
|
Radanisk/writeexcel
|
test/test_example_match.rb
|
<filename>test/test_example_match.rb<gh_stars>10-100
# -*- coding: utf-8 -*-
require 'helper'
require 'stringio'
class TC_example_match < Test::Unit::TestCase
TEST_DIR = File.expand_path(File.dirname(__FILE__))
PERL_OUTDIR = File.join(TEST_DIR, 'perl_output')
def setup
@file = StringIO.new
end
def test_a_simple
workbook = WriteExcel.new(@file)
worksheet = workbook.add_worksheet
# The general syntax is write(row, column, token). Note that row and
# column are zero indexed
#
# Write some text
worksheet.write(0, 0, "Hi Excel!")
# Write some numbers
worksheet.write(2, 0, 3) # Writes 3
worksheet.write(3, 0, 3.00000) # Writes 3
worksheet.write(4, 0, 3.00001) # Writes 3.00001
worksheet.write(5, 0, 3.14159) # TeX revision no.?
# Write some formulas
worksheet.write(7, 0, '=A3 + A6')
worksheet.write(8, 0, '=IF(A5>3,"Yes", "No")')
# Write a hyperlink
worksheet.write(10, 0, 'http://www.perl.com/')
# File save
workbook.close
# do assertion
compare_file("#{PERL_OUTDIR}/a_simple.xls", @file)
end
def test_autofilter
workbook = WriteExcel.new(@file)
worksheet1 = workbook.add_worksheet
worksheet2 = workbook.add_worksheet
worksheet3 = workbook.add_worksheet
worksheet4 = workbook.add_worksheet
worksheet5 = workbook.add_worksheet
worksheet6 = workbook.add_worksheet
bold = workbook.add_format(:bold => 1)
# Extract the data embedded at the end of this file.
headings = %w(Region Item Volume Month)
data = get_data_for_autofilter
# Set up several sheets with the same data.
workbook.sheets.each do |worksheet|
worksheet.set_column('A:D', 12)
worksheet.set_row(0, 20, bold)
worksheet.write('A1', headings)
end
###############################################################################
#
# Example 1. Autofilter without conditions.
#
worksheet1.autofilter('A1:D51')
worksheet1.write('A2', [data])
###############################################################################
#
#
# Example 2. Autofilter with a filter condition in the first column.
#
# The range in this example is the same as above but in row-column notation.
worksheet2.autofilter(0, 0, 50, 3)
# The placeholder "Region" in the filter is ignored and can be any string
# that adds clarity to the expression.
#
worksheet2.filter_column(0, 'Region eq East')
#
# Hide the rows that don't match the filter criteria.
#
row = 1
data.each do |row_data|
region = row_data[0]
if region == 'East'
# Row is visible.
else
# Hide row.
worksheet2.set_row(row, nil, nil, 1)
end
worksheet2.write(row, 0, row_data)
row += 1
end
###############################################################################
#
#
# Example 3. Autofilter with a dual filter condition in one of the columns.
#
worksheet3.autofilter('A1:D51')
worksheet3.filter_column('A', 'x eq East or x eq South')
#
# Hide the rows that don't match the filter criteria.
#
row = 1
data.each do |row_data|
region = row_data[0]
if region == 'East' || region == 'South'
# Row is visible.
else
# Hide row.
worksheet3.set_row(row, nil, nil, 1)
end
worksheet3.write(row, 0, row_data)
row += 1
end
###############################################################################
#
#
# Example 4. Autofilter with filter conditions in two columns.
#
worksheet4.autofilter('A1:D51')
worksheet4.filter_column('A', 'x eq East')
worksheet4.filter_column('C', 'x > 3000 and x < 8000' )
#
# Hide the rows that don't match the filter criteria.
#
row = 1
data.each do |row_data|
region = row_data[0]
volume = row_data[2]
if region == 'East' && volume > 3000 && volume < 8000
# Row is visible.
else
# Hide row.
worksheet4.set_row(row, nil, nil, 1)
end
worksheet4.write(row, 0, row_data)
row += 1
end
###############################################################################
#
#
# Example 5. Autofilter with filter for blanks.
#
# Create a blank cell in our test data.
data[5][0] = ''
worksheet5.autofilter('A1:D51')
worksheet5.filter_column('A', 'x == Blanks')
#
# Hide the rows that don't match the filter criteria.
#
row = 1
data.each do |row_data|
region = row_data[0]
if region == ''
# Row is visible.
else
# Hide row.
worksheet5.set_row(row, nil, nil, 1)
end
worksheet5.write(row, 0, row_data)
row += 1
end
###############################################################################
#
#
# Example 6. Autofilter with filter for non-blanks.
#
worksheet6.autofilter('A1:D51')
worksheet6.filter_column('A', 'x == NonBlanks')
#
# Hide the rows that don't match the filter criteria.
#
row = 1
data.each do |row_data|
region = row_data[0]
if region != ''
# Row is visible.
else
# Hide row.
worksheet6.set_row(row, nil, nil, 1)
end
worksheet6.write(row, 0, row_data)
row += 1
end
workbook.close
# do assertion
compare_file("#{PERL_OUTDIR}/autofilter.xls", @file)
end
def get_data_for_autofilter
[
['East', 'Apple', 9000, 'July'],
['East', 'Apple', 5000, 'July'],
['South', 'Orange', 9000, 'September'],
['North', 'Apple', 2000, 'November'],
['West', 'Apple', 9000, 'November'],
['South', 'Pear', 7000, 'October'],
['North', 'Pear', 9000, 'August'],
['West', 'Orange', 1000, 'December'],
['West', 'Grape', 1000, 'November'],
['South', 'Pear', 10000, 'April'],
['West', 'Grape', 6000, 'January'],
['South', 'Orange', 3000, 'May'],
['North', 'Apple', 3000, 'December'],
['South', 'Apple', 7000, 'February'],
['West', 'Grape', 1000, 'December'],
['East', 'Grape', 8000, 'February'],
['South', 'Grape', 10000, 'June'],
['West', 'Pear', 7000, 'December'],
['South', 'Apple', 2000, 'October'],
['East', 'Grape', 7000, 'December'],
['North', 'Grape', 6000, 'April'],
['East', 'Pear', 8000, 'February'],
['North', 'Apple', 7000, 'August'],
['North', 'Orange', 7000, 'July'],
['North', 'Apple', 6000, 'June'],
['South', 'Grape', 8000, 'September'],
['West', 'Apple', 3000, 'October'],
['South', 'Orange', 10000, 'November'],
['West', 'Grape', 4000, 'July'],
['North', 'Orange', 5000, 'August'],
['East', 'Orange', 1000, 'November'],
['East', 'Orange', 4000, 'October'],
['North', 'Grape', 5000, 'August'],
['East', 'Apple', 1000, 'December'],
['South', 'Apple', 10000, 'March'],
['East', 'Grape', 7000, 'October'],
['West', 'Grape', 1000, 'September'],
['East', 'Grape', 10000, 'October'],
['South', 'Orange', 8000, 'March'],
['North', 'Apple', 4000, 'July'],
['South', 'Orange', 5000, 'July'],
['West', 'Apple', 4000, 'June'],
['East', 'Apple', 5000, 'April'],
['North', 'Pear', 3000, 'August'],
['East', 'Grape', 9000, 'November'],
['North', 'Orange', 8000, 'October'],
['East', 'Apple', 10000, 'June'],
['South', 'Pear', 1000, 'December'],
['North', 'Grape', 10000, 'July'],
['East', 'Grape', 6000, 'February'],
]
end
def test_regions
workbook = WriteExcel.new(@file)
# Add some worksheets
north = workbook.add_worksheet("North")
south = workbook.add_worksheet("South")
east = workbook.add_worksheet("East")
west = workbook.add_worksheet("West")
# Add a Format
format = workbook.add_format()
format.set_bold()
format.set_color('blue')
# Add a caption to each worksheet
workbook.sheets.each do |worksheet|
worksheet.write(0, 0, "Sales", format)
end
# Write some data
north.write(0, 1, 200000)
south.write(0, 1, 100000)
east.write(0, 1, 150000)
west.write(0, 1, 100000)
# Set the active worksheet
south.activate()
# Set the width of the first column
south.set_column(0, 0, 20)
# Set the active cell
south.set_selection(0, 1)
workbook.close
# do assertion
compare_file("#{PERL_OUTDIR}/regions.xls", @file)
end
def test_stats
workbook = WriteExcel.new(@file)
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
# do assertion
compare_file("#{PERL_OUTDIR}/stats.xls", @file)
end
def test_hyperlink1
# Create a new workbook and add a worksheet
workbook = WriteExcel.new(@file)
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
# do assertion
compare_file("#{PERL_OUTDIR}/hyperlink.xls", @file)
end
def test_hyperlink2
# Create workbook1
ireland = WriteExcel.new(@file)
ire_links = ireland.add_worksheet('Links')
ire_sales = ireland.add_worksheet('Sales')
ire_data = ireland.add_worksheet('Product Data')
file2 = StringIO.new
italy = WriteExcel.new(file2)
ita_links = italy.add_worksheet('Links')
ita_sales = italy.add_worksheet('Sales')
ita_data = italy.add_worksheet('Product Data')
file3 = StringIO.new
china = WriteExcel.new(file3)
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
# do assertion
compare_file("#{PERL_OUTDIR}/Ireland.xls", @file)
compare_file("#{PERL_OUTDIR}/Italy.xls", file2)
compare_file("#{PERL_OUTDIR}/China.xls", file3)
end
def test_copyformat
# Create workbook1
workbook1 = WriteExcel.new(@file)
worksheet1 = workbook1.add_worksheet
format1a = workbook1.add_format
format1b = workbook1.add_format
# Create workbook2
file2 = StringIO.new
workbook2 = WriteExcel.new(file2)
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 = Writeexcel::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
# do assertion
compare_file("#{PERL_OUTDIR}/workbook1.xls", @file)
compare_file("#{PERL_OUTDIR}/workbook2.xls", file2)
end
def test_data_validate
workbook = WriteExcel.new(@file)
worksheet = workbook.add_worksheet
# Add a format for the header cells.
header_format = workbook.add_format(
:border => 1,
:bg_color => 43,
:bold => 1,
:text_wrap => 1,
:valign => 'vcenter',
:indent => 1
)
# Set up layout of the worksheet.
worksheet.set_column('A:A', 64)
worksheet.set_column('B:B', 15)
worksheet.set_column('D:D', 15)
worksheet.set_row(0, 36)
worksheet.set_selection('B3')
# Write the header cells and some data that will be used in the examples.
row = 0
heading1 = 'Some examples of data validation in WriteExcel'
heading2 = 'Enter values in this column'
heading3 = 'Sample Data'
worksheet.write('A1', heading1, header_format)
worksheet.write('B1', heading2, header_format)
worksheet.write('D1', heading3, header_format)
worksheet.write('D3', ['Integers', 1, 10])
worksheet.write('D4', ['List data', 'open', 'high', 'close'])
worksheet.write('D5', ['Formula', '=AND(F5=50,G5=60)', 50, 60])
#
# Example 1. Limiting input to an integer in a fixed range.
#
txt = 'Enter an integer between 1 and 10'
row += 2
worksheet.write(row, 0, txt)
worksheet.data_validation(row, 1,
{
:validate => 'integer',
:criteria => 'between',
:minimum => 1,
:maximum => 10
})
#
# Example 2. Limiting input to an integer outside a fixed range.
#
txt = 'Enter an integer that is not between 1 and 10 (using cell references)'
row += 2
worksheet.write(row, 0, txt)
worksheet.data_validation(row, 1,
{
:validate => 'integer',
:criteria => 'not between',
:minimum => '=E3',
:maximum => '=F3'
})
#
# Example 3. Limiting input to an integer greater than a fixed value.
#
txt = 'Enter an integer greater than 0'
row += 2
worksheet.write(row, 0, txt)
worksheet.data_validation(row, 1,
{
:validate => 'integer',
:criteria => '>',
:value => 0
})
#
# Example 4. Limiting input to an integer less than a fixed value.
#
txt = 'Enter an integer less than 10'
row += 2
worksheet.write(row, 0, txt)
worksheet.data_validation(row, 1,
{
:validate => 'integer',
:criteria => '<',
:value => 10
})
#
# Example 5. Limiting input to a decimal in a fixed range.
#
txt = 'Enter a decimal between 0.1 and 0.5'
row += 2
worksheet.write(row, 0, txt)
worksheet.data_validation(row, 1,
{
:validate => 'decimal',
:criteria => 'between',
:minimum => 0.1,
:maximum => 0.5
})
#
# Example 6. Limiting input to a value in a dropdown list.
#
txt = 'Select a value from a drop down list'
row += 2
worksheet.write(row, 0, txt)
worksheet.data_validation(row, 1,
{
:validate => 'list',
:source => ['open', 'high', 'close']
})
#
# Example 6. Limiting input to a value in a dropdown list.
#
txt = 'Select a value from a drop down list (using a cell range)'
row += 2
worksheet.write(row, 0, txt)
worksheet.data_validation(row, 1,
{
:validate => 'list',
:source => '=E4:G4'
})
#
# Example 7. Limiting input to a date in a fixed range.
#
txt = 'Enter a date between 1/1/2008 and 12/12/2008'
row += 2
worksheet.write(row, 0, txt)
worksheet.data_validation(row, 1,
{
:validate => 'date',
:criteria => 'between',
:minimum => '2008-01-01T',
:maximum => '2008-12-12T'
})
#
# Example 8. Limiting input to a time in a fixed range.
#
txt = 'Enter a time between 6:00 and 12:00'
row += 2
worksheet.write(row, 0, txt)
worksheet.data_validation(row, 1,
{
:validate => 'time',
:criteria => 'between',
:minimum => 'T06:00',
:maximum => 'T12:00'
})
#
# Example 9. Limiting input to a string greater than a fixed length.
#
txt = 'Enter a string longer than 3 characters'
row += 2
worksheet.write(row, 0, txt)
worksheet.data_validation(row, 1,
{
:validate => 'length',
:criteria => '>',
:value => 3
})
#
# Example 10. Limiting input based on a formula.
#
txt = 'Enter a value if the following is true "=AND(F5=50,G5=60)"'
row += 2
worksheet.write(row, 0, txt)
worksheet.data_validation(row, 1,
{
:validate => 'custom',
:value => '=AND(F5=50,G5=60)'
})
#
# Example 11. Displaying and modify data validation messages.
#
txt = 'Displays a message when you select the cell'
row += 2
worksheet.write(row, 0, txt)
worksheet.data_validation(row, 1,
{
:validate => 'integer',
:criteria => 'between',
:minimum => 1,
:maximum => 100,
:input_title => 'Enter an integer:',
:input_message => 'between 1 and 100'
})
#
# Example 12. Displaying and modify data validation messages.
#
txt = 'Display a custom error message when integer isn\'t between 1 and 100'
row += 2
worksheet.write(row, 0, txt)
worksheet.data_validation(row, 1,
{
:validate => 'integer',
:criteria => 'between',
:minimum => 1,
:maximum => 100,
:input_title => 'Enter an integer:',
:input_message => 'between 1 and 100',
:error_title => 'Input value is not valid!',
:error_message => 'It should be an integer between 1 and 100'
})
#
# Example 13. Displaying and modify data validation messages.
#
txt = 'Display a custom information message when integer isn\'t between 1 and 100'
row += 2
worksheet.write(row, 0, txt)
worksheet.data_validation(row, 1,
{
:validate => 'integer',
:criteria => 'between',
:minimum => 1,
:maximum => 100,
:input_title => 'Enter an integer:',
:input_message => 'between 1 and 100',
:error_title => 'Input value is not valid!',
:error_message => 'It should be an integer between 1 and 100',
:error_type => 'information'
})
workbook.close
# do assertion
compare_file("#{PERL_OUTDIR}/data_validate.xls", @file)
end
def test_merge1
workbook = WriteExcel.new(@file)
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
# do assertion
compare_file("#{PERL_OUTDIR}/merge1.xls", @file)
end
def test_merge2
workbook = WriteExcel.new(@file)
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
# do assertion
compare_file("#{PERL_OUTDIR}/merge2.xls", @file)
end
def test_merge3
workbook = WriteExcel.new(@file)
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
# do assertion
compare_file("#{PERL_OUTDIR}/merge3.xls", @file)
end
def test_merge4
# Create a new workbook and add a worksheet
workbook = WriteExcel.new(@file)
worksheet = workbook.add_worksheet
# Increase the cell size of the merged cells to highlight the formatting.
(1..11).each { |row| worksheet.set_row(row, 30) }
worksheet.set_column('B:D', 20)
###############################################################################
#
# Example 1: Text centered vertically and horizontally
#
format1 = workbook.add_format(
:border => 6,
:bold => 1,
:color => 'red',
:valign => 'vcenter',
:align => 'center'
)
worksheet.merge_range('B2:D3', 'Vertical and horizontal', format1)
###############################################################################
#
# Example 2: Text aligned to the top and left
#
format2 = workbook.add_format(
:border => 6,
:bold => 1,
:color => 'red',
:valign => 'top',
:align => 'left'
)
worksheet.merge_range('B5:D6', 'Aligned to the top and left', format2)
###############################################################################
#
# Example 3: Text aligned to the bottom and right
#
format3 = workbook.add_format(
:border => 6,
:bold => 1,
:color => 'red',
:valign => 'bottom',
:align => 'right'
)
worksheet.merge_range('B8:D9', 'Aligned to the bottom and right', format3)
###############################################################################
#
# Example 4: Text justified (i.e. wrapped) in the cell
#
format4 = workbook.add_format(
:border => 6,
:bold => 1,
:color => 'red',
:valign => 'top',
:align => 'justify'
)
worksheet.merge_range('B11:D12', 'Justified: '+'so on and '*18, format4)
workbook.close
# do assertion
compare_file("#{PERL_OUTDIR}/merge4.xls", @file)
end
def test_merge5
# Create a new workbook and add a worksheet
workbook = WriteExcel.new(@file)
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
# do assertion
compare_file("#{PERL_OUTDIR}/merge5.xls", @file)
end
def test_merge6
# Create a new workbook and add a worksheet
workbook = WriteExcel.new(@file)
worksheet = workbook.add_worksheet
# Increase the cell size of the merged cells to highlight the formatting.
(2..9).each { |i| worksheet.set_row(i, 36) }
worksheet.set_column('B:D', 25)
# Format for the merged cells.
format = workbook.add_format(
:border => 6,
:bold => 1,
:color => 'red',
:size => 20,
:valign => 'vcentre',
:align => 'left',
:indent => 1
)
###############################################################################
#
# Write an Ascii string.
#
worksheet.merge_range('B3:D4', 'ASCII: A simple string', format)
###############################################################################
#
# Write a UTF-16 Unicode string.
#
# A phrase in Cyrillic encoded as UTF-16BE.
utf16_str = [
'005500540046002d00310036003a0020' <<
'042d0442043e002004440440043004370430002004' <<
'3d043000200440044304410441043a043e043c0021'
].pack("H*")
# Note the extra parameter at the end to indicate UTF-16 encoding.
worksheet.merge_range('B6:D7', utf16_str, format, 1)
###############################################################################
#
# Write a UTF-8 Unicode string.
#
smiley = '☺' # chr 0x263a in perl
worksheet.merge_range('B9:D10', "UTF-8: A Unicode smiley #{smiley}", format)
workbook.close
# do assertion
compare_file("#{PERL_OUTDIR}/merge6.xls", @file)
end
def test_images
# Create a new workbook called simple.xls and add a worksheet
workbook = WriteExcel.new(@file)
worksheet1 = workbook.add_worksheet('Image 1')
worksheet2 = workbook.add_worksheet('Image 2')
worksheet3 = workbook.add_worksheet('Image 3')
worksheet4 = workbook.add_worksheet('Image 4')
# Insert a basic image
worksheet1.write('A10', "Image inserted into worksheet.")
worksheet1.insert_image('A1', File.join(TEST_DIR,'republic.png'))
# Insert an image with an offset
worksheet2.write('A10', "Image inserted with an offset.")
worksheet2.insert_image('A1', File.join(TEST_DIR,'republic.png'), 32, 10)
# Insert a scaled image
worksheet3.write('A10', "Image scaled: width x 2, height x 0.8.")
worksheet3.insert_image('A1', File.join(TEST_DIR,'republic.png'), 0, 0, 2, 0.8)
# Insert an image over varied column and row sizes
# This does not require any additional work
# Set the cols and row sizes
# NOTE: you must do this before you call insert_image()
worksheet4.set_column('A:A', 5)
worksheet4.set_column('B:B', nil, nil, 1) # Hidden
worksheet4.set_column('C:D', 10)
worksheet4.set_row(0, 30)
worksheet4.set_row(3, 5)
worksheet4.write('A10', "Image inserted over scaled rows and columns.")
worksheet4.insert_image('A1', File.join(TEST_DIR,'republic.png'))
workbook.close
# do assertion
compare_file("#{PERL_OUTDIR}/images.xls", @file)
end
def test_tab_colors
workbook = WriteExcel.new(@file)
worksheet1 = workbook.add_worksheet
worksheet2 = workbook.add_worksheet
worksheet3 = workbook.add_worksheet
worksheet4 = workbook.add_worksheet
# Worsheet1 will have the default tab colour.
worksheet2.set_tab_color('red')
worksheet3.set_tab_color('green')
worksheet4.set_tab_color(0x35) # Orange
workbook.close
# do assertion
compare_file("#{PERL_OUTDIR}/tab_colors.xls", @file)
end
def test_stocks
# Create a new workbook and add a worksheet
workbook = WriteExcel.new(@file)
worksheet = workbook.add_worksheet
# Set the column width for columns 1, 2, 3 and 4
worksheet.set_column(0, 3, 15)
# Create a format for the column headings
header = workbook.add_format
header.set_bold
header.set_size(12)
header.set_color('blue')
# Create a format for the stock price
f_price = workbook.add_format
f_price.set_align('left')
f_price.set_num_format('$0.00')
# Create a format for the stock volume
f_volume = workbook.add_format
f_volume.set_align('left')
f_volume.set_num_format('#,##0')
# Create a format for the price change. This is an example of a conditional
# format. The number is formatted as a percentage. If it is positive it is
# formatted in green, if it is negative it is formatted in red and if it is
# zero it is formatted as the default font colour (in this case black).
# Note: the [Green] format produces an unappealing lime green. Try
# [Color 10] instead for a dark green.
#
f_change = workbook.add_format
f_change.set_align('left')
f_change.set_num_format('[Green]0.0%;[Red]-0.0%;0.0%')
# Write out the data
worksheet.write(0, 0, 'Company', header)
worksheet.write(0, 1, 'Price', header)
worksheet.write(0, 2, 'Volume', header)
worksheet.write(0, 3, 'Change', header)
worksheet.write(1, 0, 'Damage Inc.' )
worksheet.write(1, 1, 30.25, f_price) # $30.25
worksheet.write(1, 2, 1234567, f_volume) # 1,234,567
worksheet.write(1, 3, 0.085, f_change) # 8.5% in green
worksheet.write(2, 0, 'Dump Corp.' )
worksheet.write(2, 1, 1.56, f_price) # $1.56
worksheet.write(2, 2, 7564, f_volume) # 7,564
worksheet.write(2, 3, -0.015, f_change) # -1.5% in red
worksheet.write(3, 0, 'Rev Ltd.' )
worksheet.write(3, 1, 0.13, f_price) # $0.13
worksheet.write(3, 2, 321, f_volume) # 321
worksheet.write(3, 3, 0, f_change) # 0 in the font color (black)
workbook.close
# do assertion
compare_file("#{PERL_OUTDIR}/stocks.xls", @file)
end
def test_protection
workbook = WriteExcel.new(@file)
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
# do assertion
compare_file("#{PERL_OUTDIR}/protection.xls", @file)
end
def test_password_protection
workbook = WriteExcel.new(@file)
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
# do assertion
compare_file("#{PERL_OUTDIR}/password_protection.xls", @file)
end
def test_date_time
# Create a new workbook and add a worksheet
workbook = WriteExcel.new(@file)
worksheet = workbook.add_worksheet
bold = workbook.add_format(:bold => 1)
# Expand the first column so that the date is visible.
worksheet.set_column("A:B", 30)
# Write the column headers
worksheet.write('A1', 'Formatted date', bold)
worksheet.write('B1', 'Format', bold)
# Examples date and time formats. In the output file compare how changing
# the format codes change the appearance of the date.
#
date_formats = [
'dd/mm/yy',
'mm/dd/yy',
'',
'd mm yy',
'dd mm yy',
'',
'dd m yy',
'dd mm yy',
'dd mmm yy',
'dd mmmm yy',
'',
'dd mm y',
'dd mm yyy',
'dd mm yyyy',
'',
'd mmmm yyyy',
'',
'dd/mm/yy',
'dd/mm/yy hh:mm',
'dd/mm/yy hh:mm:ss',
'dd/mm/yy hh:mm:ss.000',
'',
'hh:mm',
'hh:mm:ss',
'hh:mm:ss.000',
]
# Write the same date and time using each of the above formats. The empty
# string formats create a blank line to make the example clearer.
#
row = 0
date_formats.each do |date_format|
row += 1
next if date_format == ''
# Create a format for the date or time.
format = workbook.add_format(
:num_format => date_format,
:align => 'left'
)
# Write the same date using different formats.
worksheet.write_date_time(row, 0, '2004-08-01T12:30:45.123', format)
worksheet.write(row, 1, date_format)
end
# The following is an example of an invalid date. It is written as a string instead
# of a number. This is also Excel's default behaviour.
#
row += 2
worksheet.write_date_time(row, 0, '2004-13-01T12:30:45.123')
worksheet.write(row, 1, 'Invalid date. Written as string.', bold)
workbook.close
# do assertion
compare_file("#{PERL_OUTDIR}/date_time.xls", @file)
end
def test_diag_border
workbook = WriteExcel.new(@file)
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
# do assertion
compare_file("#{PERL_OUTDIR}/diag_border.xls", @file)
end
def test_headers
workbook = WriteExcel.new(@file)
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
# do assertion
compare_file("#{PERL_OUTDIR}/headers.xls", @file)
end
def test_demo
workbook = WriteExcel.new(@file)
worksheet = workbook.add_worksheet('Demo')
worksheet2 = workbook.add_worksheet('Another sheet')
worksheet3 = workbook.add_worksheet('And another')
bold = workbook.add_format(:bold => 1)
#######################################################################
#
# Write a general heading
#
worksheet.set_column('A:A', 36, bold)
worksheet.set_column('B:B', 20 )
worksheet.set_row(0, 40 )
heading = workbook.add_format(
:bold => 1,
:color => 'blue',
:size => 16,
:merge => 1,
:align => 'vcenter'
)
headings = ['Features of Spreadsheet::WriteExcel', '']
worksheet.write_row('A1', headings, heading)
#######################################################################
#
# Some text examples
#
text_format = workbook.add_format(
:bold => 1,
:italic => 1,
:color => 'red',
:size => 18,
:font =>'Lucida Calligraphy'
)
# A phrase in Cyrillic
unicode = [
"042d0442043e002004440440043004370430002004"+
"3d043000200440044304410441043a043e043c0021"
].pack('H*')
worksheet.write('A2', "Text")
worksheet.write('B2', "Hello Excel")
worksheet.write('A3', "Formatted text")
worksheet.write('B3', "Hello Excel", text_format)
worksheet.write('A4', "Unicode text")
worksheet.write_utf16be_string('B4', unicode)
#######################################################################
#
# Some numeric examples
#
num1_format = workbook.add_format(:num_format => '$#,##0.00')
num2_format = workbook.add_format(:num_format => ' d mmmm yyy')
worksheet.write('A5', "Numbers")
worksheet.write('B5', 1234.56)
worksheet.write('A6', "Formatted numbers")
worksheet.write('B6', 1234.56, num1_format)
worksheet.write('A7', "Formatted numbers")
worksheet.write('B7', 37257, num2_format)
#######################################################################
#
# Formulae
#
worksheet.set_selection('B8')
worksheet.write('A8', 'Formulas and functions, "=SIN(PI()/4)"')
worksheet.write('B8', '=SIN(PI()/4)')
#######################################################################
#
# Hyperlinks
#
worksheet.write('A9', "Hyperlinks")
worksheet.write('B9', 'http://www.perl.com/' )
#######################################################################
#
# Images
#
worksheet.write('A10', "Images")
worksheet.insert_image('B10', "#{TEST_DIR}/republic.png", 16, 8)
#######################################################################
#
# Misc
#
worksheet.write('A18', "Page/printer setup")
worksheet.write('A19', "Multiple worksheets")
workbook.close
# do assertion
compare_file("#{PERL_OUTDIR}/demo.xls", @file)
end
def test_unicode_cyrillic
# Create a Russian worksheet name in utf8.
sheet = [0x0421, 0x0442, 0x0440, 0x0430, 0x043D, 0x0438,
0x0446, 0x0430].pack("U*")
# Create a Russian string.
str = [0x0417, 0x0434, 0x0440, 0x0430, 0x0432, 0x0441,
0x0442, 0x0432, 0x0443, 0x0439, 0x0020, 0x041C,
0x0438, 0x0440, 0x0021].pack("U*")
workbook = WriteExcel.new(@file)
worksheet = workbook.add_worksheet(sheet + '1')
worksheet.set_column('A:A', 18)
worksheet.write('A1', str)
workbook.close
# do assertion
compare_file("#{PERL_OUTDIR}/unicode_cyrillic.xls", @file)
end
def test_defined_name
workbook = WriteExcel.new(@file)
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
# do assertion
compare_file("#{PERL_OUTDIR}/defined_name.xls", @file)
end
def test_chart_area
workbook = WriteExcel.new(@file)
worksheet = workbook.add_worksheet
bold = workbook.add_format(:bold => 1)
# Add the data to the worksheet 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::Area')
# 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::Area')
# 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::Area')
# 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::Area')
# 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::Area', :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
# do assertion
compare_file("#{PERL_OUTDIR}/chart_area.xls", @file)
end
def test_chart_bar
workbook = WriteExcel.new(@file)
worksheet = workbook.add_worksheet
bold = workbook.add_format(:bold => 1)
# Add the data to the worksheet 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
# do assertion
compare_file("#{PERL_OUTDIR}/chart_bar.xls", @file)
end
def test_chart_column
workbook = WriteExcel.new(@file)
worksheet = workbook.add_worksheet
bold = workbook.add_format(:bold => 1)
# Add the data to the worksheet 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::Column')
# 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::Column')
# 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::Column')
# 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::Column')
# 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::Column', :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
# do assertion
compare_file("#{PERL_OUTDIR}/chart_column.xls", @file)
end
def test_chart_line
workbook = WriteExcel.new(@file)
worksheet = workbook.add_worksheet
bold = workbook.add_format(:bold => 1)
# Add the data to the worksheet 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::Line')
# 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::Line')
# 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::Line')
# 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::Line')
# 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::Line', :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
# do assertion
compare_file("#{PERL_OUTDIR}/chart_line.xls", @file)
end
def test_chess
workbook = WriteExcel.new(@file)
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
# do assertion
compare_file("#{PERL_OUTDIR}/chess.xls", @file)
end
def test_colors
workbook = WriteExcel.new(@file)
# Some common formats
center = workbook.add_format(:align => 'center')
heading = workbook.add_format(:align => 'center', :bold => 1)
######################################################################
#
# Demonstrate the named colors.
#
order = [
0x21,
0x0B,
0x35,
0x11,
0x16,
0x12,
0x0D,
0x10,
0x17,
0x09,
0x0C,
0x0F,
0x0E,
0x14,
0x08,
0x0A
]
colors = {
0x08 => 'black',
0x0C => 'blue',
0x10 => 'brown',
0x0F => 'cyan',
0x17 => 'gray',
0x11 => 'green',
0x0B => 'lime',
0x0E => 'magenta',
0x12 => 'navy',
0x35 => 'orange',
0x21 => 'pink',
0x14 => 'purple',
0x0A => 'red',
0x16 => 'silver',
0x09 => 'white',
0x0D => 'yellow',
}
worksheet1 = workbook.add_worksheet('Named colors')
worksheet1.set_column(0, 3, 15)
worksheet1.write(0, 0, "Index", heading)
worksheet1.write(0, 1, "Index", heading)
worksheet1.write(0, 2, "Name", heading)
worksheet1.write(0, 3, "Color", heading)
i = 1
# original was colors.each....
# order unmatch between perl and ruby (of cource, it's hash!)
# so i use order array to match perl's xls order.
#
order.each do |index|
format = workbook.add_format(
:fg_color => colors[index],
:pattern => 1,
:border => 1
)
worksheet1.write(i + 1, 0, index, center)
worksheet1.write(i + 1, 1, sprintf("0x%02X", index), center)
worksheet1.write(i + 1, 2, colors[index], center)
worksheet1.write(i + 1, 3, '', format)
i += 1
end
######################################################################
#
# Demonstrate the standard Excel colors in the range 8..63.
#
worksheet2 = workbook.add_worksheet('Standard colors')
worksheet2.set_column(0, 3, 15)
worksheet2.write(0, 0, "Index", heading)
worksheet2.write(0, 1, "Index", heading)
worksheet2.write(0, 2, "Color", heading)
worksheet2.write(0, 3, "Name", heading)
(8..63).each do |i|
format = workbook.add_format(
:fg_color => i,
:pattern => 1,
:border => 1
)
worksheet2.write((i - 7), 0, i, center)
worksheet2.write((i - 7), 1, sprintf("0x%02X", i), center)
worksheet2.write((i - 7), 2, '', format)
# Add the color names
if colors.has_key?(i)
worksheet2.write((i - 7), 3, colors[i], center)
end
end
workbook.close
# do assertion
compare_file("#{PERL_OUTDIR}/colors.xls", @file)
end
def test_comments0
workbook = WriteExcel.new(@file)
worksheet = workbook.add_worksheet
worksheet.write(0, 0, 'Hello a1')
worksheet.write(0, 1, 'Hello b1')
worksheet.write(1, 0, 'Hello a2')
worksheet.write(1, 1, 'Hello b2')
worksheet.write_comment('A1', 'This is a comment a1', :author=>'arr')
worksheet.write_comment('A2', 'This is a comment a2', :author=>'arr')
worksheet.write_comment('B1', 'This is a comment b1', :author=>'arr')
worksheet.write_comment('B2', 'This is a comment b2', :author=>'arr')
workbook.close
# do assertion
compare_file("#{PERL_OUTDIR}/comments0.xls", @file)
end
def test_comments1
workbook = WriteExcel.new(@file)
worksheet = workbook.add_worksheet
worksheet.write('A1', 'Hello')
worksheet.write_comment('A1', 'This is a comment')
workbook.close
# do assertion
compare_file("#{PERL_OUTDIR}/comments1.xls", @file)
end
def test_comments2
workbook = WriteExcel.new(@file)
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
# do assertion
compare_file("#{PERL_OUTDIR}/comments2.xls", @file)
end
def test_formula_result
workbook = WriteExcel.new(@file)
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
# do assertion
compare_file("#{PERL_OUTDIR}/formula_result.xls", @file)
end
def test_indent
workbook = WriteExcel.new(@file)
worksheet = workbook.add_worksheet()
indent1 = workbook.add_format(:indent => 1)
indent2 = workbook.add_format(:indent => 2)
worksheet.set_column('A:A', 40)
worksheet.write('A1', "This text is indented 1 level", indent1)
worksheet.write('A2', "This text is indented 2 levels", indent2)
workbook.close
# do assertion
compare_file("#{PERL_OUTDIR}/indent.xls", @file)
end
def test_outline
# Create a new workbook and add some worksheets
workbook = WriteExcel.new(@file)
worksheet1 = workbook.add_worksheet('Outlined Rows')
worksheet2 = workbook.add_worksheet('Collapsed Rows')
worksheet3 = workbook.add_worksheet('Outline Columns')
worksheet4 = workbook.add_worksheet('Outline levels')
# Add a general format
bold = workbook.add_format(:bold => 1)
###############################################################################
#
# Example 1: Create a worksheet with outlined rows. It also includes SUBTOTAL()
# functions so that it looks like the type of automatic outlines that are
# generated when you use the Excel Data->SubTotals menu item.
#
# For outlines the important parameters are $hidden and $level. Rows with the
# same $level are grouped together. The group will be collapsed if $hidden is
# non-zero. $height and $XF are assigned default values if they are undef.
#
# The syntax is: set_row($row, $height, $XF, $hidden, $level, $collapsed)
#
worksheet1.set_row(1, nil, nil, 0, 2)
worksheet1.set_row(2, nil, nil, 0, 2)
worksheet1.set_row(3, nil, nil, 0, 2)
worksheet1.set_row(4, nil, nil, 0, 2)
worksheet1.set_row(5, nil, nil, 0, 1)
worksheet1.set_row(6, nil, nil, 0, 2)
worksheet1.set_row(7, nil, nil, 0, 2)
worksheet1.set_row(8, nil, nil, 0, 2)
worksheet1.set_row(9, nil, nil, 0, 2)
worksheet1.set_row(10, nil, nil, 0, 1)
# Add a column format for clarity
worksheet1.set_column('A:A', 20)
# Add the data, labels and formulas
worksheet1.write('A1', 'Region', bold)
worksheet1.write('A2', 'North')
worksheet1.write('A3', 'North')
worksheet1.write('A4', 'North')
worksheet1.write('A5', 'North')
worksheet1.write('A6', 'North Total', bold)
worksheet1.write('B1', 'Sales', bold)
worksheet1.write('B2', 1000)
worksheet1.write('B3', 1200)
worksheet1.write('B4', 900)
worksheet1.write('B5', 1200)
worksheet1.write('B6', '=SUBTOTAL(9,B2:B5)', bold)
worksheet1.write('A7', 'South')
worksheet1.write('A8', 'South')
worksheet1.write('A9', 'South')
worksheet1.write('A10', 'South')
worksheet1.write('A11', 'South Total', bold)
worksheet1.write('B7', 400)
worksheet1.write('B8', 600)
worksheet1.write('B9', 500)
worksheet1.write('B10', 600)
worksheet1.write('B11', '=SUBTOTAL(9,B7:B10)', bold)
worksheet1.write('A12', 'Grand Total', bold)
worksheet1.write('B12', '=SUBTOTAL(9,B2:B10)', bold)
###############################################################################
#
# Example 2: Create a worksheet with outlined rows. This is the same as the
# previous example except that the rows are collapsed.
# Note: We need to indicate the row that contains the collapsed symbol '+'
# with the optional parameter, $collapsed.
# The group will be collapsed if $hidden is non-zero.
# The syntax is: set_row($row, $height, $XF, $hidden, $level, $collapsed)
#
worksheet2.set_row(1, nil, nil, 1, 2)
worksheet2.set_row(2, nil, nil, 1, 2)
worksheet2.set_row(3, nil, nil, 1, 2)
worksheet2.set_row(4, nil, nil, 1, 2)
worksheet2.set_row(5, nil, nil, 1, 1)
worksheet2.set_row(6, nil, nil, 1, 2)
worksheet2.set_row(7, nil, nil, 1, 2)
worksheet2.set_row(8, nil, nil, 1, 2)
worksheet2.set_row(9, nil, nil, 1, 2)
worksheet2.set_row(10, nil, nil, 1, 1)
worksheet2.set_row(11, nil, nil, 0, 0, 1)
# Add a column format for clarity
worksheet2.set_column('A:A', 20)
# Add the data, labels and formulas
worksheet2.write('A1', 'Region', bold)
worksheet2.write('A2', 'North')
worksheet2.write('A3', 'North')
worksheet2.write('A4', 'North')
worksheet2.write('A5', 'North')
worksheet2.write('A6', 'North Total', bold)
worksheet2.write('B1', 'Sales', bold)
worksheet2.write('B2', 1000)
worksheet2.write('B3', 1200)
worksheet2.write('B4', 900)
worksheet2.write('B5', 1200)
worksheet2.write('B6', '=SUBTOTAL(9,B2:B5)', bold)
worksheet2.write('A7', 'South')
worksheet2.write('A8', 'South')
worksheet2.write('A9', 'South')
worksheet2.write('A10', 'South')
worksheet2.write('A11', 'South Total', bold)
worksheet2.write('B7', 400)
worksheet2.write('B8', 600)
worksheet2.write('B9', 500)
worksheet2.write('B10', 600)
worksheet2.write('B11', '=SUBTOTAL(9,B7:B10)', bold)
worksheet2.write('A12', 'Grand Total', bold)
worksheet2.write('B12', '=SUBTOTAL(9,B2:B10)', bold)
###############################################################################
#
# Example 3: Create a worksheet with outlined columns.
#
data = [
['Month', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', ' Total'],
['North', 50, 20, 15, 25, 65, 80, '=SUM(B2:G2)'],
['South', 10, 20, 30, 50, 50, 50, '=SUM(B3:G3)'],
['East', 45, 75, 50, 15, 75, 100, '=SUM(B4:G4)'],
['West', 15, 15, 55, 35, 20, 50, '=SUM(B5:G6)']
]
# Add bold format to the first row
worksheet3.set_row(0, nil, bold)
# Syntax: set_column(col1, col2, width, XF, hidden, level, collapsed)
worksheet3.set_column('A:A', 10, bold )
worksheet3.set_column('B:G', 5, nil, 0, 1)
worksheet3.set_column('H:H', 10)
# Write the data and a formula
worksheet3.write_col('A1', data)
worksheet3.write('H6', '=SUM(H2:H5)', bold)
###############################################################################
#
# Example 4: Show all possible outline levels.
#
levels = [
"Level 1", "Level 2", "Level 3", "Level 4",
"Level 5", "Level 6", "Level 7", "Level 6",
"Level 5", "Level 4", "Level 3", "Level 2", "Level 1"
]
worksheet4.write_col('A1', levels)
worksheet4.set_row(0, nil, nil, nil, 1)
worksheet4.set_row(1, nil, nil, nil, 2)
worksheet4.set_row(2, nil, nil, nil, 3)
worksheet4.set_row(3, nil, nil, nil, 4)
worksheet4.set_row(4, nil, nil, nil, 5)
worksheet4.set_row(5, nil, nil, nil, 6)
worksheet4.set_row(6, nil, nil, nil, 7)
worksheet4.set_row(7, nil, nil, nil, 6)
worksheet4.set_row(8, nil, nil, nil, 5)
worksheet4.set_row(9, nil, nil, nil, 4)
worksheet4.set_row(10, nil, nil, nil, 3)
worksheet4.set_row(11, nil, nil, nil, 2)
worksheet4.set_row(12, nil, nil, nil, 1)
workbook.close
# do assertion
compare_file("#{PERL_OUTDIR}/outline.xls", @file)
end
def test_outline_collapsed
# Create a new workbook and add some worksheets
workbook = WriteExcel.new(@file)
worksheet1 = workbook.add_worksheet('Outlined Rows')
worksheet2 = workbook.add_worksheet('Collapsed Rows 1')
worksheet3 = workbook.add_worksheet('Collapsed Rows 2')
worksheet4 = workbook.add_worksheet('Collapsed Rows 3')
worksheet5 = workbook.add_worksheet('Outline Columns')
worksheet6 = workbook.add_worksheet('Collapsed Columns')
# Add a general format
bold = workbook.add_format(:bold => 1)
#
# This function will generate the same data and sub-totals on each worksheet.
#
def create_sub_totals(worksheet, bold)
# Add a column format for clarity
worksheet.set_column('A:A', 20)
# Add the data, labels and formulas
worksheet.write('A1', 'Region', bold)
worksheet.write('A2', 'North')
worksheet.write('A3', 'North')
worksheet.write('A4', 'North')
worksheet.write('A5', 'North')
worksheet.write('A6', 'North Total', bold)
worksheet.write('B1', 'Sales', bold)
worksheet.write('B2', 1000)
worksheet.write('B3', 1200)
worksheet.write('B4', 900)
worksheet.write('B5', 1200)
worksheet.write('B6', '=SUBTOTAL(9,B2:B5)', bold)
worksheet.write('A7', 'South')
worksheet.write('A8', 'South')
worksheet.write('A9', 'South')
worksheet.write('A10', 'South')
worksheet.write('A11', 'South Total', bold)
worksheet.write('B7', 400)
worksheet.write('B8', 600)
worksheet.write('B9', 500)
worksheet.write('B10', 600)
worksheet.write('B11', '=SUBTOTAL(9,B7:B10)', bold)
worksheet.write('A12', 'Grand Total', bold)
worksheet.write('B12', '=SUBTOTAL(9,B2:B10)', bold)
end
###############################################################################
#
# Example 1: Create a worksheet with outlined rows. It also includes SUBTOTAL()
# functions so that it looks like the type of automatic outlines that are
# generated when you use the Excel Data.SubTotals menu item.
#
# The syntax is: set_row(row, height, XF, hidden, level, collapsed)
worksheet1.set_row(1, nil, nil, 0, 2)
worksheet1.set_row(2, nil, nil, 0, 2)
worksheet1.set_row(3, nil, nil, 0, 2)
worksheet1.set_row(4, nil, nil, 0, 2)
worksheet1.set_row(5, nil, nil, 0, 1)
worksheet1.set_row(6, nil, nil, 0, 2)
worksheet1.set_row(7, nil, nil, 0, 2)
worksheet1.set_row(8, nil, nil, 0, 2)
worksheet1.set_row(9, nil, nil, 0, 2)
worksheet1.set_row(10, nil, nil, 0, 1)
# Write the sub-total data that is common to the row examples.
create_sub_totals(worksheet1, bold)
###############################################################################
#
# Example 2: Create a worksheet with collapsed outlined rows.
# This is the same as the example 1 except that the all rows are collapsed.
# Note: We need to indicate the row that contains the collapsed symbol '+' with
# the optional parameter, collapsed.
worksheet2.set_row(1, nil, nil, 1, 2)
worksheet2.set_row(2, nil, nil, 1, 2)
worksheet2.set_row(3, nil, nil, 1, 2)
worksheet2.set_row(4, nil, nil, 1, 2)
worksheet2.set_row(5, nil, nil, 1, 1)
worksheet2.set_row(6, nil, nil, 1, 2)
worksheet2.set_row(7, nil, nil, 1, 2)
worksheet2.set_row(8, nil, nil, 1, 2)
worksheet2.set_row(9, nil, nil, 1, 2)
worksheet2.set_row(10, nil, nil, 1, 1)
worksheet2.set_row(11, nil, nil, 0, 0, 1)
# Write the sub-total data that is common to the row examples.
create_sub_totals(worksheet2, bold)
###############################################################################
#
# Example 3: Create a worksheet with collapsed outlined rows.
# Same as the example 1 except that the two sub-totals are collapsed.
worksheet3.set_row(1, nil, nil, 1, 2)
worksheet3.set_row(2, nil, nil, 1, 2)
worksheet3.set_row(3, nil, nil, 1, 2)
worksheet3.set_row(4, nil, nil, 1, 2)
worksheet3.set_row(5, nil, nil, 0, 1, 1)
worksheet3.set_row(6, nil, nil, 1, 2)
worksheet3.set_row(7, nil, nil, 1, 2)
worksheet3.set_row(8, nil, nil, 1, 2)
worksheet3.set_row(9, nil, nil, 1, 2)
worksheet3.set_row(10, nil, nil, 0, 1, 1)
# Write the sub-total data that is common to the row examples.
create_sub_totals(worksheet3, bold)
###############################################################################
#
# Example 4: Create a worksheet with outlined rows.
# Same as the example 1 except that the two sub-totals are collapsed.
worksheet4.set_row(1, nil, nil, 1, 2)
worksheet4.set_row(2, nil, nil, 1, 2)
worksheet4.set_row(3, nil, nil, 1, 2)
worksheet4.set_row(4, nil, nil, 1, 2)
worksheet4.set_row(5, nil, nil, 1, 1, 1)
worksheet4.set_row(6, nil, nil, 1, 2)
worksheet4.set_row(7, nil, nil, 1, 2)
worksheet4.set_row(8, nil, nil, 1, 2)
worksheet4.set_row(9, nil, nil, 1, 2)
worksheet4.set_row(10, nil, nil, 1, 1, 1)
worksheet4.set_row(11, nil, nil, 0, 0, 1)
# Write the sub-total data that is common to the row examples.
create_sub_totals(worksheet4, bold)
###############################################################################
#
# Example 5: Create a worksheet with outlined columns.
#
data = [
['Month', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',' Total'],
['North', 50, 20, 15, 25, 65, 80, '=SUM(B2:G2)'],
['South', 10, 20, 30, 50, 50, 50, '=SUM(B3:G3)'],
['East', 45, 75, 50, 15, 75, 100, '=SUM(B4:G4)'],
['West', 15, 15, 55, 35, 20, 50, '=SUM(B5:G6)']
]
# Add bold format to the first row
worksheet5.set_row(0, nil, bold)
# Syntax: set_column(col1, col2, width, XF, hidden, level, collapsed)
worksheet5.set_column('A:A', 10, bold )
worksheet5.set_column('B:G', 5, nil, 0, 1)
worksheet5.set_column('H:H', 10 )
# Write the data and a formula
worksheet5.write_col('A1', data)
worksheet5.write('H6', '=SUM(H2:H5)', bold)
###############################################################################
#
# Example 6: Create a worksheet with collapsed outlined columns.
# This is the same as the previous example except collapsed columns.
# Add bold format to the first row
worksheet6.set_row(0, nil, bold)
# Syntax: set_column(col1, col2, width, XF, hidden, level, collapsed)
worksheet6.set_column('A:A', 10, bold )
worksheet6.set_column('B:G', 5, nil, 1, 1 )
worksheet6.set_column('H:H', 10, nil, 0, 0, 1)
# Write the data and a formula
worksheet6.write_col('A1', data)
worksheet6.write('H6', '=SUM(H2:H5)', bold)
workbook.close
# do assertion
compare_file("#{PERL_OUTDIR}/outline_collapsed.xls", @file)
end
def test_panes
workbook = WriteExcel.new(@file)
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
# do assertion
compare_file("#{PERL_OUTDIR}/panes.xls", @file)
end
def test_right_to_left
workbook = WriteExcel.new(@file)
worksheet1 = workbook.add_worksheet
worksheet2 = workbook.add_worksheet
worksheet2.right_to_left
worksheet1.write(0, 0, 'Hello') # A1, B1, C1, ...
worksheet2.write(0, 0, 'Hello') # ..., C1, B1, A1
workbook.close
# do assertion
compare_file("#{PERL_OUTDIR}/right_to_left.xls", @file)
end
def test_utf8
workbook = WriteExcel.new(@file)
worksheet = workbook.add_worksheet('シート1')
format = workbook.add_format(:font => 'MS 明朝')
worksheet.set_footer('フッター')
worksheet.set_header('ヘッダー')
worksheet.write('A1', 'UTF8文字列', format)
worksheet.write('A2', '=CONCATENATE(A1,"の連結")', format)
workbook.close
# do assertion
compare_file("#{PERL_OUTDIR}/utf8.xls", @file)
end
def test_hide_zero
workbook = WriteExcel.new(@file)
worksheet = workbook.add_worksheet
worksheet.write(0, 0, 'C2, E2 value is zero, not displayed')
worksheet.write(1, 0, 1)
worksheet.write(1, 1, 2)
worksheet.write(1, 2, 0)
worksheet.write(1, 3, 4)
worksheet.write(1, 4, 0)
worksheet.hide_zero
workbook.close
# do assertion
compare_file("#{PERL_OUTDIR}/hide_zero.xls", @file)
end
def test_set_first_sheet
workbook = WriteExcel.new(@file)
20.times { workbook.add_worksheet }
worksheet21 = workbook.add_worksheet
worksheet22 = workbook.add_worksheet
worksheet21.set_first_sheet
worksheet22.activate
workbook.close
# do assertion
compare_file("#{PERL_OUTDIR}/set_first_sheet.xls", @file)
end
def test_sheet_name
workbook = WriteExcel.new(@file)
worksheet = workbook.add_worksheet("Second")
worksheet.write(0, 0, 2)
worksheet = workbook.add_worksheet("First")
worksheet.write(0, 0, 1)
worksheet = workbook.add_worksheet("Third")
worksheet.write(0, 0, "First :")
worksheet.write_formula(0, 1, %q{='First'!A1})
worksheet.write(1, 0, "Second :")
worksheet.write_formula(1, 1, %q{='Second'!A1})
workbook.close
# do assertion
compare_file("#{PERL_OUTDIR}/sheet_name.xls", @file)
end
def test_store_formula
workbook = WriteExcel.new(@file)
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
# do assertion
compare_file("#{PERL_OUTDIR}/store_formula.xls", @file)
end
def test_more_than_10_sheets_reference
workbook = WriteExcel.new(@file)
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
worksheet9 = workbook.add_worksheet
worksheet10 = workbook.add_worksheet
worksheet11 = workbook.add_worksheet
worksheet2.write(0, 0, 'worksheet2')
worksheet3.write(0, 0, 'worksheet3')
worksheet4.write(0, 0, 'worksheet4')
worksheet5.write(0, 0, 'worksheet5')
worksheet6.write(0, 0, 'worksheet6')
worksheet7.write(0, 0, 'worksheet7')
worksheet8.write(0, 0, 'worksheet8')
worksheet9.write(0, 0, 'worksheet9')
worksheet10.write(0, 0, 'worksheet10')
worksheet11.write(0, 0, 'worksheet11')
worksheet1.write(0, 2, '=Sheet2!A1')
worksheet1.write(0, 3, '=Sheet3!A1')
worksheet1.write(0, 4, '=Sheet4!A1')
worksheet1.write(0, 5, '=Sheet5!A1')
worksheet1.write(0, 6, '=Sheet6!A1')
worksheet1.write(0, 7, '=Sheet7!A1')
worksheet1.write(0, 8, '=Sheet8!A1')
worksheet1.write(0, 9, '=Sheet9!A1')
worksheet1.write(0, 10, '=Sheet10!A1')
worksheet1.write(0, 11, '=Sheet11!A1')
workbook.close
# do assertion
compare_file("#{PERL_OUTDIR}/more_than_10_sheets_reference.xls", @file)
end
def test_compatibility_mode_write_string
workbook = WriteExcel.new(@file)
workbook.compatibility_mode
worksheet = workbook.add_worksheet('DataSheet')
worksheet.write_string(0,0,'Cell00')
worksheet.write_string(0,1,'Cell01')
workbook.close
# do assertion
compare_file("#{PERL_OUTDIR}/compatibility_mode_write_string.xls", @file)
end
def test_compatibility_mode_write_number
workbook = WriteExcel.new(@file)
workbook.compatibility_mode
worksheet = workbook.add_worksheet('DataSheet')
worksheet.write_number(0,0,100)
worksheet.write_number(0,1,200)
workbook.close
# do assertion
compare_file("#{PERL_OUTDIR}/compatibility_mode_write_number.xls", @file)
end
def test_properties
tz = ENV["TZ"]
workbook = WriteExcel.new(@file)
#
# adjust @localtime to target xls file.
#
ENV["TZ"] = "Japan"
workbook.instance_variable_set(
:@localtime,
Time.gm(2013, 5, 5, 13, 37, 42).localtime
)
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
# do assertion
compare_file("#{PERL_OUTDIR}/properties.xls", @file)
ENV["TZ"] = tz
end
def test_chart_legend
workbook = WriteExcel.new(@file)
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
# do assertion
compare_file("#{PERL_OUTDIR}/chart_legend.xls", @file)
end
end
|
Radanisk/writeexcel
|
lib/writeexcel/helper.rb
|
# -*- coding: utf-8 -*-
#
# helper.rb
#
# Convert to US_ASCII encoding if ascii characters only.
def convert_to_ascii_if_ascii(str)
return nil if str.nil?
ruby_18 do
unless str =~ /[^!"#\$%&'\(\)\*\+,\-\.\/\:\;<=>\?@0-9A-Za-z_\[\\\]\{\}^` ~\0\n]/
str = String.new(str)
end
end ||
ruby_19 do
if str.ascii_only?
str = [str].pack('a*')
end
end
str
end
private :convert_to_ascii_if_ascii
def utf16be_to_16le(utf16be)
utf16be.unpack('n*').pack('v*')
end
def utf8_to_16be(utf8)
ruby_18 { NKF.nkf('-w16B0 -m0 -W', utf8) } ||
ruby_19 do
utf16be = utf8.encode('UTF-16BE')
utf16be.force_encoding('UTF-16BE')
end
end
private :utf8_to_16be
def utf8_to_16le(utf8)
ruby_18 { NKF.nkf('-w16L0 -m0 -W', utf8) } ||
ruby_19 do
utf16le = utf8.encode('UTF-16LE')
utf16le.force_encoding('UTF-16LE')
end
end
private :utf8_to_16le
def ascii_to_16be(ascii)
str_16be = ascii.unpack("C*").pack("n*")
ruby_19 { str_16be.force_encoding('UTF-16BE') }
str_16be
end
private :ascii_to_16be
def store_simple(record, length, *args)
header = [record, length].pack('vv')
data = args.collect { |arg| [arg].pack('v') }.join('')
append(header, data)
end
private :store_simple
# Convert base26 column string to a number.
# All your Base are belong to us.
def chars_to_col(chars)
expn = 0
col = 0
while (!chars.empty?)
char = chars.pop # LS char first
col += (char.ord - "A".ord + 1) * (26 ** expn)
expn += 1
end
col
end
private :chars_to_col
NonAscii = /[^!"#\$%&'\(\)\*\+,\-\.\/\:\;<=>\?@0-9A-Za-z_\[\\\]\{\}^` ~\0\n]/
def is_utf8?(str)
ruby_18 { str =~ NonAscii } ||
ruby_19 { str.encoding == Encoding::UTF_8 }
end
|
Radanisk/writeexcel
|
lib/writeexcel/charts/external.rb
|
# -*- coding: utf-8 -*-
###############################################################################
#
# External - A writer class for Excel external charts.
#
# Used in conjunction with WriteExcel
#
# perltidy with options: -mbl=2 -pt=0 -nola
#
# Copyright 2000-2010, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel/chart'
module Writeexcel
class External < Chart # :nodoc:
###############################################################################
#
# new()
#
def initialize(external_filename, *args)
super(*args)
@filename = external_filename
@external_bin = true
_initialize # Requires overridden initialize().
self
end
###############################################################################
#
# _initialize()
#
# Read all the data into memory for the external binary style chart.
#
def _initialize
filename = @filename
filehandle = File.open(filename, 'rb')
@filehandle = filehandle
@datasize = FileTest.size(filename)
@using_tmpfile = false
# Read the entire external chart binary into the the data buffer.
# This will be retrieved by _get_data() when the chart is closed().
@data = @filehandle.read(@datasize)
end
###############################################################################
#
# _close()
#
# We don't need to create or store Chart data structures when using an
# external binary, so we have a default close method.
#
def close
nil
end
end # class Chart
end # module Writeexcel
|
Radanisk/writeexcel
|
lib/writeexcel/chart.rb
|
<reponame>Radanisk/writeexcel
# -*- coding: utf-8 -*-
###############################################################################
#
# Chart - A writer class for Excel Charts.
#
#
# Used in conjunction with WriteExcel
#
# Copyright 2000-2010, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel/worksheet'
require 'writeexcel/colors'
###############################################################################
#
# Formatting information.
#
# perltidy with options: -mbl=2 -pt=0 -nola
#
# Any camel case Hungarian notation style variable names in the BIFF record
# writing sub-routines below are for similarity with names used in the Excel
# documentation. Otherwise lowercase underscore style names are used.
#
###############################################################################
#
# The chart class hierarchy is as follows. Chart.pm acts as a factory for the
# sub-classes.
#
#
# BIFFwriter
# ^
# |
# Writeexcel::Worksheet
# ^
# |
# Writeexcel::Chart
# ^
# |
# Writeexcel::Chart::* (sub-types)
#
#
# = Chart
# Chart - A writer class for Excel Charts.
#
module Writeexcel
class Chart < Worksheet
require 'writeexcel/helper'
#
# Factory method for returning chart objects based on their class type.
#
def self.factory(type, *args) #:nodoc:
klass =
case type
when 'Chart::Column'
Chart::Column
when 'Chart::Bar'
Chart::Bar
when 'Chart::Line'
Chart::Line
when 'Chart::Area'
Chart::Area
when 'Chart::Pie'
Chart::Pie
when 'Chart::Scatter'
Chart::Scatter
when 'Chart::Stock'
Chart::Stock
end
klass.new(*args)
end
#
# :call-seq:
# new(filename, name, index, encoding, activesheet, firstsheet, external_bin = nil)
#
# Default constructor for sub-classes.
#
def initialize(*args) #:nodoc:
super
@type = 0x0200
@orientation = 0x0
@series = []
@embedded = false
@external_bin = false
@x_axis_formula = nil
@x_axis_name = nil
@y_axis_formula = nil
@y_axis_name = nil
@title_name = nil
@title_formula = nil
@vary_data_color = 0
set_default_properties
set_default_config_data
end
#
# Add a series and it's properties to a chart.
#
# In an Excel chart a "series" is a collection of information such as values,
# x-axis labels and the name that define which data is plotted. These
# settings are displayed when you select the Chart -> Source Data... menu
# option.
#
# With a WriteExcel chart object the add_series() method is used to set the
# properties for a series:
#
# chart.add_series(
# :categories => '=Sheet1!$A$2:$A$10',
# :values => '=Sheet1!$B$2:$B$10',
# :name => 'Series name',
# :name_formula => '=Sheet1!$B$1'
# )
#
# The properties that can be set are:
#
# :values (required)
# :categories (optional for most chart types)
# :name (optional)
# :name_formula (optional)
#
# * :values
#
# This is the most important property of a series and must be set for
# every chart object. It links the chart with the worksheet data that
# it displays.
#
# chart.add_series(:values => '=Sheet1!$B$2:$B$10')
#
# Note the format that should be used for the formula. It is the same
# as is used in Excel. You must also add the worksheet that you are
# referring to before you link to it, via the workbook
# add_worksheet() method.
#
# * :categories
#
# This sets the chart category labels. The category is more or less
# the same as the X-axis. In most chart types the categories property
# is optional and the chart will just assume a sequential series
# from 1 .. n.
#
# chart.add_series(
# :categories => '=Sheet1!$A$2:$A$10',
# :values => '=Sheet1!$B$2:$B$10'
# )
#
# * :name
#
# Set the name for the series. The name is displayed in the chart
# legend and in the formula bar. The name property is optional and
# if it isn't supplied will default to Series 1 .. n.
#
# chart.add_series(
# ...
# :name => 'Series name'
# )
#
# * :name_formula
#
# Optional, can be used to link the name to a worksheet cell.
# See "Chart names and links".
#
# chart.add_series(
# ...
# :name => 'Series name',
# :name_formula => '=Sheet1!$B$1'
# )
#
# You can add more than one series to a chart. The series numbering and
# order in the final chart is the same as the order in which that are added.
#
# # Add the first series.
# chart.add_series(
# :categories => '=Sheet1!$A$2:$A$7',
# :values => '=Sheet1!$B$2:$B$7',
# :name => 'Test data series 1'
# )
#
# # Add another series. Category is the same but values are different.
# chart.add_series(
# :categories => '=Sheet1!$A$2:$A$7',
# :values => '=Sheet1!$C$2:$C$7',
# :name => 'Test data series 2'
# )
#
def add_series(params)
raise "Must specify 'values' in add_series()" if params[:values].nil?
# Parse the ranges to validate them and extract salient information.
value_data = parse_series_formula(params[:values])
category_data = parse_series_formula(params[:categories])
name_formula = parse_series_formula(params[:name_formula])
# Default category count to the same as the value count if not defined.
category_data[1] = value_data[1] if category_data.size < 2
# Add the parsed data to the user supplied data.
params[:values] = value_data
params[:categories] = category_data
params[:name_formula] = name_formula
# Encode the Series name.
name, encoding = encode_utf16(params[:name], params[:name_encoding])
params[:name] = name
params[:name_encoding] = encoding
@series << params
end
#
# Set the properties of the X-axis.
#
# The set_x_axis() method is used to set properties of the X axis.
#
# chart.set_x_axis(:name => 'Sample length (m)' )
#
# The properties that can be set are:
#
# :name (optional)
# :name_formula (optional)
#
# * :name
#
# Set the name (title or caption) for the axis. The name is displayed
# below the X axis. This property is optional. The default is to have
# no axis name.
#
# chart.set_x_axis( :name => 'Sample length (m)' )
#
# * :name_formula
#
# Optional, can be used to link the name to a worksheet cell.
# See "Chart names and links".
#
# chart.set_x_axis(
# :name => 'Sample length (m)',
# :name_formula => '=Sheet1!$A$1'
# )
#
# Additional axis properties such as range, divisions and ticks will be made
# available in later releases.
def set_x_axis(params)
name, encoding = encode_utf16(params[:name], params[:name_encoding])
formula = parse_series_formula(params[:name_formula])
@x_axis_name = name
@x_axis_encoding = encoding
@x_axis_formula = formula
end
#
# Set the properties of the Y-axis.
#
# The set_y_axis() method is used to set properties of the Y axis.
#
# chart.set_y_axis(:name => 'Sample weight (kg)' )
#
# The properties that can be set are:
#
# :name (optional)
# :name_formula (optional)
#
# * :name
#
# Set the name (title or caption) for the axis. The name is displayed
# to the left of the Y axis. This property is optional. The default
# is to have no axis name.
#
# chart.set_y_axis(:name => 'Sample weight (kg)' )
#
# * :name_formula
#
# Optional, can be used to link the name to a worksheet cell.
# See "Chart names and links".
#
# chart.set_y_axis(
# :name => 'Sample weight (kg)',
# :name_formula => '=Sheet1!$B$1'
# )
#
# Additional axis properties such as range, divisions and ticks will be made
# available in later releases.
#
def set_y_axis(params)
name, encoding = encode_utf16(params[:name], params[:name_encoding])
formula = parse_series_formula(params[:name_formula])
@y_axis_name = name
@y_axis_encoding = encoding
@y_axis_formula = formula
end
#
# The set_title() method is used to set properties of the chart title.
#
# chart.set_title(:name => 'Year End Results')
#
# The properties that can be set are:
#
# :name (optional)
# :name_formula (optional)
#
# * :name
#
# Set the name (title) for the chart. The name is displayed above the
# chart. This property is optional. The default is to have no chart
# title.
#
# chart.set_title(:name => 'Year End Results')
#
# * :name_formula
#
# Optional, can be used to link the name to a worksheet cell.
# See "Chart names and links".
#
# chart.set_title(
# :name => 'Year End Results',
# :name_formula => '=Sheet1!$C$1'
# )
#
def set_title(params)
name, encoding = encode_utf16( params[:name], params[:name_encoding])
formula = parse_series_formula(params[:name_formula])
@title_name = name
@title_encoding = encoding
@title_formula = formula
end
#
# Set the properties of the chart legend.
#
def set_legend(params = {})
if params.has_key?(:position)
if params[:position].downcase == 'none'
@legend[:visible] = 0
end
end
end
#
# Set the properties of the chart plotarea.
#
def set_plotarea(params = {})
return if params.empty?
area = @plotarea
# Set the plotarea visibility.
if params.has_key?(:visible)
area[:visible] = params[:visible]
return if area[:visible] == 0
end
# TODO. could move this out of if statement.
area[:bg_color_index] = 0x08
# Set the chart background colour.
if params.has_key?(:color)
index, rgb = get_color_indices(params[:color])
if !index.nil?
area[:fg_color_index] = index
area[:fg_color_rgb] = rgb
area[:bg_color_index] = 0x08
area[:bg_color_rgb] = 0x000000
end
end
# Set the border line colour.
if params.has_key?(:line_color)
index, rgb = get_color_indices(params[:line_color])
if !index.nil?
area[:line_color_index] = index
area[:line_color_rgb] = rgb
end
end
# Set the border line pattern.
if params.has_key?(:line_pattern)
pattern = get_line_pattern(params[:line_pattern])
area[:line_pattern] = pattern
end
# Set the border line weight.
if params.has_key?(:line_weight)
weight = get_line_weight(params[:line_weight])
area[:line_weight] = weight
end
end
#
# Set the properties of the chart chartarea.
#
def set_chartarea(params = {})
return if params.empty?
area = @chartarea
# Embedded automatic line weight has a different default value.
area[:line_weight] = 0xFFFF if @embedded
# Set the chart background colour.
if params.has_key?(:color)
index, rgb = get_color_indices(params[:color])
if !index.nil?
area[:fg_color_index] = index
area[:fg_color_rgb] = rgb
area[:bg_color_index] = 0x08
area[:bg_color_rgb] = 0x000000
area[:area_pattern] = 1
area[:area_options] = 0x0000 if @embedded
area[:visible] = 1
end
end
# Set the border line colour.
if params.has_key?(:line_color)
index, rgb = get_color_indices(params[:line_color])
if !index.nil?
area[:line_color_index] = index
area[:line_color_rgb] = rgb
area[:line_pattern] = 0x00
area[:line_options] = 0x0000
area[:visible] = 1
end
end
# Set the border line pattern.
if params.has_key?(:line_pattern)
pattern = get_line_pattern(params[:line_pattern])
area[:line_pattern] = pattern
area[:line_options] = 0x0000
area[:line_color_index] = 0x4F unless params.has_key?(:line_color)
area[:visible] = 1
end
# Set the border line weight.
if params.has_key?(:line_weight)
weight = get_line_weight(params[:line_weight])
area[:line_weight] = weight
area[:line_options] = 0x0000
area[:line_pattern] = 0x00 unless params.has_key?(:line_pattern)
area[:line_color_index] = 0x4F unless params.has_key?(:line_color)
area[:visible] = 1
end
end
def using_tmpfile=(val) # :nodoc:
@using_tmpfile = val
end
def data=(val) # :nodoc:
@data = val
end
def embedded # :nodoc:
@embedded
end
def embedded=(val) # :nodoc:
@embedded = val
end
#
# Setup the default configuration data for an embedded chart.
#
def set_embedded_config_data # :nodoc:
@embedded = true
@chartarea = {
:visible => 1,
:fg_color_index => 0x4E,
:fg_color_rgb => 0xFFFFFF,
:bg_color_index => 0x4D,
:bg_color_rgb => 0x000000,
:area_pattern => 0x0001,
:area_options => 0x0001,
:line_pattern => 0x0000,
:line_weight => 0x0000,
:line_color_index => 0x4D,
:line_color_rgb => 0x000000,
:line_options => 0x0009,
}
@config = default_config_data.merge({
:axisparent => [ 0, 0x01D8, 0x031D, 0x0D79, 0x07E9 ],
:axisparent_pos => [ 2, 2, 0x010C, 0x0292, 0x0E46, 0x09FD ],
:chart => [ 0x0000, 0x0000, 0x01847FE8, 0x00F47FE8 ],
:font_numbers => [ 5, 10, 0x1DC4, 0x1284, 0x0000 ],
:font_series => [ 6, 10, 0x1DC4, 0x1284, 0x0001 ],
:font_title => [ 7, 12, 0x1DC4, 0x1284, 0x0000 ],
:font_axes => [ 8, 10, 0x1DC4, 0x1284, 0x0001 ],
:legend => [ 0x044E, 0x0E4A, 0x088D, 0x0123, 0x0, 0x1, 0xF ],
:legend_pos => [ 5, 2, 0x044E, 0x0E4A, 0, 0 ],
:legend_text => [ 0xFFFFFFD9, 0xFFFFFFC1, 0, 0, 0x00B1, 0x0000 ],
:series_text => [ 0xFFFFFFD9, 0xFFFFFFC1, 0, 0, 0x00B1, 0x1020 ],
:title_text => [ 0x060F, 0x004C, 0x038A, 0x016F, 0x0081, 0x1030 ],
:x_axis_text => [ 0x07EF, 0x0C8F, 0x153, 0x123, 0x81, 0x00 ],
:y_axis_text => [ 0x0057, 0x0564, 0xB5, 0x035D, 0x0281, 0x00, 90 ],
})
end
#
# Create and store the Chart data structures.
#
def close # :nodoc:
# Ignore any data that has been written so far since it is probably
# from unwanted Worksheet method calls.
@data = ''
# TODO. Check for charts without a series?
# Store the chart BOF.
store_bof(0x0020)
# Store the page header
store_header
# Store the page footer
store_footer
# Store the page horizontal centering
store_hcenter
# Store the page vertical centering
store_vcenter
# Store the left margin
store_margin_left
# Store the right margin
store_margin_right
# Store the top margin
store_margin_top
# Store the bottom margin
store_margin_bottom
# Store the page setup
store_setup
# Store the sheet password
store_password
# Start of Chart specific records.
# Store the FBI font records.
store_fbi(*@config[:font_numbers])
store_fbi(*@config[:font_series])
store_fbi(*@config[:font_title])
store_fbi(*@config[:font_axes])
# Ignore UNITS record.
# Store the Chart sub-stream.
store_chart_stream
# Append the sheet dimensions
store_dimensions
# TODO add SINDEX and NUMBER records.
store_window2 unless @embedded
store_eof
end
private
#
# The parent Worksheet class needs to store some data in memory and some in
# temporary files for efficiency. The Chart* classes don't need to do this
# since they are dealing with smaller amounts of data so we override
# _prepend() to turn it into an _append() method. This allows for a more
# natural method calling order.
#
def prepend(*args) # :nodoc:
@using_tmpfile = false
append(*args)
end
#
# Write BIFF record Window2. Note, this overrides the parent Worksheet
# record because the Chart version of the record is smaller and is used
# mainly to indicate if the chart tab is selected or not.
#
def store_window2 # :nodoc:
record = 0x023E # Record identifier
length = 0x000A # Number of bytes to follow
grbit = 0x0000 # Option flags
rwTop = 0x0000 # Top visible row
colLeft = 0x0000 # Leftmost visible column
rgbHdr = 0x0000 # Row/col heading, grid color
# The options flags that comprise grbit
fDspFmla = 0 # 0 - bit
fDspGrid = 0 # 1
fDspRwCol = 0 # 2
fFrozen = 0 # 3
fDspZeros = 0 # 4
fDefaultHdr = 0 # 5
fArabic = 0 # 6
fDspGuts = 0 # 7
fFrozenNoSplit = 0 # 0 - bit
fSelected = selected? ? 1 : 0 # 1
fPaged = 0 # 2
fBreakPreview = 0 # 3
#<<< Perltidy ignore this.
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].pack("vvvV")
append(header, data)
end
#
# Parse the formula used to define a series. We also extract some range
# information required for _store_series() and the SERIES record.
#
def parse_series_formula(formula) # :nodoc:
encoding = 0
length = 0
count = 0
tokens = []
return [''] if formula.nil?
# Strip the = sign at the beginning of the formula string
formula = formula.sub(/^=/, '')
# 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)
# Force ranges to be a reference class.
tokens.collect! { |t| t.gsub(/_ref3d/, '_ref3dR') }
tokens.collect! { |t| t.gsub(/_range3d/, '_range3dR') }
tokens.collect! { |t| t.gsub(/_name/, '_nameR') }
# Parse the tokens into a formula string.
formula = parser.parse_tokens(tokens)
# Return formula for a single cell as used by title and series name.
return formula if formula.ord == 0x3A
# Extract the range from the parse formula.
if formula.ord == 0x3B
ptg, ext_ref, row_1, row_2, col_1, col_2 = formula.unpack('Cv5')
# TODO. Remove high bit on relative references.
count = row_2 - row_1 + 1
end
[formula, count]
end
#
# Convert UTF8 strings used in the chart to UTF16.
#
def encode_utf16(str, encoding = 0) # :nodoc:
# Exit if the $string isn't defined, i.e., hasn't been set by user.
return [nil, nil] if str.nil?
string = str.dup
# Return if encoding is set, i.e., string has been manually encoded.
#return ( undef, undef ) if $string == 1;
ruby_19 { string = convert_to_ascii_if_ascii(string) }
# Handle utf8 strings.
if is_utf8?(string)
string = utf8_to_16be(string)
encoding = 1
end
# Chart strings are limited to 255 characters.
limit = encoding != 0 ? 255 * 2 : 255
if string.bytesize >= limit
# truncate the string and raise a warning.
string = string[0, limit]
end
[string, encoding]
end
#
# Convert the user specified colour index or string to an colour index and
# RGB colour number.
#
def get_color_indices(color) # :nodoc:
invalid = 0x7FFF # return from Colors#get_color when color is invalid
index = Colors.new.get_color(color)
index = invalid if color.respond_to?(:coerce) && (color < 8 || color > 63)
if index == invalid
[nil, nil]
else
[index, get_color_rbg(index)]
end
end
#
# Get the RedGreenBlue number for the colour index from the Workbook palette.
#
def get_color_rbg(index) # :nodoc:
# Adjust colour index from 8-63 (user range) to 0-55 (Excel range).
index -= 8
red_green_blue = palette[index]
red_green_blue.pack('C*').unpack('V')[0]
end
def palette
@workbook.palette
end
#
# Get the Excel chart index for line pattern that corresponds to the user
# defined value.
#
def get_line_pattern(value) # :nodoc:
value = value.downcase if value.respond_to?(:to_str)
default = 0
patterns = {
0 => 5,
1 => 0,
2 => 1,
3 => 2,
4 => 3,
5 => 4,
6 => 7,
7 => 6,
8 => 8,
'solid' => 0,
'dash' => 1,
'dot' => 2,
'dash-dot' => 3,
'dash-dot-dot' => 4,
'none' => 5,
'dark-gray' => 6,
'medium-gray' => 7,
'light-gray' => 8,
}
if patterns.has_key?(value)
patterns[value]
else
default
end
end
#
# Get the Excel chart index for line weight that corresponds to the user
# defined value.
#
def get_line_weight(value) # :nodoc:
value = value.downcase if value.respond_to?(:to_str)
default = 0
weights = {
1 => -1,
2 => 0,
3 => 1,
4 => 2,
'hairline' => -1,
'narrow' => 0,
'medium' => 1,
'wide' => 2,
}
if weights.has_key?(value)
weights[value]
else
default
end
end
#
# Store the CHART record and it's substreams.
#
def store_chart_stream # :nodoc:
store_chart(*@config[:chart])
store_begin
# Store the chart SCL record.
store_plotgrowth
if @chartarea[:visible] != 0
store_chartarea_frame_stream
end
# Store SERIES stream for each series.
index = 0
@series.each do |series|
store_series_stream(
:index => index,
:value_formula => series[:values][0],
:value_count => series[:values][1],
:category_count => series[:categories][1],
:category_formula => series[:categories][0],
:name => series[:name],
:name_encoding => series[:name_encoding],
:name_formula => series[:name_formula]
)
index += 1
end
store_shtprops
# Write the TEXT streams.
(5..6).each do |font_index|
store_defaulttext
store_series_text_stream(font_index)
end
store_axesused(1)
store_axisparent_stream
if !@title_name.nil? || !@title_formula.nil?
store_title_text_stream
end
store_end
end
def _formula_type_from_param(t, f, params, key) # :nodoc:
if params.has_key?(key)
v = params[key]
(v.nil? || v == [""] || v == '' || v == 0) ? f : t
end
end
#
# Write the SERIES chart substream.
#
def store_series_stream(params) # :nodoc:
name_type = _formula_type_from_param(2, 1, params, :name_formula)
value_type = _formula_type_from_param(2, 0, params, :value_formula)
category_type = _formula_type_from_param(2, 0, params, :category_formula)
store_series(params[:value_count], params[:category_count])
store_begin
# Store the Series name AI record.
store_ai(0, name_type, params[:name_formula])
unless params[:name].nil?
store_seriestext(params[:name], params[:name_encoding])
end
store_ai(1, value_type, params[:value_formula])
store_ai(2, category_type, params[:category_formula])
store_ai(3, 1, '' )
store_dataformat_stream(params[:index])
store_sertocrt
store_end
end
#
# Write the DATAFORMAT chart substream.
#
def store_dataformat_stream(series_index) # :nodoc:
store_dataformat(series_index, series_index, 0xFFFF)
store_begin
store_3dbarshape
store_end
end
#
# Write the series TEXT substream.
#
def store_series_text_stream(font_index) # :nodoc:
store_text(*@config[:series_text])
store_begin
store_pos(*@config[:series_text_pos])
store_fontx( font_index )
store_ai( 0, 1, '' )
store_end
end
def _formula_type(t, f, formula) # :nodoc:
(formula.nil? || formula == [""] || formula == '' || formula == 0) ? f : t
end
#
# Write the X-axis TEXT substream.
#
def store_x_axis_text_stream # :nodoc:
formula = @x_axis_formula.nil? ? '' : @x_axis_formula
ai_type = _formula_type(2, 1, formula)
store_text(*@config[:x_axis_text])
store_begin
store_pos(*@config[:x_axis_text_pos])
store_fontx(8)
store_ai(0, ai_type, formula)
unless @x_axis_name.nil?
store_seriestext(@x_axis_name, @x_axis_encoding)
end
store_objectlink(3)
store_end
end
#
# Write the Y-axis TEXT substream.
#
def store_y_axis_text_stream # :nodoc:
formula = @y_axis_formula
ai_type = _formula_type(2, 1, formula)
store_text(*@config[:y_axis_text])
store_begin
store_pos(*@config[:y_axis_text_pos])
store_fontx(8)
store_ai(0, ai_type, formula)
unless @y_axis_name.nil?
store_seriestext(@y_axis_name, @y_axis_encoding)
end
store_objectlink(2)
store_end
end
#
# Write the legend TEXT substream.
#
def store_legend_text_stream # :nodoc:
store_text(*@config[:legend_text])
store_begin
store_pos(*@config[:legend_text_pos])
store_ai(0, 1, '')
store_end
end
#
# Write the title TEXT substream.
#
def store_title_text_stream # :nodoc:
formula = @title_formula
ai_type = _formula_type(2, 1, formula)
store_text(*@config[:title_text])
store_begin
store_pos(*@config[:title_text_pos])
store_fontx(7)
store_ai(0, ai_type, formula)
unless @title_name.nil?
store_seriestext(@title_name, @title_encoding)
end
store_objectlink(1)
store_end
end
#
# Write the AXISPARENT chart substream.
#
def store_axisparent_stream # :nodoc:
store_axisparent(*@config[:axisparent])
store_begin
store_pos(*@config[:axisparent_pos])
store_axis_category_stream
store_axis_values_stream
if !@x_axis_name.nil? || !@x_axis_formula.nil?
store_x_axis_text_stream
end
if !@y_axis_name.nil? || !@y_axis_formula.nil?
store_y_axis_text_stream
end
if @plotarea[:visible] != 0
store_plotarea
store_plotarea_frame_stream
end
store_chartformat_stream
store_end
end
#
# Write the AXIS chart substream for the chart category.
#
def store_axis_category_stream # :nodoc:
store_axis(0)
store_begin
store_catserrange
store_axcext
store_tick
store_end
end
#
# Write the AXIS chart substream for the chart values.
#
def store_axis_values_stream # :nodoc:
store_axis(1)
store_begin
store_valuerange
store_tick
store_axislineformat
store_lineformat(0x00000000, 0x0000, 0xFFFF, 0x0009, 0x004D)
store_end
end
#
# Write the FRAME chart substream.
#
def store_plotarea_frame_stream # :nodoc:
store_area_frame_stream_common(:plot)
end
#
# Write the FRAME chart substream for and embedded chart.
#
def store_chartarea_frame_stream # :nodoc:
store_area_frame_stream_common(:chart)
end
def store_area_frame_stream_common(type)
if type == :plot
area = @plotarea
grbit = 0x03
else
area = @chartarea
grbit = 0x02
end
store_frame(0x00, grbit)
store_begin
store_lineformat(
area[:line_color_rgb], area[:line_pattern],
area[:line_weight], area[:line_options],
area[:line_color_index]
)
store_areaformat(
area[:fg_color_rgb], area[:bg_color_rgb],
area[:area_pattern], area[:area_options],
area[:fg_color_index], area[:bg_color_index]
)
store_end
end
#
# Write the CHARTFORMAT chart substream.
#
def store_chartformat_stream # :nodoc:
# The _vary_data_color is set by classes that need it, like Pie.
store_chartformat(@vary_data_color)
store_begin
# Store the BIFF record that will define the chart type.
store_chart_type
# Note, the CHARTFORMATLINK record is only written by Excel.
if @legend[:visible] != 0
store_legend_stream
end
store_marker_dataformat_stream
store_end
end
#
# This is an abstract method that is overridden by the sub-classes to define
# the chart types such as Column, Line, Pie, etc.
#
def store_chart_type # :nodoc:
end
#
# This is an abstract method that is overridden by the sub-classes to define
# properties of markers, linetypes, pie formats and other.
#
def store_marker_dataformat_stream # :nodoc:
end
#
# Write the LEGEND chart substream.
#
def store_legend_stream # :nodoc:
store_legend(*@config[:legend])
store_begin
store_pos(*@config[:legend_pos])
store_legend_text_stream
store_end
end
###############################################################################
#
# BIFF Records.
#
###############################################################################
#
# Write the 3DBARSHAPE chart BIFF record.
#
def store_3dbarshape # :nodoc:
record = 0x105F # Record identifier.
length = 0x0002 # Number of bytes to follow.
riser = 0x00 # Shape of base.
taper = 0x00 # Column taper type.
header = [record, length].pack('vv')
data = [riser].pack('C')
data += [taper].pack('C')
append(header, data)
end
#
# Write the AI chart BIFF record.
#
def store_ai(id, type, formula, format_index = 0) # :nodoc:
formula = '' if formula == [""]
record = 0x1051 # Record identifier.
length = 0x0008 # Number of bytes to follow.
# id # Link index.
# type # Reference type.
# formula # Pre-parsed formula.
# format_index # Num format index.
grbit = 0x0000 # Option flags.
ruby_19 { formula = convert_to_ascii_if_ascii(formula) }
formula_length = formula.bytesize
length += formula_length
header = [record, length].pack('vv')
data = [id].pack('C')
data += [type].pack('C')
data += [grbit].pack('v')
data += [format_index].pack('v')
data += [formula_length].pack('v')
if formula.respond_to?(:to_array)
data +=
ruby_18 { formula[0] } ||
ruby_19 { formula[0].encode('BINARY') }
else
data +=
ruby_18 { formula unless formula.nil? } ||
ruby_19 { formula.encode('BINARY') unless formula.nil? }
end
append(header, data)
end
#
# Write the AREAFORMAT chart BIFF record. Contains the patterns and colours
# of a chart area.
#
def store_areaformat(rgbFore, rgbBack, pattern, grbit, indexFore, indexBack) # :nodoc:
record = 0x100A # Record identifier.
length = 0x0010 # Number of bytes to follow.
# rgbFore # Foreground RGB colour.
# rgbBack # Background RGB colour.
# pattern # Pattern.
# grbit # Option flags.
# indexFore # Index to Foreground colour.
# indexBack # Index to Background colour.
header = [record, length].pack('vv')
data = [rgbFore].pack('V')
data += [rgbBack].pack('V')
data += [pattern].pack('v')
data += [grbit].pack('v')
data += [indexFore].pack('v')
data += [indexBack].pack('v')
append(header, data)
end
#
# Write the AXCEXT chart BIFF record.
#
def store_axcext # :nodoc:
record = 0x1062 # Record identifier.
length = 0x0012 # Number of bytes to follow.
catMin = 0x0000 # Minimum category on axis.
catMax = 0x0000 # Maximum category on axis.
catMajor = 0x0001 # Value of major unit.
unitMajor = 0x0000 # Units of major unit.
catMinor = 0x0001 # Value of minor unit.
unitMinor = 0x0000 # Units of minor unit.
unitBase = 0x0000 # Base unit of axis.
catCrossDate = 0x0000 # Crossing point.
grbit = 0x00EF # Option flags.
store_simple(record, length, catMin, catMax, catMajor, unitMajor,
catMinor, unitMinor, unitBase, catCrossDate, grbit)
end
#
# Write the AXESUSED chart BIFF record.
#
def store_axesused(num_axes) # :nodoc:
record = 0x1046 # Record identifier.
length = 0x0002 # Number of bytes to follow.
# num_axes # Number of axes used.
store_simple(record, length, num_axes)
end
#
# Write the AXIS chart BIFF record to define the axis type.
#
def store_axis(type) # :nodoc:
record = 0x101D # Record identifier.
length = 0x0012 # Number of bytes to follow.
# type # Axis type.
reserved1 = 0x00000000 # Reserved.
reserved2 = 0x00000000 # Reserved.
reserved3 = 0x00000000 # Reserved.
reserved4 = 0x00000000 # Reserved.
header = [record, length].pack('vv')
data = [type].pack('v')
data += [reserved1].pack('V')
data += [reserved2].pack('V')
data += [reserved3].pack('V')
data += [reserved4].pack('V')
append(header, data)
end
#
# Write the AXISLINEFORMAT chart BIFF record.
#
def store_axislineformat # :nodoc:
record = 0x1021 # Record identifier.
length = 0x0002 # Number of bytes to follow.
line_format = 0x0001 # Axis line format.
store_simple(record, length, line_format)
end
#
# Write the AXISPARENT chart BIFF record.
#
def store_axisparent(iax, x, y, dx, dy) # :nodoc:
record = 0x1041 # Record identifier.
length = 0x0012 # Number of bytes to follow.
# iax # Axis index.
# x # X-coord.
# y # Y-coord.
# dx # Length of x axis.
# dy # Length of y axis.
header = [record, length].pack('vv')
data = [iax].pack('v')
data += [x].pack('V')
data += [y].pack('V')
data += [dx].pack('V')
data += [dy].pack('V')
append(header, data)
end
#
# Write the BEGIN chart BIFF record to indicate the start of a sub stream.
#
def store_begin # :nodoc:
record = 0x1033 # Record identifier.
length = 0x0000 # Number of bytes to follow.
store_simple(record, length)
end
#
# Write the CATSERRANGE chart BIFF record.
#
def store_catserrange # :nodoc:
record = 0x1020 # Record identifier.
length = 0x0008 # Number of bytes to follow.
catCross = 0x0001 # Value/category crossing.
catLabel = 0x0001 # Frequency of labels.
catMark = 0x0001 # Frequency of ticks.
grbit = 0x0001 # Option flags.
store_simple(record, length, catCross, catLabel, catMark, grbit)
end
#
# Write the CHART BIFF record. This indicates the start of the chart sub-stream
# and contains dimensions of the chart on the display. Units are in 1/72 inch
# and are 2 byte integer with 2 byte fraction.
#
def store_chart(x_pos, y_pos, dx, dy) # :nodoc:
record = 0x1002 # Record identifier.
length = 0x0010 # Number of bytes to follow.
# x_pos # X pos of top left corner.
# y_pos # Y pos of top left corner.
# dx # X size.
# dy # Y size.
header = [record, length].pack('vv')
data = [x_pos].pack('V')
data += [y_pos].pack('V')
data += [dx].pack('V')
data += [dy].pack('V')
append(header, data)
end
#
# Write the CHARTFORMAT chart BIFF record. The parent record for formatting
# of a chart group.
#
def store_chartformat(grbit = 0) # :nodoc:
record = 0x1014 # Record identifier.
length = 0x0014 # Number of bytes to follow.
reserved1 = 0x00000000 # Reserved.
reserved2 = 0x00000000 # Reserved.
reserved3 = 0x00000000 # Reserved.
reserved4 = 0x00000000 # Reserved.
# grbit # Option flags.
icrt = 0x0000 # Drawing order.
header = [record, length].pack('vv')
data = [reserved1].pack('V')
data += [reserved2].pack('V')
data += [reserved3].pack('V')
data += [reserved4].pack('V')
data += [grbit].pack('v')
data += [icrt].pack('v')
append(header, data)
end
#
# Write the CHARTLINE chart BIFF record.
#
def store_chartline # :nodoc:
record = 0x101C # Record identifier.
length = 0x0002 # Number of bytes to follow.
type = 0x0001 # Drop/hi-lo line type.
store_simple(record, length, type)
end
#
# Write the TEXT chart BIFF record.
#
def store_charttext # :nodoc:
record = 0x1025 # Record identifier.
length = 0x0020 # Number of bytes to follow.
horz_align = 0x02 # Horizontal alignment.
vert_align = 0x02 # Vertical alignment.
bg_mode = 0x0001 # Background display.
text_color_rgb = 0x00000000 # Text RGB colour.
text_x = 0xFFFFFF46 # Text x-pos.
text_y = 0xFFFFFF06 # Text y-pos.
text_dx = 0x00000000 # Width.
text_dy = 0x00000000 # Height.
grbit1 = 0x00B1 # Options
text_color_index = 0x004D # Auto Colour.
grbit2 = 0x0000 # Data label placement.
rotation = 0x0000 # Text rotation.
header = [record, length].pack('vv')
data = [horz_align].pack('C')
data += [vert_align].pack('C')
data += [bg_mode].pack('v')
data += [text_color_rgb].pack('V')
data += [text_x].pack('V')
data += [text_y].pack('V')
data += [text_dx].pack('V')
data += [text_dy].pack('V')
data += [grbit1].pack('v')
data += [text_color_index].pack('v')
data += [grbit2].pack('v')
data += [rotation].pack('v')
append(header, data)
end
#
# Write the DATAFORMAT chart BIFF record. This record specifies the series
# that the subsequent sub stream refers to.
#
def store_dataformat(series_index, series_number, point_number) # :nodoc:
record = 0x1006 # Record identifier.
length = 0x0008 # Number of bytes to follow.
# series_index # Series index.
# series_number # Series number. (Same as index).
# point_number # Point number.
grbit = 0x0000 # Format flags.
store_simple(record, length, point_number, series_index, series_number, grbit)
end
#
# Write the DEFAULTTEXT chart BIFF record. Identifier for subsequent TEXT
# record.
#
def store_defaulttext # :nodoc:
record = 0x1024 # Record identifier.
length = 0x0002 # Number of bytes to follow.
type = 0x0002 # Type.
store_simple(record, length, type)
end
#
# Write the DROPBAR chart BIFF record.
#
def store_dropbar # :nodoc:
record = 0x103D # Record identifier.
length = 0x0002 # Number of bytes to follow.
percent_gap = 0x0096 # Drop bar width gap (%).
store_simple(record, length, percent_gap)
end
#
# Write the END chart BIFF record to indicate the end of a sub stream.
#
def store_end # :nodoc:
record = 0x1034 # Record identifier.
length = 0x0000 # Number of bytes to follow.
store_simple(record, length)
end
#
# Write the FBI chart BIFF record. Specifies the font information at the time
# it was applied to the chart.
#
def store_fbi(index, height, width_basis, height_basis, scale_basis) # :nodoc:
record = 0x1060 # Record identifier.
length = 0x000A # Number of bytes to follow.
# index # Font index.
height = height * 20 # Default font height in twips.
# width_basis # Width basis, in twips.
# height_basis # Height basis, in twips.
# scale_basis # Scale by chart area or plot area.
store_simple(record, length, width_basis, height_basis, height, scale_basis, index)
end
#
# Write the FONTX chart BIFF record which contains the index of the FONT
# record in the Workbook.
#
def store_fontx(index) # :nodoc:
record = 0x1026 # Record identifier.
length = 0x0002 # Number of bytes to follow.
# index # Font index.
store_simple(record, length, index)
end
#
# Write the FRAME chart BIFF record.
#
def store_frame(frame_type, grbit) # :nodoc:
record = 0x1032 # Record identifier.
length = 0x0004 # Number of bytes to follow.
# frame_type # Frame type.
# grbit # Option flags.
store_simple(record, length, frame_type, grbit)
end
#
# Write the LEGEND chart BIFF record. The Marcus Horan method.
#
def store_legend(x, y, width, height, wType, wSpacing, grbit) # :nodoc:
record = 0x1015 # Record identifier.
length = 0x0014 # Number of bytes to follow.
# x # X-position.
# y # Y-position.
# width # Width.
# height # Height.
# wType # Type.
# wSpacing # Spacing.
# grbit # Option flags.
header = [record, length].pack('vv')
data = [x].pack('V')
data += [y].pack('V')
data += [width].pack('V')
data += [height].pack('V')
data += [wType].pack('C')
data += [wSpacing].pack('C')
data += [grbit].pack('v')
append(header, data)
end
#
# Write the LINEFORMAT chart BIFF record.
#
def store_lineformat(rgb, lns, we, grbit, index) # :nodoc:
record = 0x1007 # Record identifier.
length = 0x000C # Number of bytes to follow.
# rgb # Line RGB colour.
# lns # Line pattern.
# we # Line weight.
# grbit # Option flags.
# index # Index to colour of line.
header = [record, length].pack('vv')
data = [rgb].pack('V')
data += [lns].pack('v')
data += [we].pack('v')
data += [grbit].pack('v')
data += [index].pack('v')
append(header, data)
end
#
# Write the MARKERFORMAT chart BIFF record.
#
def store_markerformat(rgbFore, rgbBack, marker, grbit, icvFore, icvBack, miSize)# :nodoc:
record = 0x1009 # Record identifier.
length = 0x0014 # Number of bytes to follow.
# rgbFore # Foreground RGB color.
# rgbBack # Background RGB color.
# marker # Type of marker.
# grbit # Format flags.
# icvFore # Color index marker border.
# icvBack # Color index marker fill.
# miSize # Size of line markers.
header = [record, length].pack('vv')
data = [rgbFore].pack('V')
data += [rgbBack].pack('V')
data += [marker].pack('v')
data += [grbit].pack('v')
data += [icvFore].pack('v')
data += [icvBack].pack('v')
data += [miSize].pack('V')
append(header, data)
end
#
# Write the OBJECTLINK chart BIFF record.
#
def store_objectlink(link_type) # :nodoc:
record = 0x1027 # Record identifier.
length = 0x0006 # Number of bytes to follow.
# link_type # Object text link type.
link_index1 = 0x0000 # Link index 1.
link_index2 = 0x0000 # Link index 2.
store_simple(record, length, link_type, link_index1, link_index2)
end
#
# Write the PIEFORMAT chart BIFF record.
#
def store_pieformat # :nodoc:
record = 0x100B # Record identifier.
length = 0x0002 # Number of bytes to follow.
percent = 0x0000 # Distance % from center.
store_simple(record, length, percent)
end
#
# Write the PLOTAREA chart BIFF record. This indicates that the subsequent
# FRAME record belongs to a plot area.
#
def store_plotarea # :nodoc:
record = 0x1035 # Record identifier.
length = 0x0000 # Number of bytes to follow.
store_simple(record, length)
end
#
# Write the PLOTGROWTH chart BIFF record.
#
def store_plotgrowth # :nodoc:
record = 0x1064 # Record identifier.
length = 0x0008 # Number of bytes to follow.
dx_plot = 0x00010000 # Horz growth for font scale.
dy_plot = 0x00010000 # Vert growth for font scale.
header = [record, length].pack('vv')
data = [dx_plot].pack('V')
data += [dy_plot].pack('V')
append(header, data)
end
#
# Write the POS chart BIFF record. Generally not required when using
# automatic positioning.
#
def store_pos(mdTopLt, mdBotRt, x1, y1, x2, y2) # :nodoc:
record = 0x104F # Record identifier.
length = 0x0014 # Number of bytes to follow.
# mdTopLt # Top left.
# mdBotRt # Bottom right.
# x1 # X coordinate.
# y1 # Y coordinate.
# x2 # Width.
# y2 # Height.
header = [record, length].pack('vv')
data = [mdTopLt].pack('v')
data += [mdBotRt].pack('v')
data += [x1].pack('V')
data += [y1].pack('V')
data += [x2].pack('V')
data += [y2].pack('V')
append(header, data)
end
#
# Write the SERAUXTREND chart BIFF record.
#
def store_serauxtrend(reg_type, poly_order, equation, r_squared) # :nodoc:
record = 0x104B # Record identifier.
length = 0x001C # Number of bytes to follow.
# reg_type # Regression type.
# poly_order # Polynomial order.
# equation # Display equation.
# r_squared # Display R-squared.
# intercept # Forced intercept.
# forecast # Forecast forward.
# backcast # Forecast backward.
# TODO. When supported, intercept needs to be NAN if not used.
# Also need to reverse doubles.
intercept = ['FFFFFFFF0001FFFF'].pack('H*')
forecast = ['0000000000000000'].pack('H*')
backcast = ['0000000000000000'].pack('H*')
header = [record, length].pack('vv')
data = [reg_type].pack('C')
data += [poly_order].pack('C')
data += intercept
data += [equation].pack('C')
data += [r_squared].pack('C')
data += forecast
data += backcast
append(header, data)
end
#
# Write the SERIES chart BIFF record.
#
def store_series(category_count, value_count) # :nodoc:
record = 0x1003 # Record identifier.
length = 0x000C # Number of bytes to follow.
category_type = 0x0001 # Type: category.
value_type = 0x0001 # Type: value.
# category_count # Num of categories.
# value_count # Num of values.
bubble_type = 0x0001 # Type: bubble.
bubble_count = 0x0000 # Num of bubble values.
store_simple(record, length, category_type, value_type,
category_count, value_count, bubble_type, bubble_count)
end
#
# Write the SERIESTEXT chart BIFF record.
#
def store_seriestext(str, encoding) # :nodoc:
ruby_19 { str = convert_to_ascii_if_ascii(str) }
record = 0x100D # Record identifier.
length = 0x0000 # Number of bytes to follow.
id = 0x0000 # Text id.
# str # Text.
# encoding # String encoding.
cch = str.bytesize # String length.
encoding ||= 0
# 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 = 4 + str.bytesize
header = [record, length].pack('vv')
data = [id].pack('v')
data += [cch].pack('C')
data += [encoding].pack('C')
append(header, data, str)
end
#
# Write the SERPARENT chart BIFF record.
#
def store_serparent(series) # :nodoc:
record = 0x104A # Record identifier.
length = 0x0002 # Number of bytes to follow.
# series # Series parent.
store_simple(record, length, series)
end
#
# Write the SERTOCRT chart BIFF record to indicate the chart group index.
#
def store_sertocrt # :nodoc:
record = 0x1045 # Record identifier.
length = 0x0002 # Number of bytes to follow.
chartgroup = 0x0000 # Chart group index.
store_simple(record, length, chartgroup)
end
#
# Write the SHTPROPS chart BIFF record.
#
def store_shtprops # :nodoc:
record = 0x1044 # Record identifier.
length = 0x0004 # Number of bytes to follow.
grbit = 0x000E # Option flags.
empty_cells = 0x0000 # Empty cell handling.
grbit = 0x000A if @embedded
store_simple(record, length, grbit, empty_cells)
end
#
# Write the TEXT chart BIFF record.
#
def store_text(x, y, dx, dy, grbit1, grbit2, rotation = 0x00)# :nodoc:
record = 0x1025 # Record identifier.
length = 0x0020 # Number of bytes to follow.
at = 0x02 # Horizontal alignment.
vat = 0x02 # Vertical alignment.
wBkgMode = 0x0001 # Background display.
rgbText = 0x0000 # Text RGB colour.
# x # Text x-pos.
# y # Text y-pos.
# dx # Width.
# dy # Height.
# grbit1 # Option flags.
icvText = 0x004D # Auto Colour.
# grbit2 # Show legend.
# rotation # Show value.
header = [record, length].pack('vv')
data = [at].pack('C')
data += [vat].pack('C')
data += [wBkgMode].pack('v')
data += [rgbText].pack('V')
data += [x].pack('V')
data += [y].pack('V')
data += [dx].pack('V')
data += [dy].pack('V')
data += [grbit1].pack('v')
data += [icvText].pack('v')
data += [grbit2].pack('v')
data += [rotation].pack('v')
append(header, data)
end
#
# Write the TICK chart BIFF record.
#
def store_tick # :nodoc:
record = 0x101E # Record identifier.
length = 0x001E # Number of bytes to follow.
tktMajor = 0x02 # Type of major tick mark.
tktMinor = 0x00 # Type of minor tick mark.
tlt = 0x03 # Tick label position.
wBkgMode = 0x01 # Background mode.
rgb = 0x00000000 # Tick-label RGB colour.
reserved1 = 0x00000000 # Reserved.
reserved2 = 0x00000000 # Reserved.
reserved3 = 0x00000000 # Reserved.
reserved4 = 0x00000000 # Reserved.
grbit = 0x0023 # Option flags.
index = 0x004D # Colour index.
reserved5 = 0x0000 # Reserved.
header = [record, length].pack('vv')
data = [tktMajor].pack('C')
data += [tktMinor].pack('C')
data += [tlt].pack('C')
data += [wBkgMode].pack('C')
data += [rgb].pack('V')
data += [reserved1].pack('V')
data += [reserved2].pack('V')
data += [reserved3].pack('V')
data += [reserved4].pack('V')
data += [grbit].pack('v')
data += [index].pack('v')
data += [reserved5].pack('v')
append(header, data)
end
#
# Write the VALUERANGE chart BIFF record.
#
def store_valuerange # :nodoc:
record = 0x101F # Record identifier.
length = 0x002A # Number of bytes to follow.
numMin = 0x00000000 # Minimum value on axis.
numMax = 0x00000000 # Maximum value on axis.
numMajor = 0x00000000 # Value of major increment.
numMinor = 0x00000000 # Value of minor increment.
numCross = 0x00000000 # Value where category axis crosses.
grbit = 0x011F # Format flags.
# TODO. Reverse doubles when they are handled.
header = [record, length].pack('vv')
data = [numMin].pack('d')
data += [numMax].pack('d')
data += [numMajor].pack('d')
data += [numMinor].pack('d')
data += [numCross].pack('d')
data += [grbit].pack('v')
append(header, data)
end
###############################################################################
#
# Config data.
#
###############################################################################
#
# Setup the default properties for a chart.
#
def set_default_properties # :nodoc:
@legend = {
:visible => 1,
:position => 0,
:vertical => 0,
}
@chartarea = {
:visible => 0,
:fg_color_index => 0x4E,
:fg_color_rgb => 0xFFFFFF,
:bg_color_index => 0x4D,
:bg_color_rgb => 0x000000,
:area_pattern => 0x0000,
:area_options => 0x0000,
:line_pattern => 0x0005,
:line_weight => 0xFFFF,
:line_color_index => 0x4D,
:line_color_rgb => 0x000000,
:line_options => 0x0008,
}
@plotarea = {
:visible => 1,
:fg_color_index => 0x16,
:fg_color_rgb => 0xC0C0C0,
:bg_color_index => 0x4F,
:bg_color_rgb => 0x000000,
:area_pattern => 0x0001,
:area_options => 0x0000,
:line_pattern => 0x0000,
:line_weight => 0x0000,
:line_color_index => 0x17,
:line_color_rgb => 0x808080,
:line_options => 0x0000,
}
end
#
# Setup the default configuration data for a chart.
#
def set_default_config_data # :nodoc:
@config = default_config_data
end
def default_config_data # :nodoc:
{
:axisparent => [ 0, 0x00F8, 0x01F5, 0x0E7F, 0x0B36 ],
:axisparent_pos => [ 2, 2, 0x008C, 0x01AA, 0x0EEA, 0x0C52 ],
:chart => [ 0x0000, 0x0000, 0x02DD51E0, 0x01C2B838 ],
:font_numbers => [ 5, 10, 0x38B8, 0x22A1, 0x0000 ],
:font_series => [ 6, 10, 0x38B8, 0x22A1, 0x0001 ],
:font_title => [ 7, 12, 0x38B8, 0x22A1, 0x0000 ],
:font_axes => [ 8, 10, 0x38B8, 0x22A1, 0x0001 ],
:legend => [ 0x05F9, 0x0EE9, 0x047D, 0x9C, 0x00, 0x01, 0x0F ],
:legend_pos => [ 5, 2, 0x05F9, 0x0EE9, 0, 0 ],
:legend_text => [ 0xFFFFFF46, 0xFFFFFF06, 0, 0, 0x00B1, 0x0000 ],
:legend_text_pos => [ 2, 2, 0, 0, 0, 0 ],
:series_text => [ 0xFFFFFF46, 0xFFFFFF06, 0, 0, 0x00B1, 0x1020 ],
:series_text_pos => [ 2, 2, 0, 0, 0, 0 ],
:title_text => [ 0x06E4, 0x0051, 0x01DB, 0x00C4, 0x0081, 0x1030 ],
:title_text_pos => [ 2, 2, 0, 0, 0x73, 0x1D ],
:x_axis_text => [ 0x07E1, 0x0DFC, 0xB2, 0x9C, 0x0081, 0x0000 ],
:x_axis_text_pos => [ 2, 2, 0, 0, 0x2B, 0x17 ],
:y_axis_text => [ 0x002D, 0x06AA, 0x5F, 0x1CC, 0x0281, 0x00, 90 ],
:y_axis_text_pos => [ 2, 2, 0, 0, 0x17, 0x44 ],
}
end
end # class Chart
end # module Writeexcel
|
Radanisk/writeexcel
|
examples/comments1.rb
|
<gh_stars>10-100
#!/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.
#
# For more advanced comment options see comments2.pl.
#
# reverse('©'), November 2005, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
workbook = WriteExcel.new("comments1.xls")
worksheet = workbook.add_worksheet
worksheet.write('A1', 'Hello')
worksheet.write_comment('A1', 'This is a comment')
workbook.close
|
Radanisk/writeexcel
|
test/test_properties.rb
|
# -*- coding: utf-8 -*-
require 'helper'
require 'stringio'
class TestProperties < Test::Unit::TestCase
def setup
@workbook = WriteExcel.new(StringIO.new)
end
def test_pack_VT_FILETIME
filetime =
assert_equal(
'40 00 00 00 00 FD 2D ED CE 48 CE 01',
unpack_record(pack_VT_FILETIME(Time.gm(2013, 5, 4, 13, 54, 42)))
)
end
def test_create_summary_property_set
assert_equal(
'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 08 01 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 70 00 00 00 04 00 00 00 94 00 00 00 05 00 00 00 AC 00 00 00 06 00 00 00 D0 00 00 00 0C 00 00 00 FC 00 00 00 02 00 00 00 E4 04 00 00 1E 00 00 00 1F 00 00 00 54 68 69 73 20 69 73 20 61 6E 20 65 78 61 6D 70 6C 65 20 73 70 72 65 61 64 73 68 65 65 74 00 00 1E 00 00 00 19 00 00 00 57 69 74 68 20 64 6F 63 75 6D 65 6E 74 20 70 72 6F 70 65 72 74 69 65 73 00 00 00 00 1E 00 00 00 0F 00 00 00 48 69 64 65 6F 20 4E 41 4B 41 4D 55 52 41 00 00 1E 00 00 00 1C 00 00 00 53 61 6D 70 6C 65 2C 20 45 78 61 6D 70 6C 65 2C 20 50 72 6F 70 65 72 74 69 65 73 00 1E 00 00 00 21 00 00 00 43 72 65 61 74 65 64 20 77 69 74 68 20 52 75 62 79 20 61 6E 64 20 57 72 69 74 65 45 78 63 65 6C 00 00 00 00 40 00 00 00 00 62 93 81 C5 48 CE 01',
unpack_record(create_summary_property_set(
[
[1, "VT_I2", 1252],
[2, "VT_LPSTR", "This is an example spreadsheet"],
[3, "VT_LPSTR", "With document properties"],
[4, "VT_LPSTR", "Hideo NAKAMURA"],
[5, "VT_LPSTR", "Sample, Example, Properties"],
[6, "VT_LPSTR", "Created with Ruby and WriteExcel"],
[12, "VT_FILETIME", Time.gm(2013, 5, 4, 12, 47, 16)]
]
))
)
end
end
|
Radanisk/writeexcel
|
lib/writeexcel/charts/area.rb
|
# -*- coding: utf-8 -*-
###############################################################################
#
# Area - A writer class for Excel Area charts.
#
# Used in conjunction with Chart.
#
# See formatting note in 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 Area chart using WriteExcel:
#
# #!/usr/bin/ruby -w
#
# require 'writeexcel'
#
# workbook = WriteExcel.new('chart.xls')
# worksheet = workbook.add_worksheet
#
# chart = workbook.add_chart(:type => 'Chart::Area')
#
# # 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 Area charts for WriteExcel. The chart object is
# created via the Workbook add_chart method:
#
# chart = workbook.add_chart(:type => 'Chart::Area')
#
# 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.
#
# ==Area Chart Methods
#
# There aren't currently any area chart specific methods. See the TODO
# section of Chart of 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_area.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::Area', :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 Area < 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 = 0x101A # Record identifier.
length = 0x0002 # Number of bytes to follow.
grbit = 0x0001 # Option flags.
store_simple(record, length, grbit)
end
end
end # class Chart
end # module Writeexcel
|
Radanisk/writeexcel
|
examples/data_validate.rb
|
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
###############################################################################
#
# Example of how to add data validation and dropdown lists 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('data_validate.xls')
worksheet = workbook.add_worksheet
# Add a format for the header cells.
header_format = workbook.add_format(
:border => 1,
:bg_color => 43,
:bold => 1,
:text_wrap => 1,
:valign => 'vcenter',
:indent => 1
)
# Set up layout of the worksheet.
worksheet.set_column('A:A', 64)
worksheet.set_column('B:B', 15)
worksheet.set_column('D:D', 15)
worksheet.set_row(0, 36)
worksheet.set_selection('B3')
# Write the header cells and some data that will be used in the examples.
row = 0
heading1 = 'Some examples of data validation in WriteExcel'
heading2 = 'Enter values in this column'
heading3 = 'Sample Data'
worksheet.write('A1', heading1, header_format)
worksheet.write('B1', heading2, header_format)
worksheet.write('D1', heading3, header_format)
worksheet.write('D3', ['Integers', 1, 10])
worksheet.write('D4', ['List data', 'open', 'high', 'close'])
worksheet.write('D5', ['Formula', '=AND(F5=50,G5=60)', 50, 60])
#
# Example 1. Limiting input to an integer in a fixed range.
#
txt = 'Enter an integer between 1 and 10'
row += 2
worksheet.write(row, 0, txt)
worksheet.data_validation(row, 1,
{
:validate => 'integer',
:criteria => 'between',
:minimum => 1,
:maximum => 10
})
#
# Example 2. Limiting input to an integer outside a fixed range.
#
txt = 'Enter an integer that is not between 1 and 10 (using cell references)'
row += 2
worksheet.write(row, 0, txt)
worksheet.data_validation(row, 1,
{
:validate => 'integer',
:criteria => 'not between',
:minimum => '=E3',
:maximum => '=F3'
})
#
# Example 3. Limiting input to an integer greater than a fixed value.
#
txt = 'Enter an integer greater than 0'
row += 2
worksheet.write(row, 0, txt)
worksheet.data_validation(row, 1,
{
:validate => 'integer',
:criteria => '>',
:value => 0
})
#
# Example 4. Limiting input to an integer less than a fixed value.
#
txt = 'Enter an integer less than 10'
row += 2
worksheet.write(row, 0, txt)
worksheet.data_validation(row, 1,
{
:validate => 'integer',
:criteria => '<',
:value => 10
})
#
# Example 5. Limiting input to a decimal in a fixed range.
#
txt = 'Enter a decimal between 0.1 and 0.5'
row += 2
worksheet.write(row, 0, txt)
worksheet.data_validation(row, 1,
{
:validate => 'decimal',
:criteria => 'between',
:minimum => 0.1,
:maximum => 0.5
})
#
# Example 6. Limiting input to a value in a dropdown list.
#
txt = 'Select a value from a drop down list'
row += 2
worksheet.write(row, 0, txt)
worksheet.data_validation(row, 1,
{
:validate => 'list',
:source => ['open', 'high', 'close']
})
#
# Example 6. Limiting input to a value in a dropdown list.
#
txt = 'Select a value from a drop down list (using a cell range)'
row += 2
worksheet.write(row, 0, txt)
worksheet.data_validation(row, 1,
{
:validate => 'list',
:source => '=$E$4:$G$4'
})
#
# Example 7. Limiting input to a date in a fixed range.
#
txt = 'Enter a date between 1/1/2008 and 12/12/2008'
row += 2
worksheet.write(row, 0, txt)
worksheet.data_validation(row, 1,
{
:validate => 'date',
:criteria => 'between',
:minimum => '2008-01-01T',
:maximum => '2008-12-12T'
})
#
# Example 8. Limiting input to a time in a fixed range.
#
txt = 'Enter a time between 6:00 and 12:00'
row += 2
worksheet.write(row, 0, txt)
worksheet.data_validation(row, 1,
{
:validate => 'time',
:criteria => 'between',
:minimum => 'T06:00',
:maximum => 'T12:00'
})
#
# Example 9. Limiting input to a string greater than a fixed length.
#
txt = 'Enter a string longer than 3 characters'
row += 2
worksheet.write(row, 0, txt)
worksheet.data_validation(row, 1,
{
:validate => 'length',
:criteria => '>',
:value => 3
})
#
# Example 10. Limiting input based on a formula.
#
txt = 'Enter a value if the following is true "=AND(F5=50,G5=60)"'
row += 2
worksheet.write(row, 0, txt)
worksheet.data_validation(row, 1,
{
:validate => 'custom',
:value => '=AND(F5=50,G5=60)'
})
#
# Example 11. Displaying and modify data validation messages.
#
txt = 'Displays a message when you select the cell'
row += 2
worksheet.write(row, 0, txt)
worksheet.data_validation(row, 1,
{
:validate => 'integer',
:criteria => 'between',
:minimum => 1,
:maximum => 100,
:input_title => 'Enter an integer:',
:input_message => 'between 1 and 100'
})
#
# Example 12. Displaying and modify data validation messages.
#
txt = 'Display a custom error message when integer isn\'t between 1 and 100'
row += 2
worksheet.write(row, 0, txt)
worksheet.data_validation(row, 1,
{
:validate => 'integer',
:criteria => 'between',
:minimum => 1,
:maximum => 100,
:input_title => 'Enter an integer:',
:input_message => 'between 1 and 100',
:error_title => 'Input value is not valid!',
:error_message => 'It should be an integer between 1 and 100'
})
#
# Example 13. Displaying and modify data validation messages.
#
txt = 'Display a custom information message when integer isn\'t between 1 and 100'
row += 2
worksheet.write(row, 0, txt)
worksheet.data_validation(row, 1,
{
:validate => 'integer',
:criteria => 'between',
:minimum => 1,
:maximum => 100,
:input_title => 'Enter an integer:',
:input_message => 'between 1 and 100',
:error_title => 'Input value is not valid!',
:error_message => 'It should be an integer between 1 and 100',
:error_type => 'information'
})
workbook.close
|
Radanisk/writeexcel
|
test/test_42_set_properties.rb
|
# -*- coding: utf-8 -*-
##########################################################################
# test_42_set_properties.rb
#
# Tests for Workbook property_sets() interface.
#
# some 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_set_properties < Test::Unit::TestCase
def test_dummy
assert(true)
end
def setup
@test_file = StringIO.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_same_as_previous_plus_creation_date
smiley = '☺' # chr 0x263A; in perl
workbook = WriteExcel.new(@test_file)
worksheet = workbook.add_worksheet
=begin
###############################################################################
#
# Test 1. _get_property_set_codepage() for default latin1 strings.
#
params ={
:title => 'Title',
:subject => 'Subject',
:author => 'Author',
:keywords => 'Keywords',
:comments => 'Comments',
:last_author => 'Username',
}
strings = %w(title subject author keywords comments last_author)
caption = " \t_get_property_set_codepage('latin1')"
target = 0x04E4
result = workbook.get_property_set_codepage(params, strings)
assert_equal(target, result, caption)
###############################################################################
#
# Test 2. _get_property_set_codepage() for manual utf8 strings.
#
params = {
:title => 'Title',
:subject => 'Subject',
:author => 'Author',
:keywords => 'Keywords',
:comments => 'Comments',
:last_author => 'Username',
:utf8 => 1,
}
strings = %w(title subject author keywords comments last_author)
caption = " \t_get_property_set_codepage('utf8')"
target = 0xFDE9
result = workbook.get_property_set_codepage(params, strings)
assert_equal(target, result, caption)
###############################################################################
#
# Test 3. _get_property_set_codepage() for utf8 strings.
#
params = {
:title => 'Title' + smiley,
:subject => 'Subject',
:author => 'Author',
:keywords => 'Keywords',
:comments => 'Comments',
:last_author => 'Username',
}
strings = %w(title subject author keywords comments last_author)
caption = " \t_get_property_set_codepage('utf8')";
target = 0xFDE9;
result = workbook.get_property_set_codepage(params, strings)
assert_equal(target, result, caption)
=end
###############################################################################
#
# Note, the "created => nil" parameters in some of the following tests is
# used to avoid adding the default date to the property sets.
###############################################################################
#
# Test 4. Codepage only.
#
workbook.set_properties(
:created => nil
)
caption = " \tset_properties(codepage)"
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(workbook.summary)
assert_equal(target, result, caption)
###############################################################################
#
# Test 5. Same as previous + Title.
#
workbook.set_properties(
:title => 'Title',
:created => nil
)
caption = " \tset_properties('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(workbook.summary)
assert_equal(target, result, caption)
###############################################################################
#
# Test 6. Same as previous + Subject.
#
workbook.set_properties(
:title => 'Title',
:subject => 'Subject',
:created => nil
)
caption = " \tset_properties('+ 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(workbook.summary)
assert_equal(target, result, caption)
###############################################################################
#
# Test 7. Same as previous + Author.
#
workbook.set_properties(
:title => 'Title',
:subject => 'Subject',
:author => 'Author',
:created => nil
)
caption = " \tset_properties('+ Author')"
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(workbook.summary)
assert_equal(target, result, caption)
###############################################################################
#
# Test 8. Same as previous + Keywords.
#
workbook.set_properties(
:title => 'Title',
:subject => 'Subject',
:author => 'Author',
:keywords => 'Keywords',
:created => nil
)
caption = " \tset_properties('+ 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(workbook.summary)
assert_equal(target, result, caption)
###############################################################################
#
# Test 9. Same as previous + Comments.
#
workbook.set_properties(
:title => 'Title',
:subject => 'Subject',
:author => 'Author',
:keywords => 'Keywords',
:comments => 'Comments',
:created => nil
)
caption = " \tset_properties('+ 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(workbook.summary)
assert_equal(target, result, caption)
###############################################################################
#
# Test 10. Same as previous + Last author.
#
workbook.set_properties(
:title => 'Title',
:subject => 'Subject',
:author => 'Author',
:keywords => 'Keywords',
:comments => 'Comments',
:last_author => 'Username',
:created => nil
)
caption = " \tset_properties('+ Last author')"
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(workbook.summary)
assert_equal(target, result, caption)
###############################################################################
#
# Test 11. Same as previous + Creation date.
#
# Aug 19 23:20:13 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,19,23,20,13)
workbook.set_properties(
:title => 'Title',
:subject => 'Subject',
:author => 'Author',
:keywords => 'Keywords',
:comments => 'Comments',
:last_author => 'Username',
:created => filetime
)
caption = " \tset_properties('+ Creation date')"
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(workbook.summary)
assert_equal(target, result, caption)
###############################################################################
#
# Test 12. Same as previous. Date set at the workbook level.
#
# Wed Aug 20 00:20:13 2008
# $sec,$min,$hour,$mday,$mon,$year
# We normalise the time using timegm() so that the tests don't fail due to
# different timezones.
workbook.localtime = Time.gm(2008,8,19,23,20,13)
workbook.set_properties(
:title => 'Title',
:subject => 'Subject',
:author => 'Author',
:keywords => 'Keywords',
:comments => 'Comments',
:last_author => 'Username'
)
caption = " \tset_properties('+ Creation date')"
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(workbook.summary)
assert_equal(target, result, caption)
###############################################################################
#
# Test 14. UTF-8 string used.
#
workbook.set_properties(
:title => 'Title' + smiley,
:created => nil
)
caption = " \tset_properties(utf8)"
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
34 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 E9 FD 00 00
1E 00 00 00 09 00 00 00 54 69 74 6C 65 E2 98 BA
00 00 00 00
).join(' ')
result = unpack_record(workbook.summary)
assert_equal(target, result, caption)
workbook.close
end
end
|
Radanisk/writeexcel
|
examples/regions.rb
|
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
###############################################################################
#
# Example of how to use the WriteExcel module to write a basic multiple
# worksheet Excel file.
#
# reverse('©'), March 2001, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
workbook = WriteExcel.new("regions.xls")
# Add some worksheets
north = workbook.add_worksheet("North")
south = workbook.add_worksheet("South")
east = workbook.add_worksheet("East")
west = workbook.add_worksheet("West")
# Add a Format
format = workbook.add_format()
format.set_bold()
format.set_color('blue')
# Add a caption to each worksheet
workbook.sheets.each do |worksheet|
worksheet.write(0, 0, "Sales", format)
end
# Write some data
north.write(0, 1, 200000)
south.write(0, 1, 100000)
east.write(0, 1, 150000)
west.write(0, 1, 100000)
# Set the active worksheet
south.activate()
# Set the width of the first column
south.set_column(0, 0, 20)
# Set the active cell
south.set_selection(0, 1)
workbook.close
|
Radanisk/writeexcel
|
lib/writeexcel/comments.rb
|
module Writeexcel
class Worksheet < BIFFWriter
require 'writeexcel/helper'
class Collection
def initialize
@items = {}
end
def <<(item)
if @items[item.row]
@items[item.row][item.col] = item
else
@items[item.row] = { item.col => item }
end
end
def array
return @array if @array
@array = []
@items.keys.sort.each do |row|
@items[row].keys.sort.each do |col|
@array << @items[row][col]
end
end
@array
end
end
class Comments < Collection
attr_writer :visible
def initialize
super
@visible = false
end
def visible?
@visible
end
end
class Comment
attr_reader :row, :col, :string, :encoding, :author, :author_encoding, :visible, :color, :vertices
def initialize(worksheet, row, col, string, options = {})
@worksheet = worksheet
@row, @col = row, col
@params = params_with(options)
@string, @params[:encoding] = string_and_encoding(string, @params[:encoding], 'comment')
# Limit the string to the max number of chars (not bytes).
max_len = 32767
max_len = max_len * 2 if @params[:encoding] != 0
if @string.bytesize > max_len
@string = @string[0 .. max_len]
end
@encoding = @params[:encoding]
@author = @params[:author]
@author_encoding = @params[:author_encoding]
@visible = @params[:visible]
@color = @params[:color]
@vertices = calc_vertices
end
def store_comment_record(i, num_objects, num_comments, spid)
str_len = string.bytesize
str_len = str_len / 2 if encoding != 0 # Num of chars not bytes.
spid = store_comment_mso_drawing_record(i, num_objects, num_comments, spid, visible, color, vertices)
store_obj_comment(num_objects + i + 1)
store_mso_drawing_text_box
store_txo(str_len)
store_txo_continue_1(string, encoding)
formats = [[0, 9], [str_len, 0]]
store_txo_continue_2(formats)
spid
end
#
# Write the worksheet NOTE record that is part of cell comments.
#
def store_note_record(obj_id) #:nodoc:
comment_author = author
comment_author_enc = author_encoding
ruby_19 { comment_author = [comment_author].pack('a*') if comment_author.ascii_only? }
record = 0x001C # Record identifier
length = 0x000C # Bytes to follow
comment_author = '' unless comment_author
comment_author_enc = 0 unless author_encoding
# Use the visible flag if set by the user or else use the worksheet value.
# The flag is also set in store_mso_opt_comment() but with the opposite
# value.
if visible
comment_visible = visible != 0 ? 0x0002 : 0x0000
else
comment_visible = @worksheet.comments_visible? ? 0x0002 : 0x0000
end
# Get the number of chars in the author string (not bytes).
num_chars = comment_author.bytesize
num_chars = num_chars / 2 if comment_author_enc != 0 && comment_author_enc
# Null terminate the author string.
comment_author =
ruby_18 { comment_author + "\0" } ||
ruby_19 { comment_author.force_encoding('BINARY') + "\0".force_encoding('BINARY') }
# Pack the record.
data = [@row, @col, comment_visible, obj_id, num_chars, comment_author_enc].pack("vvvvvC")
length = data.bytesize + comment_author.bytesize
header = [record, length].pack("vv")
append(header, data, comment_author)
end
#
# Write the Escher Opt record that is part of MSODRAWING.
#
def store_mso_opt_comment(spid, visible = nil, colour = 0x50) #:nodoc:
type = 0xF00B
version = 3
instance = 9
data = ''
length = 54
# Use the visible flag if set by the user or else use the worksheet value.
# Note that the value used is the opposite of Comment#note_record.
#
if visible
visible = visible != 0 ? 0x0000 : 0x0002
else
visible = @worksheet.comments_visible? ? 0x0000 : 0x0002
end
data = [spid].pack('V') +
['0000BF00080008005801000000008101'].pack("H*") +
[colour].pack("C") +
['000008830150000008BF011000110001'+'02000000003F0203000300BF03'].pack("H*") +
[visible].pack('v') +
['0A00'].pack('H*')
@worksheet.add_mso_generic(type, version, instance, data, length)
end
#
# OBJ record that is part of cell comments.
# obj_id # Object ID number.
#
def obj_comment_record(obj_id) #:nodoc:
record = 0x005D # Record identifier
length = 0x0034 # Bytes to follow
obj_type = 0x0019 # Object type (comment).
data = '' # Record data.
sub_record = 0x0000 # Sub-record identifier.
sub_length = 0x0000 # Length of sub-record.
sub_data = '' # Data of sub-record.
options = 0x4011
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 ftNts (note structure) subobject
sub_record = 0x000D # ftNts
sub_length = 0x0016
sub_data = [reserved,reserved,reserved,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.
header = [record, length].pack("vv")
header + data
end
private
def params_with(options)
params = default_params.update(options)
# Ensure that a width and height have been set.
params[:width] = default_width unless params[:width] && params[:width] != 0
params[:width] = params[:width] * params[:x_scale] if params[:x_scale] != 0
params[:height] = default_height unless params[:height] && params[:height] != 0
params[:height] = params[:height] * params[:y_scale] if params[:y_scale] != 0
params[:author], params[:author_encoding] =
string_and_encoding(params[:author], params[:author_encoding], 'author')
# Set the comment background colour.
params[:color] = background_color(params[:color])
# Set the default start cell and offsets for the comment. These are
# generally fixed in relation to the parent cell. However there are
# some edge cases for cells at the, er, edges.
#
params[:start_row] = default_start_row unless params[:start_row]
params[:y_offset] = default_y_offset unless params[:y_offset]
params[:start_col] = default_start_col unless params[:start_col]
params[:x_offset] = default_x_offset unless params[:x_offset]
params
end
def default_params
{
:author => '',
:author_encoding => 0,
:encoding => 0,
:color => nil,
:start_cell => nil,
:start_col => nil,
:start_row => nil,
:visible => nil,
:width => default_width,
:height => default_height,
:x_offset => nil,
:x_scale => 1,
:y_offset => nil,
:y_scale => 1
}
end
def default_width
128
end
def default_height
74
end
def default_start_row
case @row
when 0 then 0
when 65533 then 65529
when 65534 then 65530
when 65535 then 65531
else @row -1
end
end
def default_y_offset
case @row
when 0 then 2
when 65533 then 4
when 65534 then 4
when 65535 then 2
else 7
end
end
def default_start_col
case @col
when 253 then 250
when 254 then 251
when 255 then 252
else @col + 1
end
end
def default_x_offset
case @col
when 253 then 49
when 254 then 49
when 255 then 49
else 15
end
end
def string_and_encoding(string, encoding, type)
string = convert_to_ascii_if_ascii(string)
if encoding != 0
raise "Uneven number of bytes in #{type} string" if string.bytesize % 2 != 0
# Change from UTF-16BE to UTF-16LE
string = utf16be_to_16le(string)
# Handle utf8 strings
else
if is_utf8?(string)
string = NKF.nkf('-w16L0 -m0 -W', string)
ruby_19 { string.force_encoding('UTF-16LE') }
encoding = 1
end
end
[string, encoding]
end
def background_color(color)
color = Colors.new.get_color(color)
color = 0x50 if color == 0x7FFF # Default color.
color
end
# Calculate the positions of comment object.
def calc_vertices
@worksheet.position_object( @params[:start_col],
@params[:start_row],
@params[:x_offset],
@params[:y_offset],
@params[:width],
@params[:height]
)
end
def store_comment_mso_drawing_record(i, num_objects, num_comments, spid, visible, color, vertices)
if i == 0 && num_objects == 0
# Write the parent MSODRAWIING record.
dg_length = 200 + 128 * (num_comments - 1)
spgr_length = 176 + 128 * (num_comments - 1)
data = @worksheet.store_parent_mso_record(dg_length, spgr_length, spid)
spid += 1
else
data = ''
end
data += @worksheet.store_mso_sp_container(120) + @worksheet.store_mso_sp(202, spid, 0x0A00)
spid += 1
data +=
store_mso_opt_comment(0x80, visible, color) +
@worksheet.store_mso_client_anchor(3, *vertices) +
@worksheet.store_mso_client_data
record = 0x00EC # Record identifier
length = data.bytesize
header = [record, length].pack("vv")
append(header, data)
spid
end
def store_obj_comment(obj_id)
append(obj_comment_record(obj_id))
end
#
# Write the MSODRAWING ClientTextbox record that is part of comments.
#
def store_mso_drawing_text_box #:nodoc:
record = 0x00EC # Record identifier
length = 0x0008 # Bytes to follow
data = store_mso_client_text_box
header = [record, length].pack('vv')
append(header, data)
end
#
# Write the Escher ClientTextbox record that is part of MSODRAWING.
#
def store_mso_client_text_box #:nodoc:
type = 0xF00D
version = 0
instance = 0
data = ''
length = 0
@worksheet.add_mso_generic(type, version, instance, data, length)
end
#
# Write the worksheet TXO record that is part of cell comments.
# string_len # Length of the note text.
# format_len # Length of the format runs.
# rotation # Options
#
def store_txo(string_len, format_len = 16, rotation = 0) #:nodoc:
record = 0x01B6 # Record identifier
length = 0x0012 # Bytes to follow
grbit = 0x0212 # Options
reserved = 0x0000 # Options
# Pack the record.
header = [record, length].pack('vv')
data = [grbit, rotation, reserved, reserved, string_len, format_len, reserved].pack("vvVvvvV")
append(header, data)
end
#
# Write the first CONTINUE record to follow the TXO record. It contains the
# text data.
# string # Comment string.
# encoding # Encoding of the string.
#
def store_txo_continue_1(string, encoding = 0) #:nodoc:
# Split long comment strings into smaller continue blocks if necessary.
# We can't let BIFFwriter::_add_continue() handled this since an extra
# encoding byte has to be added similar to the SST block.
#
# We make the limit size smaller than the add_continue() size and even
# so that UTF16 chars occur in the same block.
#
limit = 8218
while string.bytesize > limit
string[0 .. limit] = ""
tmp_str = string
data = [encoding].pack("C") +
ruby_18 { tmp_str } ||
ruby_19 { tmp_str.force_encoding('ASCII-8BIT') }
length = data.bytesize
header = [record, length].pack('vv')
append(header, data)
end
# Pack the record.
data =
ruby_18 { [encoding].pack("C") + string } ||
ruby_19 { [encoding].pack("C") + string.force_encoding('ASCII-8BIT') }
record = 0x003C # Record identifier
length = data.bytesize
header = [record, length].pack('vv')
append(header, data)
end
#
# Write the second CONTINUE record to follow the TXO record. It contains the
# formatting information for the string.
# formats # Formatting information
#
def store_txo_continue_2(formats) #:nodoc:
# Pack the record.
data = ''
formats.each do |a_ref|
data += [a_ref[0], a_ref[1], 0x0].pack('vvV')
end
record = 0x003C # Record identifier
length = data.bytesize
header = [record, length].pack("vv")
append(header, data)
end
def append(*args)
@worksheet.append(*args)
end
end
end
end
|
Radanisk/writeexcel
|
lib/writeexcel.rb
|
# -*- coding: utf-8 -*-
###############################################################################
#
# WriteExcel.
#
# WriteExcel - Write to a cross-platform Excel binary file.
#
# Copyright 2000-2010, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel/biffwriter'
require 'writeexcel/olewriter'
require 'writeexcel/formula'
require 'writeexcel/format'
require 'writeexcel/worksheet'
require "writeexcel/workbook"
require 'writeexcel/chart'
require 'writeexcel/charts/area'
require 'writeexcel/charts/bar'
require 'writeexcel/charts/column'
require 'writeexcel/charts/external'
require 'writeexcel/charts/line'
require 'writeexcel/charts/pie'
require 'writeexcel/charts/scatter'
require 'writeexcel/charts/stock'
require 'writeexcel/storage_lite'
require 'writeexcel/compatibility'
require 'writeexcel/debug_info'
#
# = WriteExcel - Write to a cross-platform Excel binary file.
#
# == Contents
# SYSNOPSYS
# DESCRIPTION
# QUICK START
# WORKBOOK METHODS
# WORKSHEET METHODS
# PAGE SET-UP METHODS
# CELL FORMATTING
# FORMAT METHODS
# COLOURS IN EXCEL
# DATE AND TIME IN EXCEL
# OUTLINES AND GROUPING IN EXCEL
# DATA VALIDATION IN EXCEL
# FORMULAS AND FUNCTIONS IN EXCEL
# CHART
#
# == Synopsis
#
# To write a string, a formatted string, a number and a formula to the first
# worksheet in an Excel workbook called ruby.xls:
#
# require 'WriteExcel'
#
# # Create a new Excel workbook
# workbook = WriteExcel.new('ruby.xls')
#
# # Add a worksheet
# worksheet = workbook.add_worksheet
#
# # Add and define a format
# format = workbook.add_format # Add a format
# format.set_bold()
# format.set_color('red')
# format.set_align('center')
#
# # Write a formatted and unformatted string, row and column notation.
# col = row = 0
# worksheet.write(row, col, 'Hi Excel!', format)
# worksheet.write(1, col, 'Hi Excel!')
#
# # Write a number and a formula using A1 notation
# worksheet.write('A3', 1.2345)
# worksheet.write('A4', '=SIN(PI()/4)')
#
# # Save to ruby.xls
# workbook.close
#
# == Description
#
# WriteExcel can be used to create a cross-platform Excel binary file.
# Multiple worksheets can be added to a workbook and formatting can be applied
# to cells. Text, numbers, formulas, hyperlinks and images can be written to
# the cells.
#
# The Excel file produced by this gem is compatible with 97, 2000, 2002, 2003
# and 2007.
#
# WriteExcel will work on the majority of Windows, UNIX and Mac platforms.
# Generated files are also compatible with the Linux/UNIX spreadsheet
# applications Gnumeric and OpenOffice.org.
#
# This module cannot be used to write to an existing Excel file
#
# This library is converted from Spreadsheet::WriteExcel module of Perl.
# http://search.cpan.org/~jmcnamara/Spreadsheet-WriteExcel-2.37/
#
# == Quick Start
#
# WriteExcel tries to provide an interface to as many of Excel's features as
# possible. As a result there is a lot of documentation to accompany the
# interface and it can be difficult at first glance to see what it important
# and what is not. So for those of you who prefer to assemble Ikea furniture
# first and then read the instructions, here are four easy steps:
#
# 1. Create a new Excel workbook (i.e. file) using new().
#
# 2. Add a worksheet to the new workbook using add_worksheet().
#
# 3. Write to the worksheet using write().
#
# 4. Save to file.
#
# Like this:
#
# require 'WriteExcel' # Step 0
#
# workbook = WriteExcel.new('ruby.xls') # Step 1
# worksheet = workbook.add_worksheet # Step 2
# worksheet.write('A1', 'Hi Excel!') # Step 3
# workbook.close # Step 4
#
# This will create an Excel file called ruby.xls with a single worksheet and the
# text 'Hi Excel!' in the relevant cell. And that's it. Okay, so there is
# actually a zeroth step as well, but use WriteExcel goes without saying. There
# are also many examples that come with the distribution and which you can
# use to get you started. See EXAMPLES.
#
# = Workbook methods
#
# The WriteExcel module provides an object oriented interface
# to a new Excel workbook. The following methods are available through
# a new workbook.
#
# new()
# add_worksheet()
# add_format()
# add_chart()
# add_chart_ext()
# close()
# compatibility_mode()
# set_properties()
# define_name()
# set_tempdir()
# set_custom_color()
# sheets()
# set_1904()
# set_codepage()
#
# = Worksheet methods
#
# A new worksheet is created by calling the add_worksheet() method from
# a workbook object:
#
# worksheet1 = workbook.add_worksheet
# worksheet2 = workbook.add_worksheet
#
# The following methods are available through a new worksheet:
#
# write()
# write_number()
# write_string()
# write_utf16be_string()
# write_utf16le_string()
# keep_leading_zeros()
# write_blank()
# write_row()
# write_col()
# write_date_time()
# write_url()
# write_url_range()
# write_formula()
# store_formula()
# repeat_formula()
# write_comment()
# show_comments()
# add_write_handler() (* not implemented yet)
# insert_image()
# insert_chart()
# data_validation()
# get_name()
# activate()
# select()
# hide()
# set_first_sheet()
# protect()
# set_selection()
# set_row()
# set_column()
# outline_settings()
# freeze_panes()
# split_panes()
# merge_range()
# set_zoom()
# right_to_left()
# hide_zero()
# set_tab_color()
# autofilter()
#
# == Cell notation
# WriteExcel supports two forms of notation to designate the position of cells:
# Row-column notation and A1 notation.
#
# Row-column notation uses a zero based index for both row and column while A1
# notation uses the standard Excel alphanumeric sequence of column letter and
# 1-based row. For example:
#
# (0, 0) # The top left cell in row-column notation.
# ('A1') # The top left cell in A1 notation.
#
# (1999, 29) # Row-column notation.
# ('AD2000') # The same cell in A1 notation.
#
# Row-column notation is useful if you are referring to cells
# programmatically:
#
# (0 .. 10).each do |i|
# worksheet.write(i, 0, 'Hello') # Cells A1 to A10
# end
#
# A1 notation is useful for setting up a worksheet manually and for working
# with formulas:
#
# worksheet.write('H1', 200)
# worksheet.write('H2', '=H1+1')
#
# In formulas and applicable methods you can also use the A:A column notation:
#
# worksheet.write('A1', '=SUM(B:B)')
#
# For simplicity, the parameter lists for the worksheet method calls in the
# following sections are given in terms of row-column notation. In all cases
# it is also possible to use A1 notation.
#
# Note: in Excel it is also possible to use a R1C1 notation. This is not
# supported by WriteExcel.
#
# ==PAGE SET-UP METHODS
#
# Page set-up methods affect the way that a worksheet looks when it is printed.
# They control features such as page headers and footers and margins. These
# methods are really just standard worksheet methods. They are documented
# here in a separate section for the sake of clarity.
#
# The following methods are available for page set-up:
#
# set_landscape()
# set_portrait()
# set_page_view()
# set_paper()
# center_horizontally()
# center_vertically()
# set_margins()
# set_header()
# set_footer()
# repeat_rows()
# repeat_columns()
# hide_gridlines()
# print_row_col_headers()
# print_area()
# print_across()
# fit_to_pages()
# set_start_page()
# set_print_scale()
# set_h_pagebreaks()
# set_v_pagebreaks()
#
# A common requirement when working with WriteExcel is to apply the same page
# set-up features to all of the worksheets in a workbook. To do this you can use
# the sheets() method of the workbook class to access the array of worksheets
# in a workbook:
#
# workbook.sheets.each do |worksheet|
# worksheet.set_landscape
# end
#
# ==CELL FORMATTING
#
# This section describes the methods and properties that are available for
# formatting cells in Excel. The properties of a cell that can be formatted
# include: fonts, colours, patterns, borders, alignment and number formatting.
#
# ===Creating and using a Format object
#
# Cell formatting is defined through a Format object. Format objects are
# created by calling the workbook add_format() method as follows:
#
# format1 = workbook.add_format # Set properties later
# format2 = workbook.add_format(property hash..) # Set at creation
#
# The format object holds all the formatting properties that can be applied
# to a cell, a row or a column. The process of setting these properties is
# discussed in the next section.
#
# Once a Format object has been constructed and it properties have been set
# it can be passed as an argument to the worksheet write methods as follows:
#
# worksheet.write(0, 0, 'One', format)
# worksheet.write_string(1, 0, 'Two', format)
# worksheet.write_number(2, 0, 3, format)
# worksheet.write_blank(3, 0, format)
#
# Formats can also be passed to the worksheet set_row() and set_column()
# methods to define the default property for a row or column.
#
# worksheet.set_row(0, 15, format)
# worksheet.set_column(0, 0, 15, format)
#
# ===Format methods and Format properties
#
# The following table shows the Excel format categories, the formatting
# properties that can be applied and the equivalent object method:
#
# Category Description Property Method Name
# -------- ----------- -------- -----------
# Font Font type font set_font()
# Font size size set_size()
# Font color color set_color()
# Bold bold set_bold()
# Italic italic set_italic()
# Underline underline set_underline()
# Strikeout font_strikeout set_font_strikeout()
# Super/Subscript font_script set_font_script()
# Outline font_outline set_font_outline()
# Shadow font_shadow set_font_shadow()
#
# Number Numeric format num_format set_num_format()
#
# Protection Lock cells locked set_locked()
# Hide formulas hidden set_hidden()
#
# Alignment Horizontal align align set_align()
# Vertical align valign set_align()
# Rotation rotation set_rotation()
# Text wrap text_wrap set_text_wrap()
# Justify last text_justlast set_text_justlast()
# Center across center_across set_center_across()
# Indentation indent set_indent()
# Shrink to fit shrink set_shrink()
#
# Pattern Cell pattern pattern set_pattern()
# Background color bg_color set_bg_color()
# Foreground color fg_color set_fg_color()
#
# Border Cell border border set_border()
# Bottom border bottom set_bottom()
# Top border top set_top()
# Left border left set_left()
# Right border right set_right()
# Border color border_color set_border_color()
# Bottom color bottom_color set_bottom_color()
# Top color top_color set_top_color()
# Left color left_color set_left_color()
# Right color right_color set_right_color()
#
# There are two ways of setting Format properties: by using the object method
# interface or by setting the property directly. For example, a typical use of
# the method interface would be as follows:
#
# format = workbook.add_format
# format.set_bold
# format.set_color('red')
#
# By comparison the properties can be set directly by passing a hash of
# properties to the Format constructor:
#
# format = workbook.add_format(:bold => 1, :color => 'red')
#
# or after the Format has been constructed by means of the
# set_format_properties() method as follows:
#
# format = workbook.add_format
# format.set_format_properties(:bold => 1, :color => 'red')
#
# You can also store the properties in one or more named hashes and pass them
# to the required method:
#
# font = {
# :font => 'Arial',
# :size => 12,
# :color => 'blue',
# :bold => 1
# }
#
# shading = {
# :bg_color => 'green',
# :pattern => 1
# }
#
# format1 = workbook.add_format(font) # Font only
# format2 = workbook.add_format(font, shading) # Font and shading
#
# The provision of two ways of setting properties might lead you to wonder
# which is the best way. The method mechanism may be better is you prefer
# setting properties via method calls (which the author did when they were
# code was first written) otherwise passing properties to the constructor has
# proved to be a little more flexible and self documenting in practice. An
# additional advantage of working with property hashes is that it allows you to
# share formatting between workbook objects as shown in the example above.
#
#--
#
# did not converted ???
#
# The Perl/Tk style of adding properties is also supported:
#
# %font = (
# -font => 'Arial',
# -size => 12,
# -color => 'blue',
# -bold => 1,
# )
#++
#
# ===Working with formats
#
# The default format is Arial 10 with all other properties off.
#
# Each unique format in WriteExcel must have a corresponding
# Format object. It isn't possible to use a Format with a write() method and
# then redefine the Format for use at a later stage. This is because a Format
# is applied to a cell not in its current state but in its final state.
# Consider the following example:
#
# format = workbook.add_format
# format.set_bold
# format.set_color('red')
# worksheet.write('A1', 'Cell A1', format)
# format.set_color('green')
# worksheet.write('B1', 'Cell B1', format)
#
# Cell A1 is assigned the Format _format_ which is initially set to the colour
# red. However, the colour is subsequently set to green. When Excel displays
# Cell A1 it will display the final state of the Format which in this case
# will be the colour green.
#
# In general a method call without an argument will turn a property on,
# for example:
#
# format1 = workbook.add_format
# format1.set_bold # Turns bold on
# format1.set_bold(1) # Also turns bold on
# format1.set_bold(0) # Turns bold off
#
# ==FORMAT METHODS
#
# The Format object methods are described in more detail in the following
# sections. In addition, there is a Ruby program called formats.rb in the
# examples directory of the WriteExcel distribution. This program creates an
# Excel workbook called formats.xls which contains examples of almost all
# the format types.
#
# The following Format methods are available:
#
# set_font()
# set_size()
# set_color()
# set_bold()
# set_italic()
# set_underline()
# set_font_strikeout()
# set_font_script()
# set_font_outline()
# set_font_shadow()
# set_num_format()
# set_locked()
# set_hidden()
# set_align()
# set_rotation()
# set_text_wrap()
# set_text_justlast()
# set_center_across()
# set_indent()
# set_shrink()
# set_pattern()
# set_bg_color()
# set_fg_color()
# set_border()
# set_bottom()
# set_top()
# set_left()
# set_right()
# set_border_color()
# set_bottom_color()
# set_top_color()
# set_left_color()
# set_right_color()
#
# The above methods can also be applied directly as properties. For example
# format.set_bold is equivalent to workbook.add_format(:bold => 1).
#
# ==COLOURS IN EXCEL
#
# Excel provides a colour palette of 56 colours. In WriteExcel these colours
# are accessed via their palette index in the range 8..63. This index is used
# to set the colour of fonts, cell patterns and cell borders. For example:
#
# format = workbook.add_format(
# :color => 12, # index for blue
# :font => 'Arial',
# :size => 12,
# :bold => 1
# )
#
# The most commonly used colours can also be accessed by name. The name acts
# as a simple alias for the colour index:
#
# 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
#
# For example:
#
# font = workbook.add_format(:color => 'red')
#
# Users of VBA in Excel should note that the equivalent colour indices are in
# the range 1..56 instead of 8..63.
#
# If the default palette does not provide a required colour you can override
# one of the built-in values. This is achieved by using the set_custom_color()
# workbook method to adjust the RGB (red green blue) components of the colour:
#
# ferrari = workbook.set_custom_color(40, 216, 12, 12)
#
# format = workbook.add_format(
# :bg_color => ferrari,
# :pattern => 1,
# :border => 1
# )
#
# worksheet.write_blank('A1', format)
#
# You may also find the following links helpful:
#
# A detailed look at Excel's colour palette:
# http://www.mvps.org/dmcritchie/excel/colors.htm
#
# A decimal RGB chart: http://www.hypersolutions.org/pages/rgbdec.html
#
# A hex RGB chart: : http://www.hypersolutions.org/pages/rgbhex.html
#
# ==DATES AND TIME IN EXCEL
#
# There are two important things to understand about dates and times in Excel:
#
# 1. A date/time in Excel is a real number plus an Excel number format.
#
# 2. WriteExcel doesn't automatically convert date/time strings in write() to
# an Excel date/time.
#
# These two points are explained in more detail below along with some
# suggestions on how to convert times and dates to the required format.
#
# ===An Excel date/time is a number plus a format
#
# If you write a date string with write() then all you will get is a string:
#
# worksheet.write('A1', '02/03/04') # !! Writes a string not a date. !!
#
# Dates and times in Excel are represented by real numbers, for example
# "Jan 1 2001 12:30 AM" is represented by the number 36892.521.
#
# The integer part of the number stores the number of days since the epoch
# and the fractional part stores the percentage of the day.
#
# A date or time in Excel is just like any other number. To have the number
# display as a date you must apply an Excel number format to it. Here are
# some examples.
#
# #!/usr/bin/ruby -w
#
# require 'writeexcel'
#
# workbook = WriteExcel.new('date_examples.xls')
# worksheet = workbook.add_worksheet
#
# worksheet.set_column('A:A', 30) # For extra visibility.
#
# number = 39506.5
#
# worksheet.write('A1', number) # 39506.5
#
# format2 = workbook.add_format(:num_format => 'dd/mm/yy')
# worksheet.write('A2', number , format2); # 28/02/08
#
# format3 = workbook.add_format(:num_format => 'mm/dd/yy')
# worksheet.write('A3', number , format3); # 02/28/08
#
# format4 = workbook.add_format(:num_format => 'd-m-yyyy')
# worksheet.write('A4', .number , format4) # 28-2-2008
#
# format5 = workbook.add_format(:num_format => 'dd/mm/yy hh:mm')
# worksheet.write('A5', number , format5) # 28/02/08 12:00
#
# format6 = workbook.add_format(:num_format => 'd mmm yyyy')
# worksheet.write('A6', number , format6) # 28 Feb 2008
#
# format7 = workbook.add_format(:num_format => 'mmm d yyyy hh:mm AM/PM')
# worksheet.write('A7', number , format7) # Feb 28 2008 12:00 PM
#
# ===WriteExcel doesn't automatically convert date/time strings
#
# WriteExcel doesn't automatically convert input date strings into Excel's
# formatted date numbers due to the large number of possible date formats
# and also due to the possibility of misinterpretation.
#
# For example, does 02/03/04 mean March 2 2004, February 3 2004 or even March
# 4 2002.
#
# Therefore, in order to handle dates you will have to convert them to numbers
# and apply an Excel format. Some methods for converting dates are listed in
# the next section.
#
# The most direct way is to convert your dates to the ISO8601
# yyyy-mm-ddThh:mm:ss.sss date format and use the write_date_time() worksheet
# method:
#
# worksheet.write_date_time('A2', '2001-01-01T12:20', format)
#
# See the write_date_time() section of the documentation for more details.
#
# A general methodology for handling date strings with write_date_time() is:
#
# 1. Identify incoming date/time strings with a regex.
# 2. Extract the component parts of the date/time using the same regex.
# 3. Convert the date/time to the ISO8601 format.
# 4. Write the date/time using write_date_time() and a number format.
#
# Here is an example:
#
# #!/usr/bin/ruby -w
#
# require 'writeexcel'
#
# workbook = WriteExcel.new('example.xls')
# worksheet = workbook.add_worksheet
#
# # Set the default format for dates.
# date_format = workbook.add_format(:num_format => 'mmm d yyyy')
#
# # Increase column width to improve visibility of data.
# worksheet.set_column('A:C', 20)
#
# data = [
# %w(Item Cost Date),
# %w(Book 10 1/9/2007),
# %w(Beer 4 12/9/2007),
# %w(Bed 500 5/10/2007)
# ]
#
# # Simulate reading from a data source.
# row = 0
#
# data.each do |row_data|
# col = 0
# row_data.each do |item|
#
# # Match dates in the following formats: d/m/yy, d/m/yyyy
# if item =~ %r[^(\d{1,2})/(\d{1,2})/(\d{4})$]
# # Change to the date format required by write_date_time().
# date = sprintf "%4d-%02d-%02dT", $3, $2, $1
# worksheet.write_date_time(row, col, date, date_format)
# else
# # Just plain data
# worksheet.write(row, col, item)
# end
# col += 1
# end
# row += 1
# end
#
#--
# For a slightly more advanced solution you can modify the write() method to
# handle date formats of your choice via the add_write_handler() method. See
# the add_write_handler() section of the docs and the write_handler3.rb and
# write_handler4.rb programs in the examples directory of the distro.
#++
#
# ==OUTLINES AND GROUPING IN EXCEL
#
# Excel allows you to group rows or columns so that they can be hidden or
# displayed with a single mouse click. This feature is referred to as outlines.
#
# Outlines can reduce complex data down to a few salient sub-totals or
# summaries.
#
# This feature is best viewed in Excel but the following is an ASCII
# representation of what a worksheet with three outlines might look like. Rows
# 3-4 and rows 7-8 are grouped at level 2. Rows 2-9 are grouped at level 1.
# The lines at the left hand side are called outline level bars.
#
# ------------------------------------------
# 1 2 3 | | A | B | C | D | ...
# ------------------------------------------
# _ | 1 | A | | | | ...
# | _ | 2 | B | | | | ...
# | | | 3 | (C) | | | | ...
# | | | 4 | (D) | | | | ...
# | - | 5 | E | | | | ...
# | _ | 6 | F | | | | ...
# | | | 7 | (G) | | | | ...
# | | | 8 | (H) | | | | ...
# | - | 9 | I | | | | ...
# - | . | ... | ... | ... | ... | ...
#
# Clicking the minus sign on each of the level 2 outlines will collapse and
# hide the data as shown in the next figure. The minus sign changes to a plus
# sign to indicate that the data in the outline is hidden.
#
# ------------------------------------------
# 1 2 3 | | A | B | C | D | ...
# ------------------------------------------
# _ | 1 | A | | | | ...
# | | 2 | B | | | | ...
# | + | 5 | E | | | | ...
# | | 6 | F | | | | ...
# | + | 9 | I | | | | ...
# - | . | ... | ... | ... | ... | ...
#
# Clicking on the minus sign on the level 1 outline will collapse the
# remaining rows as follows:
#
# ------------------------------------------
# 1 2 3 | | A | B | C | D | ...
# ------------------------------------------
# | 1 | A | | | | ...
# + | . | ... | ... | ... | ... | ...
#
# Grouping in WriteExcel is achieved by setting the outline level via the
# set_row() and set_column() worksheet methods:
#
# set_row(row, height, format, hidden, level, collapsed)
# set_column(first_col, last_col, width, format, hidden, level, collapsed)
#
# The following example sets an outline level of 1 for rows 1 and 2
# (zero-indexed) and columns B to G. The parameters _height_ and _format_ are
# assigned default values since they are undefined:
#
# worksheet.set_row(1, nil, nil, 0, 1)
# worksheet.set_row(2, nil, nil, 0, 1)
# worksheet.set_column('B:G', nil, nil, 0, 1)
#
# Excel allows up to 7 outline levels. Therefore the _level_ parameter should
# be in the range 0 <= _level_ <= 7.
#
# Rows and columns can be collapsed by setting the _hidden_ flag for the hidden
# rows/columns and setting the _collapsed_ flag for the row/column that has
# the collapsed + symbol:
#
# worksheet.set_row(1, nil, nil, 1, 1)
# worksheet.set_row(2, nil, nil, 1, 1)
# worksheet.set_row(3, nil, nil, 0, 0, 1) # Collapsed flag.
#
# worksheet.set_column('B:G', nil, nil, 1, 1)
# worksheet.set_column('H:H', nil, nil, 0, 0, 1) # Collapsed flag.
#
# Note: Setting the _collapsed_ flag is particularly important for
# compatibility with OpenOffice.org and Gnumeric.
#
# For a more complete example see the outline.rb
# and outline_collapsed.rb
# programs in the examples directory of the distro.
#
# Some additional outline properties can be set via the outline_settings()
# worksheet method, see above.
#
# ==DATA VALIDATION IN EXCEL
#
# Data validation is a feature of Excel which allows you to restrict the data
# that a users enters in a cell and to display help and warning messages. It
# also allows you to restrict input to values in a drop down list.
#
# A typical use case might be to restrict data in a cell to integer values in
# a certain range, to provide a help message to indicate the required value and
# to issue a warning if the input data doesn't meet the stated criteria.
# In WriteExcel we could do that as follows:
#
# worksheet.data_validation('B3',
# {
# :validate => 'integer',
# :criteria => 'between',
# :minimum => 1,
# :maximum => 100,
# :input_title => 'Input an integer:',
# :input_message => 'Between 1 and 100',
# :error_message => 'Sorry, try again.'
# })
#
# The above example would look like this in Excel:
# http://homepage.eircom.net/~jmcnamara/perl/data_validation.jpg.
#
# For more information on data validation see the following Microsoft
# support article "Description and examples of data validation in Excel":
# http://support.microsoft.com/kb/211485.
#
# ==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 WriteExcel::Utility module that is included in the distro
# contains helper functions for dealing with A1 notation, for example:
#
# use Spreadsheet::WriteExcel::Utility;
#
# ($row, $col) = xl_cell_to_rowcol('C2'); # (1, 2)
# $str = xl_rowcol_to_cell(1, 2); # C2
#++
#
# 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. 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).to_s)
# end
#
# On an arbitrary test machine this method was 10 times faster than the
# brute force method shown above.
#
# It should be noted however that the overall speed of direct formula parsing
# will be improved in a future version.
#
# ==Chart
#
# ===Synopsis(Chart)
#
# To create a simple Excel file with a chart using WriteExcel:
#
# #!/usr/bin/ruby -w
#
# require 'writeexcel'
#
# workbook = WriteExcel.new('chart.xls')
# worksheet = workbook.add_worksheet
#
# chart = workbook.add_chart(:type => 'Chart::Column')
#
# # Configure the chart.
# chart.add_series(
# :categories => '=Sheet1!$A$2:$A$7',
# :values => '=Sheet1!$B$2:$B$7'
# )
#
# # Add the data to the worksheet 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(Chart)
#
# The Chart module is an abstract base class for modules that implement charts
# in WriteExcel. The information below is applicable to all of the available
# subclasses.
#
# The Chart module isn't used directly, a chart object is created via the
# Workbook add_chart() method where the chart type is specified:
#
# chart = workbook.add_chart(:type => 'Chart::Column')
#
# Currently the supported chart types are:
#
# * 'Chart::Column': Creates a column style (histogram) chart. See Column.
# * 'Chart::Bar': Creates a Bar style (transposed histogram) chart. See Bar.
# * 'Chart::Line': Creates a Line style chart. See Line.
# * 'Chart::Area': Creates an Area (filled line) style chart. See Area.
# * 'Chart::Scatter': Creates an Scatter style chart. See Scatter.
# * 'Chart::Stock': Creates an Stock style chart. See Stock.
#
# More chart types will be supported in time. See the "TODO" section.
#
# === Chart names and links
#
# The add_series()), set_x_axis(), set_y_axis() and set_title() methods all
# support a name property. In general these names can be either a static
# string or a link to a worksheet cell. If you choose to use the name_formula
# property to specify a link then you should also the name property.
# This isn't strictly required by Excel but some third party applications
# expect it to be present.
#
# chartl.set_title(
# :name => 'Year End Results',
# :name_formula => '=Sheet1!$C$1'
# )
#
# These links should be used sparingly since they aren't commonly
# used in Excel charts.
#
# === Chart names and Unicode
#
# The add_series()), set_x_axis(), set_y_axis() and set_title() methods all
# support a name property. These names can be UTF8 strings.
#
# This methodology is explained in the "UNICODE IN EXCEL" section of WriteExcel
# but is semi-deprecated. If you are using Unicode the easiest option is to
# just use UTF8.
#
# === TODO(Chart)
#
# Charts in WriteExcel are a work in progress. More chart types and
# features will be added in time. Please be patient. Even a small feature
# can take a week or more to implement, test and document.
#
# Features that are on the TODO list and will be added are:
#
# * Additional chart types. Stock, Pie and Scatter charts are next in line.
# Send an email if you are interested in other types and they will be
# added to the queue.
# * Colours and formatting options. For now you will have to make do
# with the default Excel colours and formats.
# * Axis controls, gridlines.
# * Embedded data in charts for third party application support.
#
# == KNOWN ISSUES(Chart)
#
# * Currently charts don't contain embedded data from which the charts
# can be rendered. Excel and most other third party applications ignore
# this and read the data via the links that have been specified. However,
# some applications may complain or not render charts correctly. The
# preview option in Mac OS X is an known example. This will be fixed
# in a later release.
# * When there are several charts with titles set in a workbook some of
# the titles may display at a font size of 10 instead of the default
# 12 until another chart with the title set is viewed.
#
class WriteExcel < Workbook
if RUBY_VERSION < '1.9'
$KCODE = 'u'
end
end
|
Radanisk/writeexcel
|
test/test_63_chart_area_formats.rb
|
# -*- coding: utf-8 -*-
require 'helper'
require 'stringio'
###############################################################################
#
# A test for Spreadsheet::Writeexcel::Chart.
#
# Tests for the Excel Chart.pm format conversion methods.
#
# reverse('ゥ'), January 2010, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
class TC_ChartAreaFormats < Test::Unit::TestCase
def setup
@io = StringIO.new
@workbook = WriteExcel.new(@io)
@chart = @workbook.add_chart(:type => 'Chart::Column')
@chart.using_tmpfile = false
@caption1 = " \tChart: chartarea format - line";
@caption2 = " \tChart: chartarea format - area";
@embed_caption1 = " \tChart: embedded chartarea format - line";
@embed_caption2 = " \tChart: embedded chartarea format - area";
@plotarea_caption1 = " \tChart: plotarea format - line";
@plotarea_caption2 = " \tChart: plotarea format - area";
end
###############################################################################
#
# 1. Test the chartarea format methods. See the set_*area() properties below.
#
def test_the_chartarea_format_methods
reset_chart(@chart)
@chart.set_chartarea(
:color => 'red',
:line_color => 'black',
:line_pattern => 2,
:line_weight => 3
)
expected_line = %w(
07 10 0C 00 00 00 00 00 01 00 01 00 00 00 08 00
).join(' ')
expected_area = %w(
0A 10 10 00 FF 00 00 00 00 00 00 00 01 00 00 00
0A 00 08 00
).join(' ')
got_line, got_area = get_chartarea_formats(@chart)
assert_equal(expected_line, got_line, @caption1)
assert_equal(expected_area, got_area, @caption2)
reset_chart(@chart)
@chart.set_chartarea(
:color => 'red'
)
expected_line = %w(
07 10 0C 00 00 00 00 00 05 00 FF FF 08 00 4D 00
).join(' ')
expected_area = %w(
0A 10 10 00 FF 00 00 00 00 00 00 00 01 00 00 00
0A 00 08 00
).join(' ')
got_line, got_area = get_chartarea_formats(@chart)
assert_equal(expected_line, got_line, @caption1)
assert_equal(expected_area, got_area, @caption2)
reset_chart(@chart)
@chart.set_chartarea(
:line_color => 'red'
)
expected_line = %w(
07 10 0C 00 FF 00 00 00 00 00 FF FF 00 00 0A 00
).join(' ')
expected_area = %w(
0A 10 10 00 FF FF FF 00 00 00 00 00 00 00 00 00
4E 00 4D 00
).join(' ')
got_line, got_area = get_chartarea_formats(@chart)
assert_equal(expected_line, got_line, @caption1)
assert_equal(expected_area, got_area, @caption2)
reset_chart(@chart)
@chart.set_chartarea(
:line_pattern => 2
)
expected_line = %w(
07 10 0C 00 00 00 00 00 01 00 FF FF 00 00 4F 00
).join(' ')
expected_area = %w(
0A 10 10 00 FF FF FF 00 00 00 00 00 00 00 00 00
4E 00 4D 00
).join(' ')
got_line, got_area = get_chartarea_formats(@chart)
assert_equal(expected_line, got_line, @caption1)
assert_equal(expected_area, got_area, @caption2)
reset_chart(@chart)
@chart.set_chartarea(
:line_weight => 3
)
expected_line = %w(
07 10 0C 00 00 00 00 00 00 00 01 00 00 00 4F 00
).join(' ')
expected_area = %w(
0A 10 10 00 FF FF FF 00 00 00 00 00 00 00 00 00
4E 00 4D 00
).join(' ')
got_line, got_area = get_chartarea_formats(@chart)
assert_equal(expected_line, got_line, @caption1)
assert_equal(expected_area, got_area, @caption2)
reset_chart(@chart)
@chart.set_chartarea(
:color => 'red',
:line_color => 'black'
)
expected_line = %w(
07 10 0C 00 00 00 00 00 00 00 FF FF 00 00 08 00
).join(' ')
expected_area = %w(
0A 10 10 00 FF 00 00 00 00 00 00 00 01 00 00 00
0A 00 08 00
).join(' ')
got_line, got_area = get_chartarea_formats(@chart)
assert_equal(expected_line, got_line, @caption1)
assert_equal(expected_area, got_area, @caption2)
reset_chart(@chart)
@chart.set_chartarea(
:color => 'red',
:line_pattern => 2
)
expected_line = %w(
07 10 0C 00 00 00 00 00 01 00 FF FF 00 00 4F 00
).join(' ')
expected_area = %w(
0A 10 10 00 FF 00 00 00 00 00 00 00 01 00 00 00
0A 00 08 00
).join(' ')
got_line, got_area = get_chartarea_formats(@chart)
assert_equal(expected_line, got_line, @caption1)
assert_equal(expected_area, got_area, @caption2)
reset_chart(@chart)
@chart.set_chartarea(
:color => 'red',
:line_weight => 3
)
expected_line = %w(
07 10 0C 00 00 00 00 00 00 00 01 00 00 00 4F 00
).join(' ')
expected_area = %w(
0A 10 10 00 FF 00 00 00 00 00 00 00 01 00 00 00
0A 00 08 00
).join(' ')
got_line, got_area = get_chartarea_formats(@chart)
assert_equal(expected_line, got_line, @caption1)
assert_equal(expected_area, got_area, @caption2)
@chart.embedded = true
reset_chart(@chart, true)
@chart.set_chartarea(
)
expected_line = %w(
07 10 0C 00 00 00 00 00 00 00 00 00 09 00 4D 00
).join(' ')
expected_area = %w(
0A 10 10 00 FF FF FF 00 00 00 00 00 01 00 01 00
4E 00 4D 00
).join(' ')
got_line, got_area = get_chartarea_formats(@chart)
assert_equal(expected_line, got_line, @embed_caption1)
assert_equal(expected_area, got_area, @embed_caption2)
reset_chart(@chart, true)
@chart.set_chartarea(
:color => 'red',
:line_color => 'black',
:line_pattern => 2,
:line_weight => 3
)
expected_line = %w(
07 10 0C 00 00 00 00 00 01 00 01 00 00 00 08 00
).join(' ')
expected_area = %w(
0A 10 10 00 FF 00 00 00 00 00 00 00 01 00 00 00
0A 00 08 00
).join(' ')
got_line, got_area = get_chartarea_formats(@chart)
assert_equal(expected_line, got_line, @embed_caption1)
assert_equal(expected_area, got_area, @embed_caption2)
reset_chart(@chart, true)
@chart.set_chartarea(
:color => 'red'
)
expected_line = %w(
07 10 0C 00 00 00 00 00 00 00 FF FF 09 00 4D 00
).join(' ')
expected_area = %w(
0A 10 10 00 FF 00 00 00 00 00 00 00 01 00 00 00
0A 00 08 00
).join(' ')
got_line, got_area = get_chartarea_formats(@chart)
assert_equal(expected_line, got_line, @embed_caption1)
assert_equal(expected_area, got_area, @embed_caption2)
reset_chart(@chart, true)
@chart.set_chartarea(
:line_color => 'red'
)
expected_line = %w(
07 10 0C 00 FF 00 00 00 00 00 FF FF 00 00 0A 00
).join(' ')
expected_area = %w(
0A 10 10 00 FF FF FF 00 00 00 00 00 01 00 01 00
4E 00 4D 00
).join(' ')
got_line, got_area = get_chartarea_formats(@chart)
assert_equal(expected_line, got_line, @embed_caption1)
assert_equal(expected_area, got_area, @embed_caption2)
reset_chart(@chart, true)
@chart.set_chartarea(
:line_pattern => 2
)
expected_line = %w(
07 10 0C 00 00 00 00 00 01 00 FF FF 00 00 4F 00
).join(' ')
expected_area = %w(
0A 10 10 00 FF FF FF 00 00 00 00 00 01 00 01 00
4E 00 4D 00
).join(' ')
got_line, got_area = get_chartarea_formats(@chart)
assert_equal(expected_line, got_line, @embed_caption1)
assert_equal(expected_area, got_area, @embed_caption2)
reset_chart(@chart, true)
@chart.set_chartarea(
:line_weight => 3
)
expected_line = %w(
07 10 0C 00 00 00 00 00 00 00 01 00 00 00 4F 00
).join(' ')
expected_area = %w(
0A 10 10 00 FF FF FF 00 00 00 00 00 01 00 01 00
4E 00 4D 00
).join(' ')
got_line, got_area = get_chartarea_formats(@chart)
assert_equal(expected_line, got_line, @embed_caption1)
assert_equal(expected_area, got_area, @embed_caption2)
reset_chart(@chart, true)
@chart.set_chartarea(
:color => 'red',
:line_color => 'black'
)
expected_line = %w(
07 10 0C 00 00 00 00 00 00 00 FF FF 00 00 08 00
).join(' ')
expected_area = %w(
0A 10 10 00 FF 00 00 00 00 00 00 00 01 00 00 00
0A 00 08 00
).join(' ')
got_line, got_area = get_chartarea_formats(@chart)
assert_equal(expected_line, got_line, @embed_caption1)
assert_equal(expected_area, got_area, @embed_caption2)
reset_chart(@chart, true)
@chart.set_chartarea(
:color => 'red',
:line_pattern => 2
)
expected_line = %w(
07 10 0C 00 00 00 00 00 01 00 FF FF 00 00 4F 00
).join(' ')
expected_area = %w(
0A 10 10 00 FF 00 00 00 00 00 00 00 01 00 00 00
0A 00 08 00
).join(' ')
got_line, got_area = get_chartarea_formats(@chart)
assert_equal(expected_line, got_line, @embed_caption1)
assert_equal(expected_area, got_area, @embed_caption2)
reset_chart(@chart, true)
@chart.set_chartarea(
:color => 'red',
:line_weight => 3
)
expected_line = %w(
07 10 0C 00 00 00 00 00 00 00 01 00 00 00 4F 00
).join(' ')
expected_area = %w(
0A 10 10 00 FF 00 00 00 00 00 00 00 01 00 00 00
0A 00 08 00
).join(' ')
got_line, got_area = get_chartarea_formats(@chart)
assert_equal(expected_line, got_line, @embed_caption1)
assert_equal(expected_area, got_area, @embed_caption2)
@chart.embedded = false
reset_chart(@chart)
@chart.set_plotarea(
)
expected_line = %w(
07 10 0C 00 80 80 80 00 00 00 00 00 00 00 17 00
).join(' ')
expected_area = %w(
0A 10 10 00 C0 C0 C0 00 00 00 00 00 01 00 00 00
16 00 4F 00
).join(' ')
got_line, got_area = get_plotarea_formats(@chart)
assert_equal(expected_line, got_line, @plotarea_caption1)
assert_equal(expected_area, got_area, @plotarea_caption2)
reset_chart(@chart)
@chart.set_plotarea(
:color => 'red',
:line_color => 'black',
:line_pattern => 2,
:line_weight => 3
)
expected_line = %w(
07 10 0C 00 00 00 00 00 01 00 01 00 00 00 08 00
).join(' ')
expected_area = %w(
0A 10 10 00 FF 00 00 00 00 00 00 00 01 00 00 00
0A 00 08 00
).join(' ')
got_line, got_area = get_plotarea_formats(@chart)
assert_equal(expected_line, got_line, @plotarea_caption1)
assert_equal(expected_area, got_area, @plotarea_caption2)
reset_chart(@chart)
@chart.set_plotarea(
:color => 'red'
)
expected_line = %w(
07 10 0C 00 80 80 80 00 00 00 00 00 00 00 17 00
).join(' ')
expected_area = %w(
0A 10 10 00 FF 00 00 00 00 00 00 00 01 00 00 00
0A 00 08 00
).join(' ')
got_line, got_area = get_plotarea_formats(@chart)
assert_equal(expected_line, got_line, @plotarea_caption1)
assert_equal(expected_area, got_area, @plotarea_caption2)
reset_chart(@chart)
@chart.set_plotarea(
:line_color => 'red'
)
expected_line = %w(
07 10 0C 00 FF 00 00 00 00 00 00 00 00 00 0A 00
).join(' ')
expected_area = %w(
0A 10 10 00 C0 C0 C0 00 00 00 00 00 01 00 00 00
16 00 08 00
).join(' ')
got_line, got_area = get_plotarea_formats(@chart)
assert_equal(expected_line, got_line, @plotarea_caption1)
assert_equal(expected_area, got_area, @plotarea_caption2)
reset_chart(@chart)
@chart.set_plotarea(
:line_pattern => 2
)
expected_line = %w(
07 10 0C 00 80 80 80 00 01 00 00 00 00 00 17 00
).join(' ')
expected_area = %w(
0A 10 10 00 C0 C0 C0 00 00 00 00 00 01 00 00 00
16 00 08 00
).join(' ')
got_line, got_area = get_plotarea_formats(@chart)
assert_equal(expected_line, got_line, @plotarea_caption1)
assert_equal(expected_area, got_area, @plotarea_caption2)
reset_chart(@chart)
@chart.set_plotarea(
:line_weight => 3
)
expected_line = %w(
07 10 0C 00 80 80 80 00 00 00 01 00 00 00 17 00
).join(' ')
expected_area = %w(
0A 10 10 00 C0 C0 C0 00 00 00 00 00 01 00 00 00
16 00 08 00
).join(' ')
got_line, got_area = get_plotarea_formats(@chart)
assert_equal(expected_line, got_line, @plotarea_caption1)
assert_equal(expected_area, got_area, @plotarea_caption2)
reset_chart(@chart)
@chart.set_plotarea(
:color => 'red',
:line_color => 'black'
)
expected_line = %w(
07 10 0C 00 00 00 00 00 00 00 00 00 00 00 08 00
).join(' ')
expected_area = %w(
0A 10 10 00 FF 00 00 00 00 00 00 00 01 00 00 00
0A 00 08 00
).join(' ')
got_line, got_area = get_plotarea_formats(@chart)
assert_equal(expected_line, got_line, @plotarea_caption1)
assert_equal(expected_area, got_area, @plotarea_caption2)
reset_chart(@chart)
@chart.set_plotarea(
:color => 'red',
:line_pattern => 2
)
expected_line = %w(
07 10 0C 00 80 80 80 00 01 00 00 00 00 00 17 00
).join(' ')
expected_area = %w(
0A 10 10 00 FF 00 00 00 00 00 00 00 01 00 00 00
0A 00 08 00
).join(' ')
got_line, got_area = get_plotarea_formats(@chart)
assert_equal(expected_line, got_line, @plotarea_caption1)
assert_equal(expected_area, got_area, @plotarea_caption2)
reset_chart(@chart)
@chart.set_plotarea(
:color => 'red',
:line_weight => 3
)
expected_line = %w(
07 10 0C 00 80 80 80 00 00 00 01 00 00 00 17 00
).join(' ')
expected_area = %w(
0A 10 10 00 FF 00 00 00 00 00 00 00 01 00 00 00
0A 00 08 00
).join(' ')
got_line, got_area = get_plotarea_formats(@chart)
assert_equal(expected_line, got_line, @plotarea_caption1)
assert_equal(expected_area, got_area, @plotarea_caption2)
end
###############################################################################
#
# Reset the chart data for testing.
#
def reset_chart(chart, embedded = nil)
# Reset the chart data.
chart.data = ''
chart.__send__("set_default_properties")
if embedded
chart.set_embedded_config_data
end
end
###############################################################################
#
# Extract Line and Area format records from the Chartarea Frame stream.
#
def get_chartarea_formats(chart)
chart.__send__("store_chartarea_frame_stream")
line = unpack_record(chart.data[12, 16])
area = unpack_record(chart.data[28, 20])
[line, area]
end
###############################################################################
#
# Extract Line and Area format records from the Chartarea Frame stream.
#
def get_plotarea_formats(chart)
chart.__send__("store_plotarea_frame_stream")
line = unpack_record(chart.data[12, 16])
area = unpack_record(chart.data[28, 20])
[line, area]
end
end
|
Radanisk/writeexcel
|
lib/writeexcel/biffwriter.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>
#
require 'tempfile'
require 'writeexcel/write_file'
class BIFFWriter < WriteFile #:nodoc:
BIFF_Version = 0x0600
BigEndian = [1].pack("I") == [1].pack("N")
attr_reader :data, :datasize
######################################################################
# The args here aren't used by BIFFWriter, but they are needed by its
# subclasses. I don't feel like creating multiple constructors.
######################################################################
def initialize
super
set_byte_order
@ignore_continue = false
end
###############################################################################
#
# _set_byte_order()
#
# Determine the byte order and store it as class data to avoid
# recalculating it for each call to new().
#
def set_byte_order
# Check if "pack" gives the required IEEE 64bit float
teststr = [1.2345].pack("d")
hexdata = [0x8D, 0x97, 0x6E, 0x12, 0x83, 0xC0, 0xF3, 0x3F]
number = hexdata.pack("C8")
if number == teststr
@byte_order = false # Little Endian
elsif number == teststr.reverse
@byte_order = true # Big Endian
else
# Give up. I'll fix this in a later version.
raise( "Required floating point format not supported " +
"on this platform. See the portability section " +
"of the documentation."
)
end
end
###############################################################################
#
# get_data().
#
# Retrieves data from memory in one chunk, or from disk in $buffer
# sized chunks.
#
def get_data
buflen = 4096
# Return data stored in memory
unless @data.nil?
tmp = @data
@data = nil
if @using_tmpfile
@filehandle.open
@filehandle.binmode
end
return tmp
end
# Return data stored on disk
if @using_tmpfile
return @filehandle.read(buflen)
end
# No data to return
nil
end
###############################################################################
#
# _store_bof($type)
#
# $type = 0x0005, Workbook
# $type = 0x0010, Worksheet
# $type = 0x0020, Chart
#
# Writes Excel BOF record to indicate the beginning of a stream or
# sub-stream in the BIFF file.
#
def store_bof(type = 0x0005)
record = 0x0809 # Record identifier
length = 0x0010 # Number of bytes to follow
# According to the SDK $build and $year should be set to zero.
# However, this throws a warning in Excel 5. So, use these
# magic numbers.
build = 0x0DBB
year = 0x07CC
bfh = 0x00000041
sfo = 0x00000006
header = [record,length].pack("vv")
data = [BIFF_Version,type,build,year,bfh,sfo].pack("vvvvVV")
prepend(header, data)
end
###############################################################################
#
# _store_eof()
#
# Writes Excel EOF record to indicate the end of a BIFF stream.
#
def store_eof
record = 0x000A
length = 0x0000
header = [record,length].pack("vv")
append(header)
end
###############################################################################
#
# _add_continue()
#
# Excel limits the size of BIFF records. In Excel 5 the limit is 2084 bytes. In
# Excel 97 the limit is 8228 bytes. Records that are longer than these limits
# must be split up into CONTINUE blocks.
#
# This function take a long BIFF record and inserts CONTINUE records as
# necessary.
#
# Some records have their own specialised Continue blocks so there is also an
# option to bypass this function.
#
def add_continue(data)
# Skip this if another method handles the continue blocks.
return data if @ignore_continue
record = 0x003C # Record identifier
header = [record, @limit].pack("vv")
# The first 2080/8224 bytes remain intact. However, we have to change
# the length field of the record.
#
data_array = split_by_length(data, @limit)
first_data = data_array.shift
last_data = data_array.pop || ''
first_data[2, 2] = [@limit-4].pack('v')
first_data <<
data_array.join(header) <<
[record, last_data.bytesize].pack('vv') <<
last_data
end
###############################################################################
#
# _add_mso_generic()
# my $type = $_[0];
# my $version = $_[1];
# my $instance = $_[2];
# my $data = $_[3];
#
# Create a mso structure that is part of an Escher drawing object. These are
# are used for images, comments and filters. This generic method is used by
# other methods to create specific mso records.
#
# Returns the packed record.
#
def add_mso_generic(type, version, instance, data, length = nil)
length ||= data.bytesize
# The header contains version and instance info packed into 2 bytes.
header = version | (instance << 4)
record = [header, type, length].pack('vvV') + data
end
def not_using_tmpfile
@filehandle.close(true) if @filehandle
@filehandle = nil
@using_tmpfile = nil
end
def clear_data_for_test # :nodoc:
@data = ''
end
def cleanup # :nodoc:
@filehandle.close(true) if @filehandle
end
# override Object#inspect
def inspect # :nodoc:
to_s
end
private
def split_by_length(data, length)
array = []
s = 0
while s < data.length
array << data[s, length]
s += length
end
array
end
end
|
Radanisk/writeexcel
|
test/test_ole.rb
|
<filename>test/test_ole.rb
# -*- coding: utf-8 -*-
require 'helper'
require 'stringio'
class TC_OLE < Test::Unit::TestCase
def setup
@file = StringIO.new
@ole = OLEWriter.new(@file)
end
def test_constructor
assert_kind_of(OLEWriter, @ole)
end
def test_constants
assert_equal(7087104, OLEWriter::MaxSize)
assert_equal(4096, OLEWriter::BlockSize)
assert_equal(512, OLEWriter::BlockDiv)
assert_equal(127, OLEWriter::ListBlocks)
end
def test_calculate_sizes
assert_respond_to(@ole, :calculate_sizes)
assert_nothing_raised{ @ole.calculate_sizes }
assert_equal(0, @ole.big_blocks)
assert_equal(1, @ole.list_blocks)
assert_equal(0, @ole.root_start)
end
def test_set_size_too_big
assert(!@ole.set_size(999999999))
end
def test_book_size_large
assert_nothing_raised{ @ole.set_size(8192) }
assert_equal(8192, @ole.book_size)
end
def test_book_size_small
assert_nothing_raised{ @ole.set_size(2048) }
assert_equal(4096, @ole.book_size)
end
def test_biff_size
assert_nothing_raised{ @ole.set_size(2048) }
assert_equal(2048, @ole.biff_size)
end
def test_size_allowed
assert_nothing_raised{ @ole.set_size }
assert_equal(true, @ole.size_allowed)
end
def test_big_block_size_default
assert_nothing_raised{ @ole.set_size }
assert_nothing_raised{ @ole.calculate_sizes }
assert_equal(8, @ole.big_blocks, "Bad big block size")
end
def test_big_block_size_rounded_up
assert_nothing_raised{ @ole.set_size(4099) }
assert_nothing_raised{ @ole.calculate_sizes }
assert_equal(9, @ole.big_blocks, "Bad big block size")
end
def test_list_block_size
assert_nothing_raised{ @ole.set_size }
assert_nothing_raised{ @ole.calculate_sizes }
assert_equal(1, @ole.list_blocks, "Bad list block size")
end
def test_root_start_size_default
assert_nothing_raised{ @ole.set_size }
assert_nothing_raised{ @ole.calculate_sizes }
assert_equal(8, @ole.big_blocks, "Bad root start size")
end
def test_root_start_size_rounded_up
assert_nothing_raised{ @ole.set_size(4099) }
assert_nothing_raised{ @ole.calculate_sizes }
assert_equal(9, @ole.big_blocks, "Bad root start size")
end
def test_write_header
assert_nothing_raised{ @ole.write_header }
#assert_nothing_raised{ @ole.close }
#assert_equal(512, File.size(@file))
end
def test_write_big_block_depot
assert_nothing_raised{ @ole.write_big_block_depot }
#assert_nothing_raised{ @ole.close }
#assert_equal(8, File.size(@file))
end
def test_write_property_storage_size
assert_nothing_raised{ @ole.write_property_storage }
#assert_nothing_raised{ @ole.close }
#assert_equal(512, File.size(@file))
end
end
|
Radanisk/writeexcel
|
test/test_00_IEEE_double.rb
|
<reponame>Radanisk/writeexcel<filename>test/test_00_IEEE_double.rb
# -*- coding: utf-8 -*-
require 'helper'
class TC_BIFFWriter < Test::Unit::TestCase
def test_IEEE_double
teststr = [1.2345].pack("d")
hexdata = [0x8D, 0x97, 0x6E, 0x12, 0x83, 0xC0, 0xF3, 0x3F]
number = hexdata.pack("C8")
assert(number == teststr || number == teststr.reverse, "Not Little/Big endian. Give up.")
end
end
|
Radanisk/writeexcel
|
examples/tab_colors.rb
|
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
#######################################################################
#
# Example of how to set Excel worksheet tab colours.
#
# reverse('©'), May 2006, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
workbook = WriteExcel.new('tab_colors.xls')
worksheet1 = workbook.add_worksheet
worksheet2 = workbook.add_worksheet
worksheet3 = workbook.add_worksheet
worksheet4 = workbook.add_worksheet
# Worsheet1 will have the default tab colour.
worksheet2.set_tab_color('red')
worksheet3.set_tab_color('green')
worksheet4.set_tab_color(0x35) # Orange
workbook.close
workbook.close
|
Radanisk/writeexcel
|
examples/merge6.rb
|
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
###############################################################################
#
# Example of how to use the Spreadsheet::WriteExcel merge_cells() workbook
# method with Unicode strings.
#
#
# reverse('©'), December 2005, <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('merge6.xls')
worksheet = workbook.add_worksheet
# Increase the cell size of the merged cells to highlight the formatting.
(2..9).each { |i| worksheet.set_row(i, 36) }
worksheet.set_column('B:D', 25)
# Format for the merged cells.
format = workbook.add_format(
:border => 6,
:bold => 1,
:color => 'red',
:size => 20,
:valign => 'vcentre',
:align => 'left',
:indent => 1
)
###############################################################################
#
# Write an Ascii string.
#
worksheet.merge_range('B3:D4', 'ASCII: A simple string', format)
###############################################################################
#
# Write a UTF-16 Unicode string.
#
# A phrase in Cyrillic encoded as UTF-16BE.
utf16_str = [
'005500540046002d00310036003a0020' <<
'042d0442043e002004440440043004370430002004' <<
'3d043000200440044304410441043a043e043c0021'
].pack("H*")
# Note the extra parameter at the end to indicate UTF-16 encoding.
worksheet.merge_range('B6:D7', utf16_str, format, 1)
###############################################################################
#
# Write a UTF-8 Unicode string.
#
smiley = '☺' # chr 0x263a in perl
worksheet.merge_range('B9:D10', "UTF-8: A Unicode smiley #{smiley}", format)
workbook.close
|
Radanisk/writeexcel
|
lib/writeexcel/caller_info.rb
|
<gh_stars>10-100
# -*- coding: utf-8 -*-
module CallerInfo
#
# return stack trace info if defined?($debug).
#
def caller_info
caller(3).collect { |info|
file = File.expand_path(info.sub(/:(\d+)[^\d`]*(`([^']+)')?/, ''))
{ :file => file, :line => $1, :method => $3 }
}.select { |info| info[:method] } # delete if info[:method] == nil
end
end
|
Radanisk/writeexcel
|
examples/hide_sheet.rb
|
<reponame>Radanisk/writeexcel
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
#######################################################################
#
# Example of how to hide a worksheet with WriteExcel.
#
# reverse('©'), April 2005, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
workbook = WriteExcel.new('hidden.xls')
worksheet1 = workbook.add_worksheet
worksheet2 = workbook.add_worksheet
worksheet3 = workbook.add_worksheet
# Sheet2 won't be visible until it is unhidden in Excel.
worksheet2.hide
worksheet1.write(0, 0, 'Sheet2 is hidden')
worksheet2.write(0, 0, 'How did you find me?')
worksheet3.write(0, 0, 'Sheet2 is hidden')
workbook.close
|
Radanisk/writeexcel
|
examples/a_simple.rb
|
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
#
# Example of how to use the WriteExcel module to write text and numbers
# to an Excel binary file.
#
# reverse('©'), March 2001, <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('a_simple.xls');
worksheet = workbook.add_worksheet
# The general syntax is write(row, column, token). Note that row and
# column are zero indexed
#
# Write some text
worksheet.write(0, 0, "Hi Excel!")
# Write some numbers
worksheet.write(2, 0, 3) # Writes 3
worksheet.write(3, 0, 3.00000) # Writes 3
worksheet.write(4, 0, 3.00001) # Writes 3.00001
worksheet.write(5, 0, 3.14159) # TeX revision no.?
# Write some formulas
worksheet.write(7, 0, '=A3 + A6')
worksheet.write(8, 0, '=IF(A5>3,"Yes", "No")')
# Write a hyperlink
worksheet.write(10, 0, 'http://www.perl.com/')
# File save
workbook.close
|
Radanisk/writeexcel
|
examples/images.rb
|
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
#######################################################################
#
# Example of how to insert images into an Excel worksheet using the
# WriteExcel insert_image() method.
#
# reverse('©'), October 2001, <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("images.xls")
worksheet1 = workbook.add_worksheet('Image 1')
worksheet2 = workbook.add_worksheet('Image 2')
worksheet3 = workbook.add_worksheet('Image 3')
worksheet4 = workbook.add_worksheet('Image 4')
# Insert a basic image
worksheet1.write('A10', "Image inserted into worksheet.")
worksheet1.insert_image('A1',
File.join(File.dirname(File.expand_path(__FILE__)), 'republic.png')
)
# Insert an image with an offset
worksheet2.write('A10', "Image inserted with an offset.")
worksheet2.insert_image('A1',
File.join(File.dirname(File.expand_path(__FILE__)), 'republic.png'),
32, 10
)
# Insert a scaled image
worksheet3.write('A10', "Image scaled: width x 2, height x 0.8.")
worksheet3.insert_image('A1',
File.join(File.dirname(File.expand_path(__FILE__)), 'republic.png'),
0, 0, 2, 0.8
)
# Insert an image over varied column and row sizes
# This does not require any additional work
# Set the cols and row sizes
# NOTE: you must do this before you call insert_image()
worksheet4.set_column('A:A', 5)
worksheet4.set_column('B:B', nil, nil, 1) # Hidden
worksheet4.set_column('C:D', 10)
worksheet4.set_row(0, 30)
worksheet4.set_row(3, 5)
worksheet4.write('A10', "Image inserted over scaled rows and columns.")
worksheet4.insert_image('A1',
File.join(File.dirname(File.expand_path(__FILE__)), 'republic.png')
)
workbook.close
|
Radanisk/writeexcel
|
lib/writeexcel/formula.rb
|
<reponame>Radanisk/writeexcel
# -*- coding: utf-8 -*-
###############################################################################
#
# Formula - A class for generating Excel formulas.
#
#
# Used in conjunction with WriteExcel
#
# Copyright 2000-2010, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'strscan'
require 'writeexcel/excelformulaparser'
module Writeexcel
class Formula < ExcelFormulaParser #:nodoc:
require 'writeexcel/helper'
attr_accessor :workbook, :ext_sheets, :ext_refs, :ext_ref_count
def initialize(byte_order)
@byte_order = byte_order
@workbook = ""
@ext_sheets = {}
@ext_refs = {}
@ext_ref_count = 0
@ext_names = {}
initialize_hashes
end
#
# Takes a textual description of a formula and returns a RPN encoded byte
# string.
#
def parse_formula(formula, byte_stream = false)
# Build the parse tree for the formula
tokens = reverse(parse(formula))
# Add a volatile token if the formula contains a volatile function.
# This must be the first token in the list
#
tokens.unshift('_vol') if check_volatile(tokens) != 0
# The return value depends on which Worksheet.pm method is the caller
unless byte_stream
# Parse formula to see if it throws any errors and then
# return raw tokens to Worksheet::store_formula()
#
parse_tokens(tokens)
tokens
else
# Return byte stream to Worksheet::write_formula()
parse_tokens(tokens)
end
end
#
# Convert each token or token pair to its Excel 'ptg' equivalent.
#
def parse_tokens(tokens)
parse_str = ''
last_type = ''
modifier = ''
num_args = 0
_class = 0
_classary = [1]
args = tokens.dup
# A note about the class modifiers used below. In general the class,
# "reference" or "value", of a function is applied to all of its operands.
# However, in certain circumstances the operands can have mixed classes,
# e.g. =VLOOKUP with external references. These will eventually be dealt
# with by the parser. However, as a workaround the class type of a token
# can be changed via the repeat_formula interface. Thus, a _ref2d token can
# be changed by the user to _ref2dA or _ref2dR to change its token class.
#
while (!args.empty?)
token = args.shift
if (token == '_arg')
num_args = args.shift
elsif (token == '_class')
token = args.shift
_class = @functions[token][2]
# If _class is undef then it means that the function isn't valid.
exit "Unknown function #{token}() in formula\n" if _class.nil?
_classary.push(_class)
elsif (token == '_vol')
parse_str += convert_volatile()
elsif (token == 'ptgBool')
token = args.shift
parse_str += convert_bool(token)
elsif (token == '_num')
token = args.shift
parse_str += convert_number(token)
elsif (token == '_str')
token = args.shift
parse_str += convert_string(token)
elsif (token =~ /^_ref2d/)
modifier = token.sub(/_ref2d/, '')
_class = _classary[-1]
_class = 0 if modifier == 'R'
_class = 1 if modifier == 'V'
token = args.shift
parse_str += convert_ref2d(token, _class)
elsif (token =~ /^_ref3d/)
modifier = token.sub(/_ref3d/,'')
_class = _classary[-1]
_class = 0 if modifier == 'R'
_class = 1 if modifier == 'V'
token = args.shift
parse_str += convert_ref3d(token, _class)
elsif (token =~ /^_range2d/)
modifier = token.sub(/_range2d/,'')
_class = _classary[-1]
_class = 0 if modifier == 'R'
_class = 1 if modifier == 'V'
token = args.shift
parse_str += convert_range2d(token, _class)
elsif (token =~ /^_range3d/)
modifier = token.sub(/_range3d/,'')
_class = _classary[-1]
_class = 0 if modifier == 'R'
_class = 1 if modifier == 'V'
token = args.shift
parse_str += convert_range3d(token, _class)
elsif (token =~ /^_name/)
modifier = token.sub(/_name/, '')
_class = _classary[-1]
_class = 0 if modifier == 'R'
_class = 1 if modifier == 'V'
token = args.shift
parse_str += convert_name(token, _class)
elsif (token == '_func')
token = args.shift
parse_str += convert_function(token, num_args.to_i)
_classary.pop
num_args = 0 # Reset after use
elsif @ptg[token]
parse_str += [@ptg[token]].pack("C")
else
# Unrecognised token
return nil
end
end
parse_str
end
def scan(formula)
s = StringScanner.new(formula)
q = []
until s.eos?
# order is important.
if s.scan(/(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?/)
q.push [:NUMBER, s.matched]
elsif s.scan(/"([^"]|"")*"/)
q.push [:STRING, s.matched]
elsif s.scan(/\$?[A-I]?[A-Z]\$?(\d+)?:\$?[A-I]?[A-Z]\$?(\d+)?/)
q.push [:RANGE2D , s.matched]
elsif s.scan(/[^!(,]+!\$?[A-I]?[A-Z]\$?(\d+)?:\$?[A-I]?[A-Z]\$?(\d+)?/)
q.push [:RANGE3D , s.matched]
elsif s.scan(/'[^']+'!\$?[A-I]?[A-Z]\$?(\d+)?:\$?[A-I]?[A-Z]\$?(\d+)?/)
q.push [:RANGE3D , s.matched]
elsif s.scan(/\$?[A-I]?[A-Z]\$?\d+/)
q.push [:REF2D, s.matched]
elsif s.scan(/[^!(,]+!\$?[A-I]?[A-Z]\$?\d+/)
q.push [:REF3D , s.matched]
elsif s.scan(/'[^']+'!\$?[A-I]?[A-Z]\$?\d+/)
q.push [:REF3D , s.matched]
elsif s.scan(/<=/)
q.push [:LE , s.matched]
elsif s.scan(/>=/)
q.push [:GE , s.matched]
elsif s.scan(/<>/)
q.push [:NE , s.matched]
elsif s.scan(/</)
q.push [:LT , s.matched]
elsif s.scan(/>/)
q.push [:GT , s.matched]
elsif s.scan(/[A-Z0-9_.]+\(/)
s.unscan
s.scan(/[A-Z0-9_.]+/)
q.push [:FUNC, s.matched]
elsif s.scan(/TRUE/)
q.push [:TRUE, s.matched]
elsif s.scan(/FALSE/)
q.push [:FALSE, s.matched]
elsif s.scan(/[A-Za-z_]\w+/)
q.push [:NAME , s.matched]
elsif s.scan(/\s+/)
;
elsif s.scan(/./)
q.push [s.matched, s.matched]
end
end
q.push [:EOL, nil]
end
def parse(formula)
@q = scan(formula)
@q.push [false, nil]
@yydebug=true
do_parse
end
def next_token
@q.shift
end
def reverse(expression)
expression.flatten
end
###############################################################################
private
###############################################################################
#
# Check if the formula contains a volatile function, i.e. a function that must
# be recalculated each time a cell is updated. These formulas require a ptgAttr
# with the volatile flag set as the first token in the parsed expression.
#
# Examples of volatile functions: RAND(), NOW(), TODAY()
#
def check_volatile(tokens)
volatile = 0
tokens.each_index do |i|
# If the next token is a function check if it is volatile.
if tokens[i] == '_func' and @functions[tokens[i+1]][3] != 0
volatile = 1
break
end
end
volatile
end
#
# Convert _vol to a ptgAttr tag formatted to indicate that the formula contains
# a volatile function. See _check_volatile()
#
def convert_volatile
# Set bitFattrSemi flag to indicate volatile function, "w" is set to zero.
return [@ptg['ptgAttr'], 0x1, 0x0].pack("CCv")
end
#
# Convert a boolean token to ptgBool
#
def convert_bool(bool)
[@ptg['ptgBool'], bool.to_i].pack("CC")
end
#
# Convert a number token to ptgInt or ptgNum
#
def convert_number(num)
# Integer in the range 0..2**16-1
if ((num =~ /^\d+$/) && (num.to_i <= 65535))
return [@ptg['ptgInt'], num.to_i].pack("Cv")
else # A float
num = [num.to_f].pack("d")
num.reverse! if @byte_order
return [@ptg['ptgNum']].pack("C") + num
end
end
#
# Convert a string to a ptg Str.
#
def convert_string(str)
ruby_19 { str = convert_to_ascii_if_ascii(str) }
encoding = 0
str.sub!(/^"/,'') # Remove leading "
str.sub!(/"$/,'') # Remove trailing "
str.gsub!(/""/,'"') # Substitute Excel's escaped double quote "" for "
# number of characters in str
length = ruby_18 { str.gsub(/[^\WA-Za-z_\d]/, ' ').length } ||
ruby_19 { str.length }
# Handle utf8 strings
if is_utf8?(str)
str = utf8_to_16le(str)
ruby_19 { str.force_encoding('BINARY') }
encoding = 1
end
exit "String in formula has more than 255 chars\n" if length > 255
[@ptg['ptgStr'], length, encoding].pack("CCC") + str
end
#
# Convert an Excel reference such as A1, $B2, C$3 or $D$4 to a ptgRefV.
#
def convert_ref2d(cell, _class)
# Convert the cell reference
row, col = cell_to_packed_rowcol(cell)
# The ptg value depends on the class of the ptg.
if (_class == 0)
ptgref = [@ptg['ptgRef']].pack("C")
elsif (_class == 1)
ptgref = [@ptg['ptgRefV']].pack("C")
elsif (_class == 2)
ptgref = [@ptg['ptgRefA']].pack("C")
else
exit "Unknown function class in formula\n"
end
ptgref + row + col
end
#
# Convert an Excel 3d reference such as "Sheet1!A1" or "Sheet1:Sheet2!A1" to a
# ptgRef3dV.
#
def convert_ref3d(token, _class)
# Split the ref at the ! symbol
ext_ref, cell = token.split('!')
# Convert the external reference part
ext_ref = pack_ext_ref(ext_ref)
# Convert the cell reference part
row, col = cell_to_packed_rowcol(cell)
# The ptg value depends on the class of the ptg.
if (_class == 0)
ptgref = [@ptg['ptgRef3d']].pack("C")
elsif (_class == 1)
ptgref = [@ptg['ptgRef3dV']].pack("C")
elsif (_class == 2)
ptgref = [@ptg['ptgRef3dA']].pack("C")
else
exit "Unknown function class in formula\n"
end
ptgref + ext_ref + row + col
end
#
# Convert an Excel range such as A1:D4 or A:D to a ptgRefV.
#
def convert_range2d(range, _class)
# Split the range into 2 cell refs
cell1, cell2 = range.split(':')
# A range such as A:D is equivalent to A1:D65536, so add rows as required
cell1 += '1' unless cell1 =~ /\d/
cell2 += '65536' unless cell2 =~ /\d/
# Convert the cell references
row1, col1 = cell_to_packed_rowcol(cell1)
row2, col2 = cell_to_packed_rowcol(cell2)
# The ptg value depends on the class of the ptg.
if (_class == 0)
ptgarea = [@ptg['ptgArea']].pack("C")
elsif (_class == 1)
ptgarea = [@ptg['ptgAreaV']].pack("C")
elsif (_class == 2)
ptgarea = [@ptg['ptgAreaA']].pack("C")
else
exit "Unknown function class in formula\n"
end
ptgarea + row1 + row2 + col1 + col2
end
#
# Convert an Excel 3d range such as "Sheet1!A1:D4" or "Sheet1:Sheet2!A1:D4" to
# a ptgArea3dV.
#
def convert_range3d(token, _class)
# Split the ref at the ! symbol
ext_ref, range = token.split('!')
# Convert the external reference part
ext_ref = pack_ext_ref(ext_ref)
# Split the range into 2 cell refs
cell1, cell2 = range.split(':')
# A range such as A:D is equivalent to A1:D65536, so add rows as required
cell1 += '1' unless cell1 =~ /\d/
cell2 += '65536' unless cell2 =~ /\d/
# Convert the cell references
row1, col1 = cell_to_packed_rowcol(cell1)
row2, col2 = cell_to_packed_rowcol(cell2)
# The ptg value depends on the class of the ptg.
if (_class == 0)
ptgarea = [@ptg['ptgArea3d']].pack("C")
elsif (_class == 1)
ptgarea = [@ptg['ptgArea3dV']].pack("C")
elsif (_class == 2)
ptgarea = [@ptg['ptgArea3dA']].pack("C")
else
exit "Unknown function class in formula\n"
end
ptgarea + ext_ref + row1 + row2 + col1+ col2
end
#
# Convert the sheet name part of an external reference, for example "Sheet1" or
# "Sheet1:Sheet2", to a packed structure.
#
def pack_ext_ref(ext_ref)
ext_ref.sub!(/^'/,'') # Remove leading ' if any.
ext_ref.sub!(/'$/,'') # Remove trailing ' if any.
# Check if there is a sheet range eg., Sheet1:Sheet2.
if (ext_ref =~ /:/)
sheet1, sheet2 = ext_ref.split(':')
sheet1 = get_sheet_index(sheet1)
sheet2 = get_sheet_index(sheet2)
# Reverse max and min sheet numbers if necessary
if (sheet1 > sheet2)
sheet1, sheet2 = [sheet2, sheet1]
end
else
# Single sheet name only.
sheet1, sheet2 = [ext_ref, ext_ref]
sheet1 = get_sheet_index(sheet1)
sheet2 = sheet1
end
key = "#{sheet1}:#{sheet2}"
if @ext_refs[key].nil?
index = get_ext_ref_count
@ext_refs[key] = index
@ext_ref_count += 1
else
index = @ext_refs[key]
end
[index].pack("v")
end
#
# Look up the index that corresponds to an external sheet name. The hash of
# sheet names is updated by the add_worksheet() method of the Workbook class.
#
def get_sheet_index(sheet_name)
ruby_19 { sheet_name = convert_to_ascii_if_ascii(sheet_name) }
# Handle utf8 sheetnames
if is_utf8?(sheet_name)
ruby_18 { sheet_name = utf8_to_16be(sheet_name) } ||
ruby_19 { sheet_name = sheet_name.encode('UTF-16BE') }
end
if @ext_sheets[sheet_name].nil?
raise "Unknown sheet name '#{sheet_name}' in formula\n"
else
return @ext_sheets[sheet_name]
end
end
public :get_sheet_index
#
# This semi-public method is used to update the hash of sheet names. It is
# updated by the add_worksheet() method of the Workbook class.
#
def set_ext_sheets(worksheet, index)
# The _ext_sheets hash is used to translate between worksheet names
# and their index
@ext_sheets[worksheet] = index
end
public :set_ext_sheets
#
# This semi-public method is used to get the worksheet references that were
# used in formulas for inclusion in the EXTERNSHEET Workbook record.
#
def get_ext_sheets
@ext_refs
end
public :get_ext_sheets
#
# TODO This semi-public method is used to update the hash of sheet names. It is
# updated by the add_worksheet() method of the Workbook class.
#
def get_ext_ref_count
@ext_ref_count
end
#
# Look up the index that corresponds to an external defined name. The hash of
# defined names is updated by the define_name() method in the Workbook class.
#
def get_name_index(name)
if @ext_names.has_key?(name)
@ext_names[name]
else
raise "Unknown defined name #{name} in formula\n"
end
end
private :get_name_index
#
# This semi-public method is used to update the hash of defined names.
#
def set_ext_name(name, index)
@ext_names[name] = index
end
public :set_ext_name
#
# Convert a function to a ptgFunc or ptgFuncVarV depending on the number of
# args that it takes.
#
def convert_function(token, num_args)
exit "Unknown function #{token}() in formula\n" if @functions[token][0].nil?
args = @functions[token][1]
# Fixed number of args eg. TIME($i,$j,$k).
if (args >= 0)
# Check that the number of args is valid.
if (args != num_args)
raise "Incorrect number of arguments for #{token}() in formula\n"
else
return [@ptg['ptgFuncV'], @functions[token][0]].pack("Cv")
end
end
# Variable number of args eg. SUM(i,j,k, ..).
if (args == -1)
return [@ptg['ptgFuncVarV'], num_args, @functions[token][0]].pack("CCv")
end
end
#
# Convert a symbolic name into a name reference.
#
def convert_name(name, _class)
name_index = get_name_index(name)
# The ptg value depends on the class of the ptg.
if _class == 0
ptgName = @ptg['ptgName']
elsif _class == 1
ptgName = @ptg['ptgNameV']
elsif _class == 2
ptgName = @ptg['ptgNameA']
end
[ptgName, name_index].pack('CV')
end
private :convert_name
#
# Convert an Excel cell reference such as A1 or $B2 or C$3 or $D$4 to a zero
# indexed row and column number. Also returns two boolean values to indicate
# whether the row or column are relative references.
# TODO use function in Utility.pm
#
def cell_to_rowcol(cell)
cell =~ /(\$?)([A-I]?[A-Z])(\$?)(\d+)/
col_rel = $1 == "" ? 1 : 0
row_rel = $3 == "" ? 1 : 0
row = $4.to_i
col = chars_to_col($2.split(//))
# Convert 1-index to zero-index
row -= 1
col -= 1
[row, col, row_rel, col_rel]
end
#
# pack() row and column into the required 3 byte format.
#
def cell_to_packed_rowcol(cell)
row, col, row_rel, col_rel = cell_to_rowcol(cell)
exit "Column #{cell} greater than IV in formula\n" if col >= 256
exit "Row #{cell} greater than 65536 in formula\n" if row >= 65536
# Set the high bits to indicate if row or col are relative.
col |= col_rel << 14
col |= row_rel << 15
row = [row].pack('v')
col = [col].pack('v')
[row, col]
end
def initialize_hashes
# The Excel ptg indices
@ptg = {
'ptgExp' => 0x01,
'ptgTbl' => 0x02,
'ptgAdd' => 0x03,
'ptgSub' => 0x04,
'ptgMul' => 0x05,
'ptgDiv' => 0x06,
'ptgPower' => 0x07,
'ptgConcat' => 0x08,
'ptgLT' => 0x09,
'ptgLE' => 0x0A,
'ptgEQ' => 0x0B,
'ptgGE' => 0x0C,
'ptgGT' => 0x0D,
'ptgNE' => 0x0E,
'ptgIsect' => 0x0F,
'ptgUnion' => 0x10,
'ptgRange' => 0x11,
'ptgUplus' => 0x12,
'ptgUminus' => 0x13,
'ptgPercent' => 0x14,
'ptgParen' => 0x15,
'ptgMissArg' => 0x16,
'ptgStr' => 0x17,
'ptgAttr' => 0x19,
'ptgSheet' => 0x1A,
'ptgEndSheet' => 0x1B,
'ptgErr' => 0x1C,
'ptgBool' => 0x1D,
'ptgInt' => 0x1E,
'ptgNum' => 0x1F,
'ptgArray' => 0x20,
'ptgFunc' => 0x21,
'ptgFuncVar' => 0x22,
'ptgName' => 0x23,
'ptgRef' => 0x24,
'ptgArea' => 0x25,
'ptgMemArea' => 0x26,
'ptgMemErr' => 0x27,
'ptgMemNoMem' => 0x28,
'ptgMemFunc' => 0x29,
'ptgRefErr' => 0x2A,
'ptgAreaErr' => 0x2B,
'ptgRefN' => 0x2C,
'ptgAreaN' => 0x2D,
'ptgMemAreaN' => 0x2E,
'ptgMemNoMemN' => 0x2F,
'ptgNameX' => 0x39,
'ptgRef3d' => 0x3A,
'ptgArea3d' => 0x3B,
'ptgRefErr3d' => 0x3C,
'ptgAreaErr3d' => 0x3D,
'ptgArrayV' => 0x40,
'ptgFuncV' => 0x41,
'ptgFuncVarV' => 0x42,
'ptgNameV' => 0x43,
'ptgRefV' => 0x44,
'ptgAreaV' => 0x45,
'ptgMemAreaV' => 0x46,
'ptgMemErrV' => 0x47,
'ptgMemNoMemV' => 0x48,
'ptgMemFuncV' => 0x49,
'ptgRefErrV' => 0x4A,
'ptgAreaErrV' => 0x4B,
'ptgRefNV' => 0x4C,
'ptgAreaNV' => 0x4D,
'ptgMemAreaNV' => 0x4E,
'ptgFuncCEV' => 0x58,
'ptgNameXV' => 0x59,
'ptgRef3dV' => 0x5A,
'ptgArea3dV' => 0x5B,
'ptgRefErr3dV' => 0x5C,
'ptgArrayA' => 0x60,
'ptgFuncA' => 0x61,
'ptgFuncVarA' => 0x62,
'ptgNameA' => 0x63,
'ptgRefA' => 0x64,
'ptgAreaA' => 0x65,
'ptgMemAreaA' => 0x66,
'ptgMemErrA' => 0x67,
'ptgMemNoMemA' => 0x68,
'ptgMemFuncA' => 0x69,
'ptgRefErrA' => 0x6A,
'ptgAreaErrA' => 0x6B,
'ptgRefNA' => 0x6C,
'ptgAreaNA' => 0x6D,
'ptgMemAreaNA' => 0x6E,
'ptgFuncCEA' => 0x78,
'ptgNameXA' => 0x79,
'ptgRef3dA' => 0x7A,
'ptgArea3dA' => 0x7B,
'ptgRefErr3dA' => 0x7C
}
# Thanks to <NAME> and Gnumeric for the initial arg values.
#
# The following hash was generated by "function_locale.pl" in the distro.
# Refer to function_locale.pl for non-English function names.
#
# The array elements are as follow:
# ptg: The Excel function ptg code.
# args: The number of arguments that the function takes:
# >=0 is a fixed number of arguments.
# -1 is a variable number of arguments.
# class: The reference, value or array class of the function args.
# vol: The function is volatile.
#
@functions = {
# ptg args class vol
'COUNT' => [ 0, -1, 0, 0 ],
'IF' => [ 1, -1, 1, 0 ],
'ISNA' => [ 2, 1, 1, 0 ],
'ISERROR' => [ 3, 1, 1, 0 ],
'SUM' => [ 4, -1, 0, 0 ],
'AVERAGE' => [ 5, -1, 0, 0 ],
'MIN' => [ 6, -1, 0, 0 ],
'MAX' => [ 7, -1, 0, 0 ],
'ROW' => [ 8, -1, 0, 0 ],
'COLUMN' => [ 9, -1, 0, 0 ],
'NA' => [ 10, 0, 0, 0 ],
'NPV' => [ 11, -1, 1, 0 ],
'STDEV' => [ 12, -1, 0, 0 ],
'DOLLAR' => [ 13, -1, 1, 0 ],
'FIXED' => [ 14, -1, 1, 0 ],
'SIN' => [ 15, 1, 1, 0 ],
'COS' => [ 16, 1, 1, 0 ],
'TAN' => [ 17, 1, 1, 0 ],
'ATAN' => [ 18, 1, 1, 0 ],
'PI' => [ 19, 0, 1, 0 ],
'SQRT' => [ 20, 1, 1, 0 ],
'EXP' => [ 21, 1, 1, 0 ],
'LN' => [ 22, 1, 1, 0 ],
'LOG10' => [ 23, 1, 1, 0 ],
'ABS' => [ 24, 1, 1, 0 ],
'INT' => [ 25, 1, 1, 0 ],
'SIGN' => [ 26, 1, 1, 0 ],
'ROUND' => [ 27, 2, 1, 0 ],
'LOOKUP' => [ 28, -1, 0, 0 ],
'INDEX' => [ 29, -1, 0, 1 ],
'REPT' => [ 30, 2, 1, 0 ],
'MID' => [ 31, 3, 1, 0 ],
'LEN' => [ 32, 1, 1, 0 ],
'VALUE' => [ 33, 1, 1, 0 ],
'TRUE' => [ 34, 0, 1, 0 ],
'FALSE' => [ 35, 0, 1, 0 ],
'AND' => [ 36, -1, 1, 0 ],
'OR' => [ 37, -1, 1, 0 ],
'NOT' => [ 38, 1, 1, 0 ],
'MOD' => [ 39, 2, 1, 0 ],
'DCOUNT' => [ 40, 3, 0, 0 ],
'DSUM' => [ 41, 3, 0, 0 ],
'DAVERAGE' => [ 42, 3, 0, 0 ],
'DMIN' => [ 43, 3, 0, 0 ],
'DMAX' => [ 44, 3, 0, 0 ],
'DSTDEV' => [ 45, 3, 0, 0 ],
'VAR' => [ 46, -1, 0, 0 ],
'DVAR' => [ 47, 3, 0, 0 ],
'TEXT' => [ 48, 2, 1, 0 ],
'LINEST' => [ 49, -1, 0, 0 ],
'TREND' => [ 50, -1, 0, 0 ],
'LOGEST' => [ 51, -1, 0, 0 ],
'GROWTH' => [ 52, -1, 0, 0 ],
'PV' => [ 56, -1, 1, 0 ],
'FV' => [ 57, -1, 1, 0 ],
'NPER' => [ 58, -1, 1, 0 ],
'PMT' => [ 59, -1, 1, 0 ],
'RATE' => [ 60, -1, 1, 0 ],
'MIRR' => [ 61, 3, 0, 0 ],
'IRR' => [ 62, -1, 0, 0 ],
'RAND' => [ 63, 0, 1, 1 ],
'MATCH' => [ 64, -1, 0, 0 ],
'DATE' => [ 65, 3, 1, 0 ],
'TIME' => [ 66, 3, 1, 0 ],
'DAY' => [ 67, 1, 1, 0 ],
'MONTH' => [ 68, 1, 1, 0 ],
'YEAR' => [ 69, 1, 1, 0 ],
'WEEKDAY' => [ 70, -1, 1, 0 ],
'HOUR' => [ 71, 1, 1, 0 ],
'MINUTE' => [ 72, 1, 1, 0 ],
'SECOND' => [ 73, 1, 1, 0 ],
'NOW' => [ 74, 0, 1, 1 ],
'AREAS' => [ 75, 1, 0, 1 ],
'ROWS' => [ 76, 1, 0, 1 ],
'COLUMNS' => [ 77, 1, 0, 1 ],
'OFFSET' => [ 78, -1, 0, 1 ],
'SEARCH' => [ 82, -1, 1, 0 ],
'TRANSPOSE' => [ 83, 1, 1, 0 ],
'TYPE' => [ 86, 1, 1, 0 ],
'ATAN2' => [ 97, 2, 1, 0 ],
'ASIN' => [ 98, 1, 1, 0 ],
'ACOS' => [ 99, 1, 1, 0 ],
'CHOOSE' => [ 100, -1, 1, 0 ],
'HLOOKUP' => [ 101, -1, 0, 0 ],
'VLOOKUP' => [ 102, -1, 0, 0 ],
'ISREF' => [ 105, 1, 0, 0 ],
'LOG' => [ 109, -1, 1, 0 ],
'CHAR' => [ 111, 1, 1, 0 ],
'LOWER' => [ 112, 1, 1, 0 ],
'UPPER' => [ 113, 1, 1, 0 ],
'PROPER' => [ 114, 1, 1, 0 ],
'LEFT' => [ 115, -1, 1, 0 ],
'RIGHT' => [ 116, -1, 1, 0 ],
'EXACT' => [ 117, 2, 1, 0 ],
'TRIM' => [ 118, 1, 1, 0 ],
'REPLACE' => [ 119, 4, 1, 0 ],
'SUBSTITUTE' => [ 120, -1, 1, 0 ],
'CODE' => [ 121, 1, 1, 0 ],
'FIND' => [ 124, -1, 1, 0 ],
'CELL' => [ 125, -1, 0, 1 ],
'ISERR' => [ 126, 1, 1, 0 ],
'ISTEXT' => [ 127, 1, 1, 0 ],
'ISNUMBER' => [ 128, 1, 1, 0 ],
'ISBLANK' => [ 129, 1, 1, 0 ],
'T' => [ 130, 1, 0, 0 ],
'N' => [ 131, 1, 0, 0 ],
'DATEVALUE' => [ 140, 1, 1, 0 ],
'TIMEVALUE' => [ 141, 1, 1, 0 ],
'SLN' => [ 142, 3, 1, 0 ],
'SYD' => [ 143, 4, 1, 0 ],
'DDB' => [ 144, -1, 1, 0 ],
'INDIRECT' => [ 148, -1, 1, 1 ],
'CALL' => [ 150, -1, 1, 0 ],
'CLEAN' => [ 162, 1, 1, 0 ],
'MDETERM' => [ 163, 1, 2, 0 ],
'MINVERSE' => [ 164, 1, 2, 0 ],
'MMULT' => [ 165, 2, 2, 0 ],
'IPMT' => [ 167, -1, 1, 0 ],
'PPMT' => [ 168, -1, 1, 0 ],
'COUNTA' => [ 169, -1, 0, 0 ],
'PRODUCT' => [ 183, -1, 0, 0 ],
'FACT' => [ 184, 1, 1, 0 ],
'DPRODUCT' => [ 189, 3, 0, 0 ],
'ISNONTEXT' => [ 190, 1, 1, 0 ],
'STDEVP' => [ 193, -1, 0, 0 ],
'VARP' => [ 194, -1, 0, 0 ],
'DSTDEVP' => [ 195, 3, 0, 0 ],
'DVARP' => [ 196, 3, 0, 0 ],
'TRUNC' => [ 197, -1, 1, 0 ],
'ISLOGICAL' => [ 198, 1, 1, 0 ],
'DCOUNTA' => [ 199, 3, 0, 0 ],
'ROUNDUP' => [ 212, 2, 1, 0 ],
'ROUNDDOWN' => [ 213, 2, 1, 0 ],
'RANK' => [ 216, -1, 0, 0 ],
'ADDRESS' => [ 219, -1, 1, 0 ],
'DAYS360' => [ 220, -1, 1, 0 ],
'TODAY' => [ 221, 0, 1, 1 ],
'VDB' => [ 222, -1, 1, 0 ],
'MEDIAN' => [ 227, -1, 0, 0 ],
'SUMPRODUCT' => [ 228, -1, 2, 0 ],
'SINH' => [ 229, 1, 1, 0 ],
'COSH' => [ 230, 1, 1, 0 ],
'TANH' => [ 231, 1, 1, 0 ],
'ASINH' => [ 232, 1, 1, 0 ],
'ACOSH' => [ 233, 1, 1, 0 ],
'ATANH' => [ 234, 1, 1, 0 ],
'DGET' => [ 235, 3, 0, 0 ],
'INFO' => [ 244, 1, 1, 1 ],
'DB' => [ 247, -1, 1, 0 ],
'FREQUENCY' => [ 252, 2, 0, 0 ],
'ERROR.TYPE' => [ 261, 1, 1, 0 ],
'REGISTER.ID' => [ 267, -1, 1, 0 ],
'AVEDEV' => [ 269, -1, 0, 0 ],
'BETADIST' => [ 270, -1, 1, 0 ],
'GAMMALN' => [ 271, 1, 1, 0 ],
'BETAINV' => [ 272, -1, 1, 0 ],
'BINOMDIST' => [ 273, 4, 1, 0 ],
'CHIDIST' => [ 274, 2, 1, 0 ],
'CHIINV' => [ 275, 2, 1, 0 ],
'COMBIN' => [ 276, 2, 1, 0 ],
'CONFIDENCE' => [ 277, 3, 1, 0 ],
'CRITBINOM' => [ 278, 3, 1, 0 ],
'EVEN' => [ 279, 1, 1, 0 ],
'EXPONDIST' => [ 280, 3, 1, 0 ],
'FDIST' => [ 281, 3, 1, 0 ],
'FINV' => [ 282, 3, 1, 0 ],
'FISHER' => [ 283, 1, 1, 0 ],
'FISHERINV' => [ 284, 1, 1, 0 ],
'FLOOR' => [ 285, 2, 1, 0 ],
'GAMMADIST' => [ 286, 4, 1, 0 ],
'GAMMAINV' => [ 287, 3, 1, 0 ],
'CEILING' => [ 288, 2, 1, 0 ],
'HYPGEOMDIST' => [ 289, 4, 1, 0 ],
'LOGNORMDIST' => [ 290, 3, 1, 0 ],
'LOGINV' => [ 291, 3, 1, 0 ],
'NEGBINOMDIST' => [ 292, 3, 1, 0 ],
'NORMDIST' => [ 293, 4, 1, 0 ],
'NORMSDIST' => [ 294, 1, 1, 0 ],
'NORMINV' => [ 295, 3, 1, 0 ],
'NORMSINV' => [ 296, 1, 1, 0 ],
'STANDARDIZE' => [ 297, 3, 1, 0 ],
'ODD' => [ 298, 1, 1, 0 ],
'PERMUT' => [ 299, 2, 1, 0 ],
'POISSON' => [ 300, 3, 1, 0 ],
'TDIST' => [ 301, 3, 1, 0 ],
'WEIBULL' => [ 302, 4, 1, 0 ],
'SUMXMY2' => [ 303, 2, 2, 0 ],
'SUMX2MY2' => [ 304, 2, 2, 0 ],
'SUMX2PY2' => [ 305, 2, 2, 0 ],
'CHITEST' => [ 306, 2, 2, 0 ],
'CORREL' => [ 307, 2, 2, 0 ],
'COVAR' => [ 308, 2, 2, 0 ],
'FORECAST' => [ 309, 3, 2, 0 ],
'FTEST' => [ 310, 2, 2, 0 ],
'INTERCEPT' => [ 311, 2, 2, 0 ],
'PEARSON' => [ 312, 2, 2, 0 ],
'RSQ' => [ 313, 2, 2, 0 ],
'STEYX' => [ 314, 2, 2, 0 ],
'SLOPE' => [ 315, 2, 2, 0 ],
'TTEST' => [ 316, 4, 2, 0 ],
'PROB' => [ 317, -1, 2, 0 ],
'DEVSQ' => [ 318, -1, 0, 0 ],
'GEOMEAN' => [ 319, -1, 0, 0 ],
'HARMEAN' => [ 320, -1, 0, 0 ],
'SUMSQ' => [ 321, -1, 0, 0 ],
'KURT' => [ 322, -1, 0, 0 ],
'SKEW' => [ 323, -1, 0, 0 ],
'ZTEST' => [ 324, -1, 0, 0 ],
'LARGE' => [ 325, 2, 0, 0 ],
'SMALL' => [ 326, 2, 0, 0 ],
'QUARTILE' => [ 327, 2, 0, 0 ],
'PERCENTILE' => [ 328, 2, 0, 0 ],
'PERCENTRANK' => [ 329, -1, 0, 0 ],
'MODE' => [ 330, -1, 2, 0 ],
'TRIMMEAN' => [ 331, 2, 0, 0 ],
'TINV' => [ 332, 2, 1, 0 ],
'CONCATENATE' => [ 336, -1, 1, 0 ],
'POWER' => [ 337, 2, 1, 0 ],
'RADIANS' => [ 342, 1, 1, 0 ],
'DEGREES' => [ 343, 1, 1, 0 ],
'SUBTOTAL' => [ 344, -1, 0, 0 ],
'SUMIF' => [ 345, -1, 0, 0 ],
'COUNTIF' => [ 346, 2, 0, 0 ],
'COUNTBLANK' => [ 347, 1, 0, 0 ],
'ROMAN' => [ 354, -1, 1, 0 ]
}
end
def inspect
to_s
end
end
if $0 ==__FILE__
parser = Formula.new
puts
puts 'type "Q" to quit.'
puts
while true
puts
print '? '
str = gets.chop!
break if /q/i =~ str
begin
e = parser.parse(str)
p parser.reverse(e)
rescue ParseError
puts $!
end
end
end # class Formula
end # module Writeexcel
|
Radanisk/writeexcel
|
lib/writeexcel/format.rb
|
<filename>lib/writeexcel/format.rb
# -*- coding: utf-8 -*-
##############################################################################
#
# Format - A class for defining Excel formatting.
#
#
# Used in conjunction with WriteExcel
#
# Copyright 2000-2010, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
#
# Format - A class for defining Excel formatting.
#
# See CELL FORMATTING, FORMAT METHODS, COLOURS IN EXCEL in WriteExcel's rdoc.
#
require 'writeexcel/compatibility'
require 'writeexcel/colors'
module Writeexcel
class Format < Colors
require 'writeexcel/helper'
#
# Constructor
#
# xf_index :
# properties : Hash of property => value
#
def initialize(xf_index = 0, properties = {}) # :nodoc:
@xf_index = xf_index
@type = 0
@font_index = 0
@font = 'Arial'
@size = 10
@bold = 0x0190
@italic = 0
@color = 0x7FFF
@underline = 0
@font_strikeout = 0
@font_outline = 0
@font_shadow = 0
@font_script = 0
@font_family = 0
@font_charset = 0
@font_encoding = 0
@num_format = 0
@num_format_enc = 0
@hidden = 0
@locked = 1
@text_h_align = 0
@text_wrap = 0
@text_v_align = 2
@text_justlast = 0
@rotation = 0
@fg_color = 0x40
@bg_color = 0x41
@pattern = 0
@bottom = 0
@top = 0
@left = 0
@right = 0
@bottom_color = 0x40
@top_color = 0x40
@left_color = 0x40
@right_color = 0x40
@indent = 0
@shrink = 0
@merge_range = 0
@reading_order = 0
@diag_type = 0
@diag_color = 0x40
@diag_border = 0
@font_only = 0
# Temp code to prevent merged formats in non-merged cells.
@used_merge = 0
set_format_properties(properties) unless properties.empty?
end
#
# :call-seq:
# copy(format)
#
# Copy the attributes of another Format object.
#
# 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
#
# 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.
#
def copy(other)
# copy properties except xf, merge_range, used_merge
# Copy properties
@type = other.type
@font_index = other.font_index
@font = other.font
@size = other.size
@bold = other.bold
@italic = other.italic
@color = other.color
@underline = other.underline
@font_strikeout = other.font_strikeout
@font_outline = other.font_outline
@font_shadow = other.font_shadow
@font_script = other.font_script
@font_family = other.font_family
@font_charset = other.font_charset
@font_encoding = other.font_encoding
@num_format = other.num_format
@num_format_enc = other.num_format_enc
@hidden = other.hidden
@locked = other.locked
@text_h_align = other.text_h_align
@text_wrap = other.text_wrap
@text_v_align = other.text_v_align
@text_justlast = other.text_justlast
@rotation = other.rotation
@fg_color = other.fg_color
@bg_color = other.bg_color
@pattern = other.pattern
@bottom = other.bottom
@top = other.top
@left = other.left
@right = other.right
@bottom_color = other.bottom_color
@top_color = other.top_color
@left_color = other.left_color
@right_color = other.right_color
@indent = other.indent
@shrink = other.shrink
@reading_order = other.reading_order
@diag_type = other.diag_type
@diag_color = other.diag_color
@diag_border = other.diag_border
@font_only = other.font_only
end
#
# Generate an Excel BIFF XF record.
#
def get_xf # :nodoc:
# Local Variable
# record; # Record identifier
# length; # Number of bytes to follow
#
# ifnt; # Index to FONT record
# ifmt; # Index to FORMAT record
# style; # Style and other options
# align; # Alignment
# indent; #
# icv; # fg and bg pattern colors
# border1; # Border line options
# border2; # Border line options
# border3; # Border line options
# Set the type of the XF record and some of the attributes.
if @type == 0xFFF5 then
style = 0xFFF5
else
style = @locked
style |= @hidden << 1
end
# Flags to indicate if attributes have been set.
atr_num = (@num_format != 0) ? 1 : 0
atr_fnt = (@font_index != 0) ? 1 : 0
atr_alc = (@text_h_align != 0 ||
@text_v_align != 2 ||
@shrink != 0 ||
@merge_range != 0 ||
@text_wrap != 0 ||
@indent != 0) ? 1 : 0
atr_bdr = (@bottom != 0 ||
@top != 0 ||
@left != 0 ||
@right != 0 ||
@diag_type != 0) ? 1 : 0
atr_pat = (@fg_color != 0x40 ||
@bg_color != 0x41 ||
@pattern != 0x00) ? 1 : 0
atr_prot = (@hidden != 0 ||
@locked != 1) ? 1 : 0
# Set attribute changed flags for the style formats.
if @xf_index != 0 and @type == 0xFFF5
if @xf_index >= 16
atr_num = 0
atr_fnt = 1
else
atr_num = 1
atr_fnt = 0
end
atr_alc = 1
atr_bdr = 1
atr_pat = 1
atr_prot = 1
end
# Set a default diagonal border style if none was specified.
@diag_border = 1 if (@diag_border ==0 and @diag_type != 0)
# Reset the default colours for the non-font properties
@fg_color = 0x40 if @fg_color == 0x7FFF
@bg_color = 0x41 if @bg_color == 0x7FFF
@bottom_color = 0x40 if @bottom_color == 0x7FFF
@top_color = 0x40 if @top_color == 0x7FFF
@left_color = 0x40 if @left_color == 0x7FFF
@right_color = 0x40 if @right_color == 0x7FFF
@diag_color = 0x40 if @diag_color == 0x7FFF
# Zero the default border colour if the border has not been set.
@bottom_color = 0 if @bottom == 0
@top_color = 0 if @top == 0
@right_color = 0 if @right == 0
@left_color = 0 if @left == 0
@diag_color = 0 if @diag_type == 0
# The following 2 logical statements take care of special cases in relation
# to cell colours and patterns:
# 1. For a solid fill (_pattern == 1) Excel reverses the role of foreground
# and background colours.
# 2. If the user specifies a foreground or background colour without a
# pattern they probably wanted a solid fill, so we fill in the defaults.
#
if (@pattern <= 0x01 && @bg_color != 0x41 && @fg_color == 0x40)
@fg_color = @bg_color
@bg_color = 0x40
@pattern = 1
end
if (@pattern <= 0x01 && @bg_color == 0x41 && @fg_color != 0x40)
@bg_color = 0x40
@pattern = 1
end
# Set default alignment if indent is set.
@text_h_align = 1 if @indent != 0 and @text_h_align == 0
record = 0x00E0
length = 0x0014
ifnt = @font_index
ifmt = @num_format
align = @text_h_align
align |= @text_wrap << 3
align |= @text_v_align << 4
align |= @text_justlast << 7
align |= @rotation << 8
indent = @indent
indent |= @shrink << 4
indent |= @merge_range << 5
indent |= @reading_order << 6
indent |= atr_num << 10
indent |= atr_fnt << 11
indent |= atr_alc << 12
indent |= atr_bdr << 13
indent |= atr_pat << 14
indent |= atr_prot << 15
border1 = @left
border1 |= @right << 4
border1 |= @top << 8
border1 |= @bottom << 12
border2 = @left_color
border2 |= @right_color << 7
border2 |= @diag_type << 14
border3 = @top_color
border3 |= @bottom_color << 7
border3 |= @diag_color << 14
border3 |= @diag_border << 21
border3 |= @pattern << 26
icv = @fg_color
icv |= @bg_color << 7
header = [record, length].pack("vv")
data = [ifnt, ifmt, style, align, indent,
border1, border2, border3, icv].pack("vvvvvvvVv")
header + data
end
#
# Generate an Excel BIFF FONT record.
#
def get_font # :nodoc:
# my $record; # Record identifier
# my $length; # Record length
# my $dyHeight; # Height of font (1/20 of a point)
# my $grbit; # Font attributes
# my $icv; # Index to color palette
# my $bls; # Bold style
# my $sss; # Superscript/subscript
# my $uls; # Underline
# my $bFamily; # Font family
# my $bCharSet; # Character set
# my $reserved; # Reserved
# my $cch; # Length of font name
# my $rgch; # Font name
# my $encoding; # Font name character encoding
dyHeight = @size * 20
icv = @color
bls = @bold
sss = @font_script
uls = @underline
bFamily = @font_family
bCharSet = @font_charset
rgch = @font
encoding = @font_encoding
ruby_19 { rgch = convert_to_ascii_if_ascii(rgch) }
# Handle utf8 strings
if is_utf8?(rgch)
rgch = utf8_to_16be(rgch)
encoding = 1
end
cch = rgch.bytesize
#
# Handle Unicode font names.
if (encoding == 1)
raise "Uneven number of bytes in Unicode font name" if cch % 2 != 0
cch /= 2 if encoding !=0
rgch = utf16be_to_16le(rgch)
end
record = 0x31
length = 0x10 + rgch.bytesize
reserved = 0x00
grbit = 0x00
grbit |= 0x02 if @italic != 0
grbit |= 0x08 if @font_strikeout != 0
grbit |= 0x10 if @font_outline != 0
grbit |= 0x20 if @font_shadow != 0
header = [record, length].pack("vv")
data = [dyHeight, grbit, icv, bls,
sss, uls, bFamily,
bCharSet, reserved, cch, encoding].pack('vvvvvCCCCCC')
header + data + rgch
end
#
# Returns a unique hash key for a font. Used by Workbook->_store_all_fonts()
#
def get_font_key # :nodoc:
# The following elements are arranged to increase the probability of
# generating a unique key. Elements that hold a large range of numbers
# e.g. _color are placed between two binary elements such as _italic
key = "#{@font}#{@size}#{@font_script}#{@underline}#{@font_strikeout}#{@bold}#{@font_outline}"
key += "#{@font_family}#{@font_charset}#{@font_shadow}#{@color}#{@italic}#{@font_encoding}"
key.gsub(' ', '_') # Convert the key to a single word
end
#
# Returns the used by Worksheet->_XF()
#
def xf_index # :nodoc:
@xf_index
end
def used_merge # :nodoc:
@used_merge
end
def used_merge=(val) # :nodoc:
@used_merge = val
end
def type # :nodoc:
@type
end
def font_index # :nodoc:
@font_index
end
def font_index=(val) # :nodoc:
@font_index = val
end
def font # :nodoc:
@font
end
def size # :nodoc:
@size
end
def bold # :nodoc:
@bold
end
def italic # :nodoc:
@italic
end
def color # :nodoc:
@color
end
def underline # :nodoc:
@underline
end
def font_strikeout # :nodoc:
@font_strikeout
end
def font_outline # :nodoc:
@font_outline
end
def font_shadow # :nodoc:
@font_shadow
end
def font_script # :nodoc:
@font_script
end
def font_family # :nodoc:
@font_family
end
def font_charset # :nodoc:
@font_charset
end
def font_encoding # :nodoc:
@font_encoding
end
def num_format # :nodoc:
@num_format
end
def num_format=(val) # :nodoc:
@num_format = val
end
def num_format_enc # :nodoc:
@num_format_enc
end
def hidden # :nodoc:
@hidden
end
def locked # :nodoc:
@locked
end
def text_h_align # :nodoc:
@text_h_align
end
def text_wrap # :nodoc:
@text_wrap
end
def text_v_align # :nodoc:
@text_v_align
end
def text_justlast # :nodoc:
@text_justlast
end
def rotation # :nodoc:
@rotation
end
def fg_color # :nodoc:
@fg_color
end
def bg_color # :nodoc:
@bg_color
end
def pattern # :nodoc:
@pattern
end
def bottom # :nodoc:
@bottom
end
def top # :nodoc:
@top
end
def left # :nodoc:
@left
end
def right # :nodoc:
@right
end
def bottom_color # :nodoc:
@bottom_color
end
def top_color # :nodoc:
@top_color
end
def left_color # :nodoc:
@left_color
end
def right_color # :nodoc:
@right_color
end
def indent # :nodoc:
@indent
end
def shrink # :nodoc:
@shrink
end
def reading_order # :nodoc:
@reading_order
end
def diag_type # :nodoc:
@diag_type
end
def diag_color # :nodoc:
@diag_color
end
def diag_border # :nodoc:
@diag_border
end
def font_only # :nodoc:
@font_only
end
#
# used from Worksheet.rb
#
# this is cut & copy of get_color().
#
def self._get_color(color) # :nodoc:
Colors.new.get_color(color)
end
#
# Set the XF object type as 0 = cell XF or 0xFFF5 = style XF.
#
def set_type(type = nil) # :nodoc:
if !type.nil? and type == 0
@type = 0x0000
else
@type = 0xFFF5
end
end
#
# 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.
#
# format = workbook.add_format
# format.set_size(30)
#
def set_size(size = 1)
if size.respond_to?(:to_int) && size.respond_to?(:+) && size >= 1 # avoid Symbol
@size = size.to_int
end
end
#
# Set the font colour.
#
# 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'
#
# 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.
#
def set_color(color = 0x7FFF)
@color = get_color(color)
end
#
# Set the italic property of the font:
#
# Default state: Italic is off
# Default action: Turn italic on
# Valid args: 0, 1
#
# format.set_italic # Turn italic on
#
def set_italic(arg = 1)
begin
if arg == 1 then @italic = 1 # italic on
elsif arg == 0 then @italic = 0 # italic off
else
raise ArgumentError,
"\n\n set_italic(#{arg.inspect})\n arg must be 0, 1, or none. ( 0:OFF , 1 and none:ON )\n"
end
end
end
#
# Set the bold property of the font:
#
# Default state: bold is off
# Default action: Turn bold on
# Valid args: 0, 1 [1]
#
# 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.
#
def set_bold(weight = nil)
if weight.nil?
weight = 0x2BC
elsif !weight.respond_to?(:to_int) || !weight.respond_to?(:+) # avoid Symbol
weight = 0x190
elsif weight == 1 # Bold text
weight = 0x2BC
elsif weight == 0 # Normal text
weight = 0x190
elsif weight < 0x064 || 0x3E8 < weight # Out bound
weight = 0x190
else
weight = weight.to_i
end
@bold = weight
end
#
# Set the underline property of the font.
#
# 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
#
# format.set_underline(); # Single underline
#
def set_underline(arg = 1)
begin
case arg
when 0 then @underline = 0 # off
when 1 then @underline = 1 # Single
when 2 then @underline = 2 # Double
when 33 then @underline = 33 # Single accounting
when 34 then @underline = 34 # Double accounting
else
raise ArgumentError,
"\n\n set_underline(#{arg.inspect})\n arg must be 0, 1, or none, 2, 33, 34.\n"
" ( 0:OFF, 1 and none:Single, 2:Double, 33:Single accounting, 34:Double accounting )\n"
end
end
end
#
# Set the strikeout property of the font.
#
# Default state: Strikeout is off
# Default action: Turn strikeout on
# Valid args: 0, 1
#
def set_font_strikeout(arg = 1)
begin
if arg == 0 then @font_strikeout = 0
elsif arg == 1 then @font_strikeout = 1
else
raise ArgumentError,
"\n\n set_font_strikeout(#{arg.inspect})\n arg must be 0, 1, or none.\n"
" ( 0:OFF, 1 and none:Strikeout )\n"
end
end
end
#
# Set the superscript/subscript property of the font.
# This format is currently not very useful.
#
# Default state: Super/Subscript is off
# Default action: Turn Superscript on
# Valid args: 0 = Normal
# 1 = Superscript
# 2 = Subscript
#
def set_font_script(arg = 1)
begin
if arg == 0 then @font_script = 0
elsif arg == 1 then @font_script = 1
elsif arg == 2 then @font_script = 2
else
raise ArgumentError,
"\n\n set_font_script(#{arg.inspect})\n arg must be 0, 1, or none. or 2\n"
" ( 0:OFF, 1 and none:Superscript, 2:Subscript )\n"
end
end
end
#
# Macintosh only.
#
# Default state: Outline is off
# Default action: Turn outline on
# Valid args: 0, 1
#
def set_font_outline(arg = 1)
begin
if arg == 0 then @font_outline = 0
elsif arg == 1 then @font_outline = 1
else
raise ArgumentError,
"\n\n set_font_outline(#{arg.inspect})\n arg must be 0, 1, or none.\n"
" ( 0:OFF, 1 and none:outline on )\n"
end
end
end
#
# Macintosh only.
#
# Default state: Shadow is off
# Default action: Turn shadow on
# Valid args: 0, 1
#
def set_font_shadow(arg = 1)
begin
if arg == 0 then @font_shadow = 0
elsif arg == 1 then @font_shadow = 1
else
raise ArgumentError,
"\n\n set_font_shadow(#{arg.inspect})\n arg must be 0, 1, or none.\n"
" ( 0:OFF, 1 and none:shadow on )\n"
end
end
end
#
# prevent modification of a cells contents.
#
# 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.
#
def set_locked(arg = 1)
begin
if arg == 0 then @locked = 0
elsif arg == 1 then @locked = 1
else
raise ArgumentError,
"\n\n set_locked(#{arg.inspect})\n arg must be 0, 1, or none.\n"
" ( 0:OFF, 1 and none:Lock On )\n"
end
end
end
#
# hide a formula while still displaying its result.
#
# 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.
#
# 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 .
#
def set_hidden(arg = 1)
begin
if arg == 0 then @hidden = 0
elsif arg == 1 then @hidden = 1
else
raise ArgumentError,
"\n\n set_hidden(#{arg.inspect})\n arg must be 0, 1, or none.\n"
" ( 0:OFF, 1 and none:hiding On )\n"
end
end
end
#
# Set cell alignment.
#
# 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:
#
# 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.
#
# For further examples see the 'Alignment' worksheet created by formats.rb.
#
def set_align(align = 'left')
case align.to_s.downcase
when 'left' then set_text_h_align(1)
when 'centre', 'center' then set_text_h_align(2)
when 'right' then set_text_h_align(3)
when 'fill' then set_text_h_align(4)
when 'justify' then set_text_h_align(5)
when 'center_across', 'centre_across' then set_text_h_align(6)
when 'merge' then set_text_h_align(6) # S:WE name
when 'distributed' then set_text_h_align(7)
when 'equal_space' then set_text_h_align(7) # ParseExcel
when 'top' then set_text_v_align(0)
when 'vcentre' then set_text_v_align(1)
when 'vcenter' then set_text_v_align(1)
when 'bottom' then set_text_v_align(2)
when 'vjustify' then set_text_v_align(3)
when 'vdistributed' then set_text_v_align(4)
when 'vequal_space' then set_text_v_align(4) # ParseExcel
else nil
end
end
#
# Set vertical cell alignment. This is required by the set_format_properties()
# method to differentiate between the vertical and horizontal properties.
#
def set_valign(alignment) # :nodoc:
set_align(alignment)
end
#
# Implements the Excel5 style "merge".
#
# 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)
#
# See also the merge1.pl to merge6.rb programs in the examples directory and
# the merge_range() method.
#
def set_center_across(arg = 1)
set_text_h_align(6)
end
#
# This was the way to implement a merge in Excel5. However it should have been
# called "center_across" and not "merge".
# This is now deprecated. Use set_center_across() or better merge_range().
#
#
def set_merge(val=true) # :nodoc:
set_text_h_align(6)
end
#
# 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)
#
def set_text_wrap(arg = 1)
begin
if arg == 0 then @text_wrap = 0
elsif arg == 1 then @text_wrap = 1
else
raise ArgumentError,
"\n\n set_text_wrap(#{arg.inspect})\n arg must be 0, 1, or none.\n"
" ( 0:OFF, 1 and none:text wrap On )\n"
end
end
end
#
# Set cells borders to the same style
#
# 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 ===========
#
# Examples of the available border styles are shown in the 'Borders' worksheet
# created by formats.rb.
#
def set_border(style)
set_bottom(style)
set_top(style)
set_left(style)
set_right(style)
end
#
# set bottom border of the cell.
# see set_border() about style.
#
def set_bottom(style)
@bottom = style
end
#
# set top border of the cell.
# see set_border() about style.
#
def set_top(style)
@top = style
end
#
# set left border of the cell.
# see set_border() about style.
#
def set_left(style)
@left = style
end
#
# set right border of the cell.
# see set_border() about style.
#
def set_right(style)
@right = style
end
#
# Set cells border to the same 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. Examples of the border styles and colours are shown in the
# 'Borders' worksheet created by formats.rb.
#
def set_border_color(color)
set_bottom_color(color)
set_top_color(color)
set_left_color(color)
set_right_color(color)
end
#
# set bottom border color of the cell.
# see set_border_color() about color.
#
def set_bottom_color(color)
@bottom_color = get_color(color)
end
#
# set top border color of the cell.
# see set_border_color() about color.
#
def set_top_color(color)
@top_color = get_color(color)
end
#
# set left border color of the cell.
# see set_border_color() about color.
#
def set_left_color(color)
@left_color = get_color(color)
end
#
# set right border color of the cell.
# see set_border_color() about color.
#
def set_right_color(color)
@right_color = get_color(color)
end
#
# Set the rotation angle of the text. An alignment property.
#
# 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.
#
def set_rotation(rotation)
# The arg type can be a double but the Excel dialog only allows integers.
rotation = rotation.to_i
# if (rotation == 270)
# rotation = 255
# elsif (rotation >= -90 or rotation <= 90)
# rotation = -rotation +90 if rotation < 0;
# else
# # carp "Rotation $rotation outside range: -90 <= angle <= 90";
# rotation = 0;
# end
#
if rotation == 270
rotation = 255
elsif rotation >= -90 && rotation <= 90
rotation = -rotation + 90 if rotation < 0
else
rotation = 0
end
@rotation = rotation
end
#
# :call-seq:
# set_format_properties( :bold => 1 [, :color => 'red'..] )
# set_format_properties( font [, shade, ..])
# set_format_properties( :bold => 1, font, ...)
# *) font = { :color => 'red', :bold => 1 }
# shade = { :bg_color => 'green', :pattern => 1 }
#
# Convert hashes of properties to method calls.
#
# The properties of an existing Format object can be also be set by means
# of set_format_properties():
#
# format = workbook.add_format
# format.set_format_properties(:bold => 1, :color => 'red');
#
# However, this method is here mainly for legacy reasons. It is preferable
# to set the properties in the format constructor:
#
# format = workbook.add_format(:bold => 1, :color => 'red');
#
def set_format_properties(*properties) # :nodoc:
return if properties.empty?
properties.each do |property|
property.each do |key, value|
# Strip leading "-" from Tk style properties e.g. "-color" => 'red'.
key = key.sub(/^-/, '') if key.respond_to?(:to_str)
# Create a sub to set the property.
if value.respond_to?(:to_str) || !value.respond_to?(:+)
s = "set_#{key}('#{value}')"
else
s = "set_#{key}(#{value})"
end
eval s
end
end
end
#
# Default state: Font is Arial
# Default action: None
# Valid args: Any valid font name
#
# Specify the font used:
#
# format.set_font('Times New Roman');
#
# Excel can only display fonts that are installed on the system that it is
# running on. Therefore it is best to use the fonts that come as standard
# such as 'Arial', 'Times New Roman' and 'Courier New'. See also the Fonts
# worksheet created by formats.rb
#
def set_font(fontname)
@font = fontname
end
#
# This method is used to define the numerical format of a number in Excel.
#
# Default state: General format
# Default action: Format index 1
# Valid args: See the following table
#
# 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.
#
# The numerical format of a cell can be specified by using a format string
# or an index to one of Excel's built-in formats:
#
# format1 = workbook.add_format
# format2 = workbook.add_format
# format1.set_num_format('d mmm yyyy') # Format string
# format2.set_num_format(0x0f) # Format index
#
# worksheet.write(0, 0, 36892.521, format1) # 1 Jan 2001
# worksheet.write(0, 0, 36892.521, format2) # 1-Jan-01
#
# Using format strings you can define very sophisticated formatting of
# numbers.
#
# format01.set_num_format('0.000')
# worksheet.write(0, 0, 3.1415926, format01) # 3.142
#
# format02.set_num_format('#,##0')
# worksheet.write(1, 0, 1234.56, format02) # 1,235
#
# format03.set_num_format('#,##0.00')
# worksheet.write(2, 0, 1234.56, format03) # 1,234.56
#
# format04.set_num_format('0.00')
# worksheet.write(3, 0, 49.99, format04) # 49.99
#
# # Note you can use other currency symbols such as the pound or yen as well.
# # Other currencies may require the use of Unicode.
#
# format07.set_num_format('mm/dd/yy')
# worksheet.write(6, 0, 36892.521, format07) # 01/01/01
#
# format08.set_num_format('mmm d yyyy')
# worksheet.write(7, 0, 36892.521, format08) # Jan 1 2001
#
# format09.set_num_format('d mmmm yyyy')
# worksheet.write(8, 0, 36892.521, format09) # 1 January 2001
#
# format10.set_num_format('dd/mm/yyyy hh:mm AM/PM')
# worksheet.write(9, 0, 36892.521, format10) # 01/01/2001 12:30 AM
#
# format11.set_num_format('0 "dollar and" .00 "cents"')
# worksheet.write(10, 0, 1.87, format11) # 1 dollar and .87 cents
#
# # Conditional formatting
# format12.set_num_format('[Green]General;[Red]-General;General')
# worksheet.write(11, 0, 123, format12) # > 0 Green
# worksheet.write(12, 0, -45, format12) # < 0 Red
# worksheet.write(13, 0, 0, format12) # = 0 Default colour
#
# # Zip code
# format13.set_num_format('00000')
# worksheet.write(14, 0, '01209', format13)
#
# The number system used for dates is described in "DATES AND TIME IN EXCEL".
#
# The colour format should have one of the following values:
#
# [Black] [Blue] [Cyan] [Green] [Magenta] [Red] [White] [Yellow]
#
# Alternatively you can specify the colour based on a colour index as follows:
# [Color n], where n is a standard Excel colour index - 7. See the
# 'Standard colors' worksheet created by formats.rb.
#
# For more information refer to the documentation on formatting in the doc
# directory of the WriteExcel distro, the Excel on-line help or
# http://office.microsoft.com/en-gb/assistance/HP051995001033.aspx
#
# You should ensure that the format string is valid in Excel prior to using
# it in WriteExcel.
#
# Excel's built-in formats are shown in the following table:
#
# Index Index Format String
# 0 0x00 General
# 1 0x01 0
# 2 0x02 0.00
# 3 0x03 #,##0
# 4 0x04 #,##0.00
# 5 0x05 ($#,##0_);($#,##0)
# 6 0x06 ($#,##0_);[Red]($#,##0)
# 7 0x07 ($#,##0.00_);($#,##0.00)
# 8 0x08 ($#,##0.00_);[Red]($#,##0.00)
# 9 0x09 0%
# 10 0x0a 0.00%
# 11 0x0b 0.00E+00
# 12 0x0c # ?/?
# 13 0x0d # ??/??
# 14 0x0e m/d/yy
# 15 0x0f d-mmm-yy
# 16 0x10 d-mmm
# 17 0x11 mmm-yy
# 18 0x12 h:mm AM/PM
# 19 0x13 h:mm:ss AM/PM
# 20 0x14 h:mm
# 21 0x15 h:mm:ss
# 22 0x16 m/d/yy h:mm
# .. .... ...........
# 37 0x25 (#,##0_);(#,##0)
# 38 0x26 (#,##0_);[Red](#,##0)
# 39 0x27 (#,##0.00_);(#,##0.00)
# 40 0x28 (#,##0.00_);[Red](#,##0.00)
# 41 0x29 _(* #,##0_);_(* (#,##0);_(* "-"_);_(@_)
# 42 0x2a _($* #,##0_);_($* (#,##0);_($* "-"_);_(@_)
# 43 0x2b _(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)
# 44 0x2c _($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(@_)
# 45 0x2d mm:ss
# 46 0x2e [h]:mm:ss
# 47 0x2f mm:ss.0
# 48 0x30 ##0.0E+0
# 49 0x31 @
#
# For examples of these formatting codes see the 'Numerical formats' worksheet
# created by formats.rb.
#--
# See also the number_formats1.html and the number_formats2.html documents in
# the doc directory of the distro.
#++
#
# Note 1. Numeric formats 23 to 36 are not documented by Microsoft and may
# differ in international versions.
#
# Note 2. In Excel 5 the dollar sign appears as a dollar sign. In Excel
# 97-2000 it appears as the defined local currency symbol.
#
# Note 3. The red negative numeric formats display slightly differently in
# Excel 5 and Excel 97-2000.
#
def set_num_format(num_format)
@num_format = num_format
end
#
# This method can be used to indent text. The argument, which should be an
# integer, is taken as the level of indentation:
#
# Default state: Text indentation is off
# Default action: Indent text 1 level
# Valid args: Positive integers
#
# 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.
#
def set_indent(indent = 1)
@indent = indent
end
#
# This method can be used to shrink text so that it fits in a cell.
#
# Default state: Text shrinking is off
# Default action: Turn "shrink to fit" on
# Valid args: 1
#
# format = workbook.add_format
# format.set_shrink
# worksheet.write(0, 0, 'Honey, I shrunk the text!', format)
#
def set_shrink(arg = 1)
@shrink = 1
end
#
# Default state: Justify last is off
# Default action: Turn justify last on
# Valid args: 0, 1
#
# Only applies to Far Eastern versions of Excel.
#
def set_text_justlast(arg = 1)
@text_justlast = 1
end
#
# Default state: Pattern is off
# Default action: Solid fill is on
# Valid args: 0 .. 18
#
# Set the background pattern of a cell.
#
# Examples of the available patterns are shown in the 'Patterns' worksheet
# created by formats.rb. However, it is unlikely that you will ever need
# anything other than Pattern 1 which is a solid fill of the background color.
#
def set_pattern(pattern = 1)
@pattern = pattern
end
#
# 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.
#
# Default state: Color is off
# Default action: Solid fill.
# Valid args: See set_color()
#
# 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)
#
# For further examples see the 'Patterns' worksheet created by formats.rb.
#
def set_bg_color(color = 0x41)
@bg_color = get_color(color)
end
#
# The set_fg_color() method can be used to set the foreground colour
# of a pattern.
#
# Default state: Color is off
# Default action: Solid fill.
# Valid args: See set_color()
#
# For further examples see the 'Patterns' worksheet created by formats.rb.
#
def set_fg_color(color = 0x40)
@fg_color = get_color(color)
end
# Dynamically create set methods that aren't already defined.
def method_missing(name, *args) # :nodoc:
# -- original perl comment --
# There are two types of set methods: set_property() and
# set_property_color(). When a method is AUTOLOADED we store a new anonymous
# sub in the appropriate slot in the symbol table. The speeds up subsequent
# calls to the same method.
method = "#{name}"
# Check for a valid method names, i.e. "set_xxx_yyy".
method =~ /set_(\w+)/ or raise "Unknown method: #{method}\n"
# Match the attribute, i.e. "@xxx_yyy".
attribute = "@#{$1}"
# Check that the attribute exists
# ........
if method =~ /set\w+color$/ # for "set_property_color" methods
value = get_color(args[0])
else # for "set_xxx" methods
value = args[0].nil? ? 1 : args[0]
end
if value.respond_to?(:to_str) || !value.respond_to?(:+)
s = %Q!#{attribute} = "#{value.to_s}"!
else
s = %Q!#{attribute} = #{value.to_s}!
end
eval s
end
end # class Format
end # module Writeexcel
|
Radanisk/writeexcel
|
test/test_62_chart_formats.rb
|
<filename>test/test_62_chart_formats.rb
# -*- coding: utf-8 -*-
require 'helper'
require 'stringio'
###############################################################################
#
# A test for Spreadsheet::Writeexcel::Chart.
#
# Tests for the Excel Chart.pm format conversion methods.
#
# reverse('ゥ'), January 2010, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
class TC_ChartFormats < Test::Unit::TestCase
def setup
@io = StringIO.new
@workbook = WriteExcel.new(@io)
@chart = @workbook.add_chart(:type => 'Chart::Column')
end
###############################################################################
#
# Test. User defined colour as string.
#
def test_user_defined_color_as_string
color = 'red'
caption1 = " \tChart: index = get_color_indices(#{color})"
caption2 = " \tChart: rgb = get_color_indices(#{color})"
expected_index = 0x0A
expected_rgb = 0x000000FF
got_index, got_rgb = @chart.__send__("get_color_indices", color)
assert_equal(expected_index, got_index, caption1)
assert_equal(expected_rgb, got_rgb, caption2)
color = 'black'
caption1 = " \tChart: index = get_color_indices(#{color})"
caption2 = " \tChart: rgb = get_color_indices(#{color})"
expected_index = 0x08
expected_rgb = 0x00000000
got_index, got_rgb = @chart.__send__("get_color_indices", color)
assert_equal(expected_index, got_index, caption1)
assert_equal(expected_rgb, got_rgb, caption2)
color = 'white'
caption1 = " \tChart: index = get_color_indices(#{color})"
caption2 = " \tChart: rgb = get_color_indices(#{color})"
expected_index = 0x09
expected_rgb = 0x00FFFFFF
got_index, got_rgb = @chart.__send__("get_color_indices", color)
assert_equal(expected_index, got_index, caption1)
assert_equal(expected_rgb, got_rgb, caption2)
end
###############################################################################
#
# Test. User defined colour as an index.
#
def test_user_defined_color_as_an_index
color = 0x0A
caption1 = " \tChart: index = get_color_indices(#{color})"
caption2 = " \tChart: rgb = get_color_indices(#{color})"
expected_index = 0x0A
expected_rgb = 0x000000FF
got_index, got_rgb = @chart.__send__("get_color_indices", color)
assert_equal(expected_index, got_index, caption1)
assert_equal(expected_rgb, got_rgb, caption2)
end
###############################################################################
#
# Test. User defined colour as an out of range index.
#
def test_user_defined_color_as_an_out_of_range_index
color = 7
caption1 = " \tChart: index = get_color_indices(#{color})"
caption2 = " \tChart: rgb = get_color_indices(#{color})"
expected_index = nil
expected_rgb = nil
got_index, got_rgb = @chart.__send__("get_color_indices", color)
assert_equal(expected_index, got_index, caption1)
assert_equal(expected_rgb, got_rgb, caption2)
color = 64
caption1 = " \tChart: index = get_color_indices(#{color})"
caption2 = " \tChart: rgb = get_color_indices(#{color})"
expected_index = nil
expected_rgb = nil
got_index, got_rgb = @chart.__send__("get_color_indices", color)
assert_equal(expected_index, got_index, caption1)
assert_equal(expected_rgb, got_rgb, caption2)
end
###############################################################################
#
# Test. User defined colour as an invalid string.
#
def test_user_defined_color_as_an_invalid_string
color = 'plaid'
caption1 = " \tChart: index = get_color_indices(#{color})"
caption2 = " \tChart: rgb = get_color_indices(#{color})"
expected_index = nil
expected_rgb = nil
got_index, got_rgb = @chart.__send__("get_color_indices", color)
assert_equal(expected_index, got_index, caption1)
assert_equal(expected_rgb, got_rgb, caption2)
end
###############################################################################
#
# Test. User defined colour as an undef property.
#
def test_user_defined_color_as_an_nil_property
color = nil
caption1 = " \tChart: index = get_color_indices(#{color})"
caption2 = " \tChart: rgb = get_color_indices(#{color})"
expected_index = nil
expected_rgb = nil
got_index, got_rgb = @chart.__send__("get_color_indices", color)
assert_equal(expected_index, got_index, caption1)
assert_equal(expected_rgb, got_rgb, caption2)
end
###############################################################################
#
# Test. Line patterns with indices.
#
def test_line_patterns_with_indices
caption = " \tChart: pattern = _get_line_pattern()"
values = {
0 => 5,
1 => 0,
2 => 1,
3 => 2,
4 => 3,
5 => 4,
6 => 7,
7 => 6,
8 => 8,
9 => 0,
nil => 0
}
expected = []
got = []
values.each do |user, excel|
got.push(@chart.__send__("get_line_pattern", user))
expected.push(excel)
end
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test. Line patterns with names.
#
def test_line_patterns_with_names
caption = " \tChart: pattern = _get_line_pattern()"
values = {
'solid' => 0,
'dash' => 1,
'dot' => 2,
'dash-dot' => 3,
'dash-dot-dot' => 4,
'none' => 5,
'dark-gray' => 6,
'medium-gray' => 7,
'light-gray' => 8,
'DASH' => 1,
'fictional' => 0
}
expected = []
got = []
values.each do |user, excel|
got.push(@chart.__send__("get_line_pattern", user))
expected.push(excel)
end
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test. Line weights with indices.
#
def test_line_weights_with_indices
caption = " \tChart: weight = _get_line_weight()"
values = {
1 => -1,
2 => 0,
3 => 1,
4 => 2,
5 => 0,
0 => 0,
nil => 0
}
expected = []
got = []
values.each do |user, excel|
got.push(@chart.__send__("get_line_weight", user))
expected.push(excel)
end
assert_equal(expected, got, caption)
end
###############################################################################
#
# Test. Line weights with names.
#
def test_line_weights_with_names
caption = " \tChart: weight = _get_line_weight()"
values = {
'hairline' => -1,
'narrow' => 0,
'medium' => 1,
'wide' => 2,
'WIDE' => 2,
'Fictional' => 0,
}
expected = []
got = []
values.each do |user, excel|
got.push(@chart.__send__("get_line_weight", user))
expected.push(excel)
end
assert_equal(expected, got, caption)
end
end
|
Radanisk/writeexcel
|
test/test_61_chart_subclasses.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_chart_subclasses < Test::Unit::TestCase
def setup
io = StringIO.new
@workbook = WriteExcel.new(io)
end
def test_store_chart_type_of_column
chart = Writeexcel::Chart.factory('Chart::Column', @workbook, nil, nil)
expected = %w(
17 10 06 00 00 00 96 00 00 00
).join(' ')
got = unpack_record(chart.store_chart_type)
assert_equal(expected, got)
end
def test_store_chart_type_of_bar
chart = Writeexcel::Chart.factory('Chart::Bar', @workbook, nil, nil)
expected = %w(
17 10 06 00 00 00 96 00 01 00
).join(' ')
got = unpack_record(chart.store_chart_type)
assert_equal(expected, got)
end
def test_store_chart_type_of_line
chart = Writeexcel::Chart.factory('Chart::Line', @workbook, nil, nil)
expected = %w(
18 10 02 00 00 00
).join(' ')
got = unpack_record(chart.store_chart_type)
assert_equal(expected, got)
end
def test_store_chart_type_of_area
chart = Writeexcel::Chart.factory('Chart::Area', @workbook, nil, nil)
expected = %w(
1A 10 02 00 01 00
).join(' ')
got = unpack_record(chart.store_chart_type)
assert_equal(expected, got)
end
def test_store_chart_type_of_pie
chart = Writeexcel::Chart.factory('Chart::Pie', @workbook, nil, nil)
expected = %w(
19 10 06 00 00 00 00 00 02 00
).join(' ')
got = unpack_record(chart.store_chart_type)
assert_equal(expected, got)
end
def test_store_chart_type_of_scatter
chart = Writeexcel::Chart.factory('Chart::Scatter', @workbook, nil, nil)
expected = %w(
1B 10 06 00 64 00 01 00 00 00
).join(' ')
got = unpack_record(chart.store_chart_type)
assert_equal(expected, got)
end
def test_store_chart_type_of_stock
chart = Writeexcel::Chart.factory('Chart::Stock', @workbook, nil, nil)
expected = %w(
18 10 02 00 00 00
).join(' ')
got = unpack_record(chart.store_chart_type)
assert_equal(expected, got)
end
end
|
Radanisk/writeexcel
|
examples/outline_collapsed.rb
|
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
###############################################################################
#
# Example of how use Spreadsheet::WriteExcel to generate Excel outlines and
# grouping.
#
# These example focus mainly on collapsed outlines. See also the
# outlines.pl example program for more general examples.
#
# reverse('©'), March 2008, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
# Create a new workbook and add some worksheets
workbook = WriteExcel.new('outline_collapsed.xls')
worksheet1 = workbook.add_worksheet('Outlined Rows')
worksheet2 = workbook.add_worksheet('Collapsed Rows 1')
worksheet3 = workbook.add_worksheet('Collapsed Rows 2')
worksheet4 = workbook.add_worksheet('Collapsed Rows 3')
worksheet5 = workbook.add_worksheet('Outline Columns')
worksheet6 = workbook.add_worksheet('Collapsed Columns')
# Add a general format
bold = workbook.add_format(:bold => 1)
#
# This function will generate the same data and sub-totals on each worksheet.
#
def create_sub_totals(worksheet, bold)
# Add a column format for clarity
worksheet.set_column('A:A', 20)
# Add the data, labels and formulas
worksheet.write('A1', 'Region', bold)
worksheet.write('A2', 'North')
worksheet.write('A3', 'North')
worksheet.write('A4', 'North')
worksheet.write('A5', 'North')
worksheet.write('A6', 'North Total', bold)
worksheet.write('B1', 'Sales', bold)
worksheet.write('B2', 1000)
worksheet.write('B3', 1200)
worksheet.write('B4', 900)
worksheet.write('B5', 1200)
worksheet.write('B6', '=SUBTOTAL(9,B2:B5)', bold)
worksheet.write('A7', 'South')
worksheet.write('A8', 'South')
worksheet.write('A9', 'South')
worksheet.write('A10', 'South')
worksheet.write('A11', 'South Total', bold)
worksheet.write('B7', 400)
worksheet.write('B8', 600)
worksheet.write('B9', 500)
worksheet.write('B10', 600)
worksheet.write('B11', '=SUBTOTAL(9,B7:B10)', bold)
worksheet.write('A12', 'Grand Total', bold)
worksheet.write('B12', '=SUBTOTAL(9,B2:B10)', bold)
end
###############################################################################
#
# Example 1: Create a worksheet with outlined rows. It also includes SUBTOTAL()
# functions so that it looks like the type of automatic outlines that are
# generated when you use the Excel Data.SubTotals menu item.
#
# The syntax is: set_row(row, height, XF, hidden, level, collapsed)
worksheet1.set_row(1, nil, nil, 0, 2)
worksheet1.set_row(2, nil, nil, 0, 2)
worksheet1.set_row(3, nil, nil, 0, 2)
worksheet1.set_row(4, nil, nil, 0, 2)
worksheet1.set_row(5, nil, nil, 0, 1)
worksheet1.set_row(6, nil, nil, 0, 2)
worksheet1.set_row(7, nil, nil, 0, 2)
worksheet1.set_row(8, nil, nil, 0, 2)
worksheet1.set_row(9, nil, nil, 0, 2)
worksheet1.set_row(10, nil, nil, 0, 1)
# Write the sub-total data that is common to the row examples.
create_sub_totals(worksheet1, bold)
###############################################################################
#
# Example 2: Create a worksheet with collapsed outlined rows.
# This is the same as the example 1 except that the all rows are collapsed.
# Note: We need to indicate the row that contains the collapsed symbol '+' with
# the optional parameter, collapsed.
worksheet2.set_row(1, nil, nil, 1, 2)
worksheet2.set_row(2, nil, nil, 1, 2)
worksheet2.set_row(3, nil, nil, 1, 2)
worksheet2.set_row(4, nil, nil, 1, 2)
worksheet2.set_row(5, nil, nil, 1, 1)
worksheet2.set_row(6, nil, nil, 1, 2)
worksheet2.set_row(7, nil, nil, 1, 2)
worksheet2.set_row(8, nil, nil, 1, 2)
worksheet2.set_row(9, nil, nil, 1, 2)
worksheet2.set_row(10, nil, nil, 1, 1)
worksheet2.set_row(11, nil, nil, 0, 0, 1)
# Write the sub-total data that is common to the row examples.
create_sub_totals(worksheet2, bold)
###############################################################################
#
# Example 3: Create a worksheet with collapsed outlined rows.
# Same as the example 1 except that the two sub-totals are collapsed.
worksheet3.set_row(1, nil, nil, 1, 2)
worksheet3.set_row(2, nil, nil, 1, 2)
worksheet3.set_row(3, nil, nil, 1, 2)
worksheet3.set_row(4, nil, nil, 1, 2)
worksheet3.set_row(5, nil, nil, 0, 1, 1)
worksheet3.set_row(6, nil, nil, 1, 2)
worksheet3.set_row(7, nil, nil, 1, 2)
worksheet3.set_row(8, nil, nil, 1, 2)
worksheet3.set_row(9, nil, nil, 1, 2)
worksheet3.set_row(10, nil, nil, 0, 1, 1)
# Write the sub-total data that is common to the row examples.
create_sub_totals(worksheet3, bold)
###############################################################################
#
# Example 4: Create a worksheet with outlined rows.
# Same as the example 1 except that the two sub-totals are collapsed.
worksheet4.set_row(1, nil, nil, 1, 2)
worksheet4.set_row(2, nil, nil, 1, 2)
worksheet4.set_row(3, nil, nil, 1, 2)
worksheet4.set_row(4, nil, nil, 1, 2)
worksheet4.set_row(5, nil, nil, 1, 1, 1)
worksheet4.set_row(6, nil, nil, 1, 2)
worksheet4.set_row(7, nil, nil, 1, 2)
worksheet4.set_row(8, nil, nil, 1, 2)
worksheet4.set_row(9, nil, nil, 1, 2)
worksheet4.set_row(10, nil, nil, 1, 1, 1)
worksheet4.set_row(11, nil, nil, 0, 0, 1)
# Write the sub-total data that is common to the row examples.
create_sub_totals(worksheet4, bold)
###############################################################################
#
# Example 5: Create a worksheet with outlined columns.
#
data = [
['Month', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',' Total'],
['North', 50, 20, 15, 25, 65, 80, '=SUM(B2:G2)'],
['South', 10, 20, 30, 50, 50, 50, '=SUM(B3:G3)'],
['East', 45, 75, 50, 15, 75, 100, '=SUM(B4:G4)'],
['West', 15, 15, 55, 35, 20, 50, '=SUM(B5:G6)']
]
# Add bold format to the first row
worksheet5.set_row(0, nil, bold)
# Syntax: set_column(col1, col2, width, XF, hidden, level, collapsed)
worksheet5.set_column('A:A', 10, bold )
worksheet5.set_column('B:G', 5, nil, 0, 1)
worksheet5.set_column('H:H', 10 )
# Write the data and a formula
worksheet5.write_col('A1', data)
worksheet5.write('H6', '=SUM(H2:H5)', bold)
###############################################################################
#
# Example 6: Create a worksheet with collapsed outlined columns.
# This is the same as the previous example except collapsed columns.
# Add bold format to the first row
worksheet6.set_row(0, nil, bold)
# Syntax: set_column(col1, col2, width, XF, hidden, level, collapsed)
worksheet6.set_column('A:A', 10, bold )
worksheet6.set_column('B:G', 5, nil, 1, 1 )
worksheet6.set_column('H:H', 10, nil, 0, 0, 1)
# Write the data and a formula
worksheet6.write_col('A1', data)
worksheet6.write('H6', '=SUM(H2:H5)', bold)
workbook.close
|
Radanisk/writeexcel
|
test/test_11_date_time.rb
|
# -*- coding: utf-8 -*-
###############################################################################
#
# A test for WriteExcel.
#
# Tests date and time 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_time < 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_convert_date_time_should_not_change_date_time_string
date_time = ' 1899-12-31T00:00:00.0004Z '
@worksheet.convert_date_time(date_time)
assert_equal(' 1899-12-31T00:00:00.0004Z ', date_time)
end
def test_float_comparison_function
# pass: diff < @fit_delta
date_time = '1899-12-31T00:00:00.0004'
number = 0
result = @worksheet.__send__("convert_date_time", date_time)
result = -1 if result.nil?
assert(fit_cmp(number, result),
"Testing convert_date_time: #{date_time} => #{result} <> #{number}")
# fail: diff > @fit_delta
date_time = '1989-12-31%00:00:00.0005'
number = 0
result = @worksheet.__send__("convert_date_time", date_time)
result = -1 if result.nil?
assert(!fit_cmp(number, result),
"Testing convert_date_time: #{date_time} => #{result} <> #{number}")
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="s21"><Data ss:Type="DateTime">1899-12-31T00:00:00.000</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">0</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">1982-08-25T00:15:20.213</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">30188.010650613425</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">2065-04-19T00:16:48.290</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">60376.011670023145</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">2147-12-15T00:55:25.446</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">90565.038488958337</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">2230-08-10T01:02:46.891</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">120753.04359827546</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">2313-04-06T01:04:15.597</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">150942.04462496529</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">2395-11-30T01:09:40.889</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">181130.04838991899</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">2478-07-25T01:11:32.560</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">211318.04968240741</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">2561-03-21T01:30:19.169</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">241507.06272186342</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">2643-11-15T01:48:25.580</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">271695.07529606484</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">2726-07-12T02:03:31.919</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">301884.08578609955</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">2809-03-06T02:11:11.986</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">332072.09111094906</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">2891-10-31T02:24:37.095</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">362261.10042934027</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">2974-06-26T02:35:07.220</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">392449.10772245371</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">3057-02-19T02:45:12.109</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">422637.1147234838</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">3139-10-17T03:06:39.990</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">452826.12962951389</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">3222-06-11T03:08:08.251</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">483014.13065105322</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">3305-02-05T03:19:12.576</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">513203.13834</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">3387-10-01T03:29:42.574</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">543391.14563164348</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">3470-05-27T03:37:30.813</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">573579.15105107636</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">3553-01-21T04:14:38.231</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">603768.17683137732</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">3635-09-16T04:16:28.559</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">633956.17810832174</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">3718-05-13T04:17:58.222</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">664145.17914608796</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">3801-01-06T04:21:41.794</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">694333.18173372687</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">3883-09-02T04:56:35.792</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">724522.20596981479</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">3966-04-28T05:25:14.885</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">754710.2258667245</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">4048-12-21T05:26:05.724</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">784898.22645513888</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">4131-08-18T05:46:44.068</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">815087.24078782403</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">4214-04-13T05:48:01.141</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">845275.24167987274</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">4296-12-07T05:53:52.315</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">875464.24574438657</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">4379-08-03T06:14:48.580</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">905652.26028449077</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">4462-03-28T06:46:15.738</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">935840.28212659725</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">4544-11-22T07:31:20.407</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">966029.31343063654</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">4627-07-19T07:58:33.754</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">996217.33233511576</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">4710-03-15T08:07:43.130</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">1026406.3386936343</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">4792-11-07T08:29:11.091</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">1056594.3536005903</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">4875-07-04T09:08:15.328</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">1086783.3807329629</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">4958-02-27T09:30:41.781</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">1116971.3963169097</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">5040-10-23T09:34:04.462</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">1147159.3986627546</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">5123-06-20T09:37:23.945</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">1177348.4009715857</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">5206-02-12T09:37:56.655</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">1207536.4013501736</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">5288-10-08T09:45:12.230</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">1237725.406391551</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">5371-06-04T09:54:14.782</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">1267913.412671088</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">5454-01-28T09:54:22.108</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">1298101.4127558796</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">5536-09-24T10:01:36.151</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">1328290.4177795255</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">5619-05-20T12:09:48.602</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">1358478.5068125231</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">5702-01-14T12:34:08.549</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">1388667.5237100578</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">5784-09-08T12:56:06.495</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">1418855.5389640625</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">5867-05-06T12:58:58.217</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">1449044.5409515856</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">5949-12-30T12:59:54.263</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">1479232.5416002662</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">6032-08-24T13:34:41.331</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">1509420.5657561459</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">6115-04-21T13:58:28.601</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">1539609.5822754744</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">6197-12-14T14:02:16.899</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">1569797.5849178126</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">6280-08-10T14:36:17.444</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">1599986.6085352316</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">6363-04-06T14:37:57.451</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">1630174.60969272</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">6445-11-30T14:57:42.757</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">1660363.6234115392</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">6528-07-26T15:10:48.307</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">1690551.6325035533</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">6611-03-22T15:14:39.890</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">1720739.635183912</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">6693-11-15T15:19:47.988</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">1750928.6387498612</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">6776-07-11T16:04:24.344</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">1781116.6697262037</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">6859-03-07T16:22:23.952</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">1811305.6822216667</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">6941-10-31T16:29:55.999</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">1841493.6874536921</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">7024-06-26T16:58:20.259</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">1871681.7071789235</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">7107-02-21T17:04:02.415</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">1901870.7111390624</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">7189-10-16T17:18:29.630</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">1932058.7211762732</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">7272-06-11T17:47:21.323</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">1962247.7412190163</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">7355-02-05T17:53:29.866</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">1992435.7454845603</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">7437-10-02T17:53:41.076</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">2022624.7456143056</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">7520-05-28T17:55:06.044</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">2052812.7465977315</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">7603-01-21T18:14:49.151</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">2083000.7602910995</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">7685-09-16T18:17:45.738</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">2113189.7623349307</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">7768-05-12T18:29:59.700</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">2143377.7708298611</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">7851-01-07T18:33:21.233</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">2173566.773162419</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">7933-09-02T19:14:24.673</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">2203754.8016744559</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">8016-04-27T19:17:12.816</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">2233942.8036205554</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">8098-12-22T19:23:36.418</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">2264131.8080603937</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">8181-08-17T19:46:25.908</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">2294319.8239109721</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">8264-04-13T20:07:47.314</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">2324508.8387420601</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">8346-12-08T20:31:37.603</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">2354696.855296331</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">8429-08-03T20:39:57.770</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">2384885.8610853008</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">8512-03-29T20:50:17.067</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">2415073.8682530904</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">8594-11-22T21:02:57.827</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">2445261.8770581828</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">8677-07-19T21:23:05.519</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">2475450.8910360998</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">8760-03-14T21:34:49.572</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">2505638.8991848612</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">8842-11-08T21:39:05.944</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">2535827.9021521294</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">8925-07-04T21:39:18.426</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">2566015.9022965971</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">9008-02-28T21:46:07.769</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">2596203.9070343636</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">9090-10-24T21:57:55.662</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">2626392.9152275696</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">9173-06-19T22:19:11.732</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">2656580.9299968979</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">9256-02-13T22:23:51.376</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">2686769.9332335186</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">9338-10-09T22:27:58.771</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">2716957.9360968866</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">9421-06-05T22:43:30.392</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">2747146.9468795368</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">9504-01-30T22:48:25.834</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">2777334.9502990046</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">9586-09-24T22:53:51.727</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">2807522.9540709145</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">9669-05-20T23:12:56.536</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">2837711.9673210187</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">9752-01-14T23:15:54.109</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">2867899.9693762613</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">9834-09-10T23:17:12.632</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">2898088.9702850925</Data></Cell>
</Row>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="DateTime">9999-12-31T23:59:59.000</Data></Cell>
<Cell ss:StyleID="s22" ss:Formula="=RC[-1]"><Data ss:Type="Number">2958465.999988426</Data></Cell>
</Row>
__DATA_END__
end
end
|
Radanisk/writeexcel
|
examples/utf8.rb
|
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
$debug = true
require 'writeexcel'
workbook = WriteExcel.new('utf8.xls')
worksheet = workbook.add_worksheet('シート1')
format = workbook.add_format(:font => 'MS 明朝')
worksheet.set_footer('フッター')
worksheet.set_header('ヘッダー')
worksheet.write('A1', 'UTF8文字列', format)
worksheet.write('A2', '=CONCATENATE(A1,"の連結")', format)
workbook.close
|
Radanisk/writeexcel
|
lib/writeexcel/debug_info.rb
|
<filename>lib/writeexcel/debug_info.rb
# -*- coding: utf-8 -*-
require 'writeexcel/caller_info'
if defined?($writeexcel_debug)
class BIFFWriter
include CallerInfo
def append(*args)
data =
ruby_18 { args.join } ||
ruby_19 { args.collect{ |arg| arg.dup.force_encoding('ASCII-8BIT') }.join }
print_caller_info(data, :method => 'append')
super
end
def prepend(*args)
data =
ruby_18 { args.join } ||
ruby_19 { args.collect{ |arg| arg.dup.force_encoding('ASCII-8BIT') }.join }
print_caller_info(data, :method => 'prepend')
super
end
def print_caller_info(data, param = {})
infos = caller_info
print "#{param[:method]}\n" if param[:method]
infos.each do |info|
print "#{info[:file]}:#{info[:line]}"
print " in #{info[:method]}" if info[:method]
print "\n"
end
print unpack_record(data) + "\n\n"
end
def unpack_record(data) # :nodoc:
data.unpack('C*').map! {|c| sprintf("%02X", c) }.join(' ')
end
end
end
|
Radanisk/writeexcel
|
examples/right_to_left.rb
|
<reponame>Radanisk/writeexcel
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
#######################################################################
#
# Example of how to change the default worksheet direction from
# left-to-right to right-to-left as required by some eastern verions
# of Excel.
#
# reverse('©'), January 2006, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
workbook = WriteExcel.new("right_to_left.xls")
worksheet1 = workbook.add_worksheet
worksheet2 = workbook.add_worksheet
worksheet2.right_to_left
worksheet1.write(0, 0, 'Hello') # A1, B1, C1, ...
worksheet2.write(0, 0, 'Hello') # ..., C1, B1, A1
workbook.close
|
Radanisk/writeexcel
|
test/test_28_autofilter.rb
|
<filename>test/test_28_autofilter.rb
# -*- coding: utf-8 -*-
##########################################################################
# test_28_autofilter.rb
#
# Tests for the token parsing methods 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_28_autofilter < Test::Unit::TestCase
def test_28_autofilter
@tests.each do |test|
expression = test[0]
expected = test[1]
tokens = @worksheet.__send__("extract_filter_tokens", expression)
result = @worksheet.__send__("parse_filter_expression", expression, tokens)
testname = expression || 'none'
assert_equal(expected, result, testname)
end
end
def setup
@workbook = WriteExcel.new(StringIO.new)
@worksheet = @workbook.add_worksheet
@tests = [
[
'x = 2000',
[2, 2000],
],
[
'x == 2000',
[2, 2000],
],
[
'x =~ 2000',
[2, 2000],
],
[
'x eq 2000',
[2, 2000],
],
[
'x <> 2000',
[5, 2000],
],
[
'x != 2000',
[5, 2000],
],
[
'x ne 2000',
[5, 2000],
],
[
'x !~ 2000',
[5, 2000],
],
[
'x > 2000',
[4, 2000],
],
[
'x < 2000',
[1, 2000],
],
[
'x >= 2000',
[6, 2000],
],
[
'x <= 2000',
[3, 2000],
],
[
'x > 2000 and x < 5000',
[4, 2000, 0, 1, 5000],
],
[
'x > 2000 && x < 5000',
[4, 2000, 0, 1, 5000],
],
[
'x > 2000 or x < 5000',
[4, 2000, 1, 1, 5000],
],
[
'x > 2000 || x < 5000',
[4, 2000, 1, 1, 5000],
],
[
'x = Blanks',
[2, 'blanks'],
],
[
'x = NonBlanks',
[2, 'nonblanks'],
],
[
'x <> Blanks',
[2, 'nonblanks'],
],
[
'x <> NonBlanks',
[2, 'blanks'],
],
[
'Top 10 Items',
[30, 10],
],
[
'Top 20 %',
[31, 20],
],
[
'Bottom 5 Items',
[32, 5],
],
[
'Bottom 101 %',
[33, 101],
],
]
end
end
|
Radanisk/writeexcel
|
examples/outline.rb
|
<filename>examples/outline.rb
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
###############################################################################
#
# Example of how use Spreadsheet::WriteExcel to generate Excel outlines and
# grouping.
#
#
# Excel allows you to group rows or columns so that they can be hidden or
# displayed with a single mouse click. This feature is referred to as outlines.
#
# Outlines can reduce complex data down to a few salient sub-totals or
# summaries.
#
# This feature is best viewed in Excel but the following is an ASCII
# representation of what a worksheet with three outlines might look like.
# Rows 3-4 and rows 7-8 are grouped at level 2. Rows 2-9 are grouped at
# level 1. The lines at the left hand side are called outline level bars.
#
#
# ------------------------------------------
# 1 2 3 | | A | B | C | D | ...
# ------------------------------------------
# _ | 1 | A | | | | ...
# | _ | 2 | B | | | | ...
# | | | 3 | (C) | | | | ...
# | | | 4 | (D) | | | | ...
# | - | 5 | E | | | | ...
# | _ | 6 | F | | | | ...
# | | | 7 | (G) | | | | ...
# | | | 8 | (H) | | | | ...
# | - | 9 | I | | | | ...
# - | . | ... | ... | ... | ... | ...
#
#
# Clicking the minus sign on each of the level 2 outlines will collapse and
# hide the data as shown in the next figure. The minus sign changes to a plus
# sign to indicate that the data in the outline is hidden.
#
# ------------------------------------------
# 1 2 3 | | A | B | C | D | ...
# ------------------------------------------
# _ | 1 | A | | | | ...
# | | 2 | B | | | | ...
# | + | 5 | E | | | | ...
# | | 6 | F | | | | ...
# | + | 9 | I | | | | ...
# - | . | ... | ... | ... | ... | ...
#
#
# Clicking on the minus sign on the level 1 outline will collapse the remaining
# rows as follows:
#
# ------------------------------------------
# 1 2 3 | | A | B | C | D | ...
# ------------------------------------------
# | 1 | A | | | | ...
# + | . | ... | ... | ... | ... | ...
#
# See the main Spreadsheet::WriteExcel documentation for more information.
#
# reverse('©'), April 2003, <NAME>, <EMAIL>
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'writeexcel'
# Create a new workbook and add some worksheets
workbook = WriteExcel.new('outline.xls')
worksheet1 = workbook.add_worksheet('Outlined Rows')
worksheet2 = workbook.add_worksheet('Collapsed Rows')
worksheet3 = workbook.add_worksheet('Outline Columns')
worksheet4 = workbook.add_worksheet('Outline levels')
# Add a general format
bold = workbook.add_format(:bold => 1)
###############################################################################
#
# Example 1: Create a worksheet with outlined rows. It also includes SUBTOTAL()
# functions so that it looks like the type of automatic outlines that are
# generated when you use the Excel Data->SubTotals menu item.
#
# For outlines the important parameters are $hidden and $level. Rows with the
# same $level are grouped together. The group will be collapsed if $hidden is
# non-zero. $height and $XF are assigned default values if they are undef.
#
# The syntax is: set_row($row, $height, $XF, $hidden, $level, $collapsed)
#
worksheet1.set_row(1, nil, nil, 0, 2)
worksheet1.set_row(2, nil, nil, 0, 2)
worksheet1.set_row(3, nil, nil, 0, 2)
worksheet1.set_row(4, nil, nil, 0, 2)
worksheet1.set_row(5, nil, nil, 0, 1)
worksheet1.set_row(6, nil, nil, 0, 2)
worksheet1.set_row(7, nil, nil, 0, 2)
worksheet1.set_row(8, nil, nil, 0, 2)
worksheet1.set_row(9, nil, nil, 0, 2)
worksheet1.set_row(10, nil, nil, 0, 1)
# Add a column format for clarity
worksheet1.set_column('A:A', 20)
# Add the data, labels and formulas
worksheet1.write('A1', 'Region', bold)
worksheet1.write('A2', 'North')
worksheet1.write('A3', 'North')
worksheet1.write('A4', 'North')
worksheet1.write('A5', 'North')
worksheet1.write('A6', 'North Total', bold)
worksheet1.write('B1', 'Sales', bold)
worksheet1.write('B2', 1000)
worksheet1.write('B3', 1200)
worksheet1.write('B4', 900)
worksheet1.write('B5', 1200)
worksheet1.write('B6', '=SUBTOTAL(9,B2:B5)', bold)
worksheet1.write('A7', 'South')
worksheet1.write('A8', 'South')
worksheet1.write('A9', 'South')
worksheet1.write('A10', 'South')
worksheet1.write('A11', 'South Total', bold)
worksheet1.write('B7', 400)
worksheet1.write('B8', 600)
worksheet1.write('B9', 500)
worksheet1.write('B10', 600)
worksheet1.write('B11', '=SUBTOTAL(9,B7:B10)', bold)
worksheet1.write('A12', 'Grand Total', bold)
worksheet1.write('B12', '=SUBTOTAL(9,B2:B10)', bold)
###############################################################################
#
# Example 2: Create a worksheet with outlined rows. This is the same as the
# previous example except that the rows are collapsed.
# Note: We need to indicate the row that contains the collapsed symbol '+'
# with the optional parameter, $collapsed.
# The group will be collapsed if $hidden is non-zero.
# The syntax is: set_row($row, $height, $XF, $hidden, $level, $collapsed)
#
worksheet2.set_row(1, nil, nil, 1, 2)
worksheet2.set_row(2, nil, nil, 1, 2)
worksheet2.set_row(3, nil, nil, 1, 2)
worksheet2.set_row(4, nil, nil, 1, 2)
worksheet2.set_row(5, nil, nil, 1, 1)
worksheet2.set_row(6, nil, nil, 1, 2)
worksheet2.set_row(7, nil, nil, 1, 2)
worksheet2.set_row(8, nil, nil, 1, 2)
worksheet2.set_row(9, nil, nil, 1, 2)
worksheet2.set_row(10, nil, nil, 1, 1)
worksheet2.set_row(11, nil, nil, 0, 0, 1)
# Add a column format for clarity
worksheet2.set_column('A:A', 20)
# Add the data, labels and formulas
worksheet2.write('A1', 'Region', bold)
worksheet2.write('A2', 'North')
worksheet2.write('A3', 'North')
worksheet2.write('A4', 'North')
worksheet2.write('A5', 'North')
worksheet2.write('A6', 'North Total', bold)
worksheet2.write('B1', 'Sales', bold)
worksheet2.write('B2', 1000)
worksheet2.write('B3', 1200)
worksheet2.write('B4', 900)
worksheet2.write('B5', 1200)
worksheet2.write('B6', '=SUBTOTAL(9,B2:B5)', bold)
worksheet2.write('A7', 'South')
worksheet2.write('A8', 'South')
worksheet2.write('A9', 'South')
worksheet2.write('A10', 'South')
worksheet2.write('A11', 'South Total', bold)
worksheet2.write('B7', 400)
worksheet2.write('B8', 600)
worksheet2.write('B9', 500)
worksheet2.write('B10', 600)
worksheet2.write('B11', '=SUBTOTAL(9,B7:B10)', bold)
worksheet2.write('A12', 'Grand Total', bold)
worksheet2.write('B12', '=SUBTOTAL(9,B2:B10)', bold)
###############################################################################
#
# Example 3: Create a worksheet with outlined columns.
#
data = [
['Month', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', ' Total'],
['North', 50, 20, 15, 25, 65, 80, '=SUM(B2:G2)'],
['South', 10, 20, 30, 50, 50, 50, '=SUM(B3:G3)'],
['East', 45, 75, 50, 15, 75, 100, '=SUM(B4:G4)'],
['West', 15, 15, 55, 35, 20, 50, '=SUM(B5:G6)']
]
# Add bold format to the first row
worksheet3.set_row(0, nil, bold)
# Syntax: set_column(col1, col2, width, XF, hidden, level, collapsed)
worksheet3.set_column('A:A', 10, bold )
worksheet3.set_column('B:G', 5, nil, 0, 1)
worksheet3.set_column('H:H', 10)
# Write the data and a formula
worksheet3.write_col('A1', data)
worksheet3.write('H6', '=SUM(H2:H5)', bold)
###############################################################################
#
# Example 4: Show all possible outline levels.
#
levels = [
"Level 1", "Level 2", "Level 3", "Level 4",
"Level 5", "Level 6", "Level 7", "Level 6",
"Level 5", "Level 4", "Level 3", "Level 2", "Level 1"
]
worksheet4.write_col('A1', levels)
worksheet4.set_row(0, nil, nil, nil, 1)
worksheet4.set_row(1, nil, nil, nil, 2)
worksheet4.set_row(2, nil, nil, nil, 3)
worksheet4.set_row(3, nil, nil, nil, 4)
worksheet4.set_row(4, nil, nil, nil, 5)
worksheet4.set_row(5, nil, nil, nil, 6)
worksheet4.set_row(6, nil, nil, nil, 7)
worksheet4.set_row(7, nil, nil, nil, 6)
worksheet4.set_row(8, nil, nil, nil, 5)
worksheet4.set_row(9, nil, nil, nil, 4)
worksheet4.set_row(10, nil, nil, nil, 3)
worksheet4.set_row(11, nil, nil, nil, 2)
worksheet4.set_row(12, nil, nil, nil, 1)
workbook.close
|
Radanisk/writeexcel
|
lib/writeexcel/version.rb
|
<gh_stars>10-100
require 'writeexcel'
class WriteExcel < Workbook
VERSION = "1.0.5"
end
|
Radanisk/writeexcel
|
lib/writeexcel/properties.rb
|
<gh_stars>10-100
# -*- coding: utf-8 -*-
###############################################################################
#
# Properties - A module for creating Excel property sets.
#
#
# Used in conjunction with WriteExcel
#
# Copyright 2000-2010, <NAME>.
#
# original written in Perl by <NAME>
# converted to Ruby by <NAME>, <EMAIL>
#
require 'date'
###############################################################################
#
# create_summary_property_set().
#
# Create the SummaryInformation property set. This is mainly used for the
# Title, Subject, Author, Keywords, Comments, Last author keywords and the
# creation date.
#
def create_summary_property_set(properties) #:nodoc:
byte_order = [0xFFFE].pack('v')
version = [0x0000].pack('v')
system_id = [0x00020105].pack('V')
class_id = ['00000000000000000000000000000000'].pack('H*')
num_property_sets = [0x0001].pack('V')
format_id = ['E0859FF2F94F6810AB9108002B27B3D9'].pack('H*')
offset = [0x0030].pack('V')
num_property = [properties.size].pack('V')
property_offsets = ''
# Create the property set data block and calculate the offsets into it.
property_data, offsets = pack_property_data(properties)
# Create the property type and offsets based on the previous calculation.
0.upto(properties.size - 1) do |i|
property_offsets += [properties[i][0], offsets[i]].pack('VV')
end
# Size of size (4 bytes) + num_property (4 bytes) + the data structures.
size = 8 + (property_offsets).bytesize + property_data.bytesize
size = [size].pack('V')
byte_order +
version +
system_id +
class_id +
num_property_sets +
format_id +
offset +
size +
num_property +
property_offsets +
property_data
end
###############################################################################
#
# Create the DocSummaryInformation property set. This is mainly used for the
# Manager, Company and Category keywords.
#
# The DocSummary also contains a stream for user defined properties. However
# this is a little arcane and probably not worth the implementation effort.
#
def create_doc_summary_property_set(properties) #:nodoc:
byte_order = [0xFFFE].pack('v')
version = [0x0000].pack('v')
system_id = [0x00020105].pack('V')
class_id = ['00000000000000000000000000000000'].pack('H*')
num_property_sets = [0x0002].pack('V')
format_id_0 = ['02D5CDD59C2E1B10939708002B2CF9AE'].pack('H*')
format_id_1 = ['05D5CDD59C2E1B10939708002B2CF9AE'].pack('H*')
offset_0 = [0x0044].pack('V')
num_property_0 = [properties.size].pack('V')
property_offsets_0 = ''
# Create the property set data block and calculate the offsets into it.
property_data_0, offsets = pack_property_data(properties)
# Create the property type and offsets based on the previous calculation.
0.upto(properties.size-1) do |i|
property_offsets_0 += [properties[i][0], offsets[i]].pack('VV')
end
# Size of size (4 bytes) + num_property (4 bytes) + the data structures.
data_len = 8 + (property_offsets_0).bytesize + property_data_0.bytesize
size_0 = [data_len].pack('V')
# The second property set offset is at the end of the first property set.
offset_1 = [0x0044 + data_len].pack('V')
# We will use a static property set stream rather than try to generate it.
property_data_1 = [%w(
98 00 00 00 03 00 00 00 00 00 00 00 20 00 00 00
01 00 00 00 36 00 00 00 02 00 00 00 3E 00 00 00
01 00 00 00 02 00 00 00 0A 00 00 00 5F 50 49 44
5F 47 55 49 44 00 02 00 00 00 E4 04 00 00 41 00
00 00 4E 00 00 00 7B 00 31 00 36 00 43 00 34 00
42 00 38 00 33 00 42 00 2D 00 39 00 36 00 35 00
46 00 2D 00 34 00 42 00 32 00 31 00 2D 00 39 00
30 00 33 00 44 00 2D 00 39 00 31 00 30 00 46 00
41 00 44 00 46 00 41 00 37 00 30 00 31 00 42 00
7D 00 00 00 00 00 00 00 2D 00 39 00 30 00 33 00
).join('')].pack('H*')
byte_order +
version +
system_id +
class_id +
num_property_sets +
format_id_0 +
offset_0 +
format_id_1 +
offset_1 +
size_0 +
num_property_0 +
property_offsets_0 +
property_data_0 +
property_data_1
end
###############################################################################
#
# _pack_property_data().
#
# Create a packed property set structure. Strings are null terminated and
# padded to a 4 byte boundary. We also use this function to keep track of the
# property offsets within the data structure. These offsets are used by the
# calling functions. Currently we only need to handle 4 property types:
# VT_I2, VT_LPSTR, VT_FILETIME.
#
def pack_property_data(properties, offset = 0) #:nodoc:
packed_property = ''
data = ''
offsets = []
# Get the strings codepage from the first property.
codepage = properties[0][2]
# The properties start after 8 bytes for size + num_properties + 8 bytes
# for each propety type/offset pair.
offset += 8 * (properties.size + 1)
properties.each do |property|
offsets.push(offset)
property_type = property[1]
if property_type == 'VT_I2'
packed_property = pack_VT_I2(property[2])
elsif property_type == 'VT_LPSTR'
packed_property = pack_VT_LPSTR(property[2], codepage)
elsif property_type == 'VT_FILETIME'
packed_property = pack_VT_FILETIME(property[2])
else
raise "Unknown property type: '#{property_type}'\n"
end
offset += packed_property.bytesize
data += packed_property
end
[data, offsets]
end
###############################################################################
#
# _pack_VT_I2().
#
# Pack an OLE property type: VT_I2, 16-bit signed integer.
#
def pack_VT_I2(value) #:nodoc:
type = 0x0002
data = [type, value].pack('VV')
end
###############################################################################
#
# _pack_VT_LPSTR().
#
# Pack an OLE property type: VT_LPSTR, String in the Codepage encoding.
# The strings are null terminated and padded to a 4 byte boundary.
#
def pack_VT_LPSTR(str, codepage) #:nodoc:
type = 0x001E
string =
ruby_18 { "#{str}\0" } ||
ruby_19 { str.force_encoding('BINARY') + "\0".encode('BINARY') }
if codepage == 0x04E4
# Latin1
length = string.bytesize
elsif codepage == 0xFDE9
# utf8
length = string.bytesize
else
raise "Unknown codepage: #{codepage}\n"
end
# Pack the data.
data = [type, length].pack('VV')
data += string
# The packed data has to null padded to a 4 byte boundary.
if (extra = length % 4) != 0
data += "\0" * (4 - extra)
end
data
end
###############################################################################
#
# _pack_VT_FILETIME().
#
# Pack an OLE property type: VT_FILETIME.
#
def pack_VT_FILETIME(localtime) #:nodoc:
type = 0x0040
epoch = DateTime.new(1601, 1, 1)
t = localtime.getgm
datetime = DateTime.new(
t.year,
t.mon,
t.mday,
t.hour,
t.min,
t.sec,
t.usec
)
bignum = (datetime - epoch) * 86400 * 1e7.to_i
high, low = bignum.divmod 1 << 32
[type].pack('V') + [low, high].pack('V2')
end
|
theletterf/ruby-rails-instrumentation
|
spec/subscribers/action_controller_subscriber_spec.rb
|
require 'spec_helper'
RSpec.describe Rails::Instrumentation::ActionControllerSubscriber do
let(:tracer) { OpenTracingTestTracer.build }
before { allow(Rails::Instrumentation).to receive(:tracer).and_return(tracer) }
describe 'Class Methods' do
it 'responds to all event methods' do
test_class_events(described_class)
end
end
context 'when calling event method' do
before { tracer.spans.clear }
describe 'write_fragment' do
let(:event) { ::ActiveSupport::Notifications::Event.new('write_fragment.action_controller', Time.now, Time.now, 0, {}) }
it 'adds tags' do
described_class.write_fragment(event)
expected_keys = %w[key.write]
check_span(expected_keys, tracer.spans.last)
end
end
describe 'read_fragment' do
let(:event) { ::ActiveSupport::Notifications::Event.new('read_fragment.action_controller', Time.now, Time.now, 0, {}) }
it 'adds tags' do
described_class.read_fragment(event)
expected_keys = %w[key.read]
check_span(expected_keys, tracer.spans.last)
end
end
describe 'expire_fragment' do
let(:event) { ::ActiveSupport::Notifications::Event.new('expire_fragment.action_controller', Time.now, Time.now, 0, {}) }
it 'adds tags' do
described_class.expire_fragment(event)
expected_keys = %w[key.expire]
check_span(expected_keys, tracer.spans.last)
end
end
describe 'exist_fragment?' do
let(:event) { ::ActiveSupport::Notifications::Event.new('exist_fragment?.action_controller', Time.now, Time.now, 0, {}) }
it 'adds tags' do
described_class.exist_fragment?(event)
expected_keys = %w[key.exist]
check_span(expected_keys, tracer.spans.last)
end
end
describe 'write_page' do
let(:event) { ::ActiveSupport::Notifications::Event.new('write_page.action_controller', Time.now, Time.now, 0, {}) }
it 'adds tags' do
described_class.write_page(event)
expected_keys = %w[path.write]
check_span(expected_keys, tracer.spans.last)
end
end
describe 'expire_page' do
let(:event) { ::ActiveSupport::Notifications::Event.new('expire_page.action_controller', Time.now, Time.now, 0, {}) }
it 'adds tags' do
described_class.expire_page(event)
expected_keys = %w[path.expire]
check_span(expected_keys, tracer.spans.last)
end
end
describe 'start_processing' do
let(:event) { ::ActiveSupport::Notifications::Event.new('start_processing.action_controller', Time.now, Time.now, 0, {}) }
it 'adds tags' do
described_class.start_processing(event)
expected_keys = %w[controller controller.action request.params request.format http.method http.url]
check_span(expected_keys, tracer.spans.last)
end
end
describe 'process_action' do
let(:event) { ::ActiveSupport::Notifications::Event.new('process_action.action_controller', Time.now, Time.now, 0, {}) }
it 'adds tags' do
described_class.process_action(event)
expected_keys = %w[controller controller.action request.params request.format http.method http.url http.status_code view.runtime.ms db.runtime.ms]
check_span(expected_keys, tracer.spans.last)
end
end
describe 'process_action_exception' do
let(:event) { ::ActiveSupport::Notifications::Event.new('process_action.action_controller', Time.now, Time.now, 0, {:exception => ["ArgumentError", "Invalid value"], :exception_object => ArgumentError.new("Invalid value")}) }
it 'adds tags' do
described_class.process_action(event)
expected_keys = %w[controller controller.action error request.params request.format http.method http.url http.status_code view.runtime.ms db.runtime.ms]
check_span(expected_keys, tracer.spans.last)
end
end
describe 'process_action_status_code' do
let(:event) { ::ActiveSupport::Notifications::Event.new('process_action.action_controller', Time.now, Time.now, 0, {:status => 503}) }
it 'adds tags' do
described_class.process_action(event)
expected_keys = %w[controller controller.action error request.params request.format http.method http.url http.status_code view.runtime.ms db.runtime.ms]
check_span(expected_keys, tracer.spans.last)
end
end
describe 'send_file' do
let(:event) { ::ActiveSupport::Notifications::Event.new('send_file.action_controller', Time.now, Time.now, 0, {}) }
it 'adds tags' do
described_class.send_file(event)
expected_keys = %w[path.send]
check_span(expected_keys, tracer.spans.last)
end
end
# describe 'send_data' do
# let(:event) { ::ActiveSupport::Notifications::Event.new('send_data.action_controller', Time.now, Time.now, 0, {})}
# it 'adds tags' do
# described_class.send_data(event)
# check_span(expected_keys, tracer.spans.last)
# end
# end
describe 'redirect_to' do
let(:event) { ::ActiveSupport::Notifications::Event.new('redirect_to.action_controller', Time.now, Time.now, 0, {}) }
it 'adds tags' do
described_class.redirect_to(event)
expected_keys = %w[http.status_code redirect.url]
check_span(expected_keys, tracer.spans.last)
end
end
describe 'halted_callback' do
let(:event) { ::ActiveSupport::Notifications::Event.new('halted_callback.action_controller', Time.now, Time.now, 0, {}) }
it 'adds tags' do
described_class.halted_callback(event)
expected_keys = %w[filter]
check_span(expected_keys, tracer.spans.last)
end
end
describe 'unpermitted_parameters' do
let(:event) { ::ActiveSupport::Notifications::Event.new('unpermitted_parameters.action_controller', Time.now, Time.now, 0, {}) }
it 'adds tags' do
described_class.unpermitted_parameters(event)
expected_keys = %w[unpermitted_keys]
check_span(expected_keys, tracer.spans.last)
end
end
end
end
|
theletterf/ruby-rails-instrumentation
|
spec/subscribers/active_record_subscriber_spec.rb
|
require 'spec_helper'
RSpec.describe Rails::Instrumentation::ActiveRecordSubscriber do
let(:tracer) { OpenTracingTestTracer.build }
before { allow(Rails::Instrumentation).to receive(:tracer).and_return(tracer) }
describe 'Class Methods' do
it 'responds to all event methods' do
test_class_events(described_class)
end
end
context 'when calling event method' do
before { tracer.spans.clear }
describe 'sql' do
statement = 'SELECT' * 4096
let(:event) { ::ActiveSupport::Notifications::Event.new('sql.active_record', Time.now, Time.now, 0, sql: statement) }
it 'adds tags' do
described_class.sql(event)
expected_keys = %w[db.statement name connection_id binds cached]
span = tracer.spans.last
check_span(expected_keys, span)
expect(span.tags['db.statement']).to eq(statement[0..1023])
end
end
describe 'instantiation' do
let(:event) { ::ActiveSupport::Notifications::Event.new('instantiation.active_record', Time.now, Time.now, 0, {}) }
it 'adds tags' do
described_class.instantiation(event)
expected_keys = %w[record.count record.class]
check_span(expected_keys, tracer.spans.last)
end
end
end
end
|
theletterf/ruby-rails-instrumentation
|
lib/rails/instrumentation/patch.rb
|
<gh_stars>1-10
module Rails
module Instrumentation
module Patch
def self.patch_process_action(klass: ::ActionController::Instrumentation)
klass.class_eval do
alias_method :process_action_original, :process_action
def process_action(method_name, *args)
# this naming scheme 'class.method' is how we ensure that the notification in the
# subscriber is the same one
name = "#{self.class.name}.#{method_name}"
scope = ::Rails::Instrumentation.tracer.start_active_span(name)
# skip adding tags here. Getting the complete set of information is
# easiest in the notification
process_action_original(method_name, *args)
rescue Error => error
if scope
scope.span.record_exception(error)
end
raise
ensure
scope.close
end
end
end
def self.restore_process_action(klass: ::ActionController::Instrumentation)
klass.class_eval do
remove_method :process_action
alias_method :process_action, :process_action_original
remove_method :process_action_original
end
end
end
end
end
|
theletterf/ruby-rails-instrumentation
|
spec/spec_helper.rb
|
<filename>spec/spec_helper.rb
require 'bundler/setup'
require 'rails/instrumentation'
require 'signalfx_test_tracer'
# require 'rack/test'
RSpec.configure do |config|
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
def test_class_events(subscriber_class)
subscriber_class::EVENTS.each do |event|
expect(subscriber_class).to respond_to event
end
end
def check_span(expected_keys, span)
span_tags = span.tags
expected_keys.each do |key|
expect(span_tags).to have_key(key)
end
end
class TestSubscriber
include Rails::Instrumentation::Subscriber
EVENTS = %w[test_event_1 test_event_2 test_event_3].freeze
EVENT_NAMESPACE = 'test_subscriber'.freeze
class << self
attr_reader :subscribers
end
def self.test_event_1(event); end
def self.test_event_2(event); end
def self.test_event_3(event); end
end
|
theletterf/ruby-rails-instrumentation
|
lib/rails/instrumentation/utils.rb
|
require 'active_support/notifications'
module Rails
module Instrumentation
module Utils
class << self
# calls a handler function with name 'event' on the handler module.
# For example, if the handler module is ActionViewSubscriber and the
# event hook is 'render_template.action_controller', full_name is
# 'render_template.action_controller' and event_name is 'render_template'
def register_subscriber(full_name: '', event_name: '', handler_module: nil)
::ActiveSupport::Notifications.subscribe(full_name) do |*args|
event = ::ActiveSupport::Notifications::Event.new(*args)
handler_module.send(event_name, event)
end
end
# takes and event and some set of tags from a handler, and creates a
# span with the event's name and the start and finish times.
def trace_notification(event:, tags: [])
tags = ::Rails::Instrumentation::TAGS.clone.merge(tags)
span = ::Rails::Instrumentation.tracer.start_span(event.name,
tags: tags,
start_time: event.time)
# tag transaction_id
span.set_tag('transaction.id', event.transaction_id)
tag_error(span, event.payload) if event.payload.key? :exception
span.finish(end_time: event.end)
end
# according to the ActiveSupport::Notifications documentation, exceptions
# will be indicated with the presence of the :exception and :exception_object
# keys. These will be tagged and logged according to the OpenTracing
# specification.
def tag_error(span, payload)
if payload.key? :exception_object
span.record_exception(payload[:exception_object])
else
exception = payload[:exception]
span.set_tag(:error, true)
span.set_tag(:'sfx.error.kind', exception[0])
span.set_tag(:'sfx.error.message', exception[1])
end
end
end
end
end
end
|
jtimberman/chef-handler-updated-resources
|
chef-handler-updated-resources.gemspec
|
<gh_stars>1-10
Gem::Specification.new do |s|
s.name = 'chef-handler-updated-resources'
s.version = '0.2.0'
s.platform = Gem::Platform::RUBY
s.summary = 'Chef report handler to display resources updated in the Chef Run'
s.description = s.summary
s.author = '<NAME>'
s.email = '<EMAIL>'
s.homepage = 'http://github.com/jtimberman/chef-handler-updated-resources'
s.require_path = 'lib'
s.files = %w(LICENSE README.md) + Dir.glob('lib/**/*')
end
|
jtimberman/chef-handler-updated-resources
|
lib/chef/handler/updated_resources.rb
|
#
# Copyright:: 2011, <NAME> <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'chef/handler'
module SimpleReport
class UpdatedResources < Chef::Handler
def initialize(line_prefix=" ")
super()
@line_prefix = line_prefix
end
def report
if run_status.updated_resources
Chef::Log.info "Resources updated this run:"
run_status.updated_resources.each {|r| Chef::Log.info "#{@line_prefix}#{r.to_s}"}
else
Chef::Log.info "No Resources updated this run!"
end
end
end
end
|
J5Wood/flavor-town
|
backend/db/seeds.rb
|
<gh_stars>0
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
n = City.create(name: "New York")
n.restaurants.create(name: "Mario's", style: "Italian", neighborhood: "Little Italy", notes: "Neapolitan, family owned Italian.", top_dishes: ["Spedini ala Romana", "Mario’s epic seafood salad"])
n.restaurants.create(name: "Africa Kine", style: "Senegalese", neighborhood: "Harlem", notes: "Takeout Only.", top_dishes: ["Thiebu Djen", "Mafe", "Yassa"])
n.restaurants.create(name: "<NAME>", style: "Mexican", neighborhood: "The Bronx", notes: "Oaxacan. Amazing Moles.", top_dishes: ["Mole Oaxaqueño", "Molcajete"])
n.restaurants.create(name: "Fieldtrip", style: "American", neighborhood: "Harlem", notes: "Takeout Only.", top_dishes: ["Texas Brown Rice", "Spicy Seafood Gumbo", "hibiscus rice milk soft serve"])
l = City.create(name: "Los Angeles")
l.restaurants.create(name: "Broad Street Oyster Company", style: "Seafood", neighborhood: "Malibu", notes: "Drive thru is an option!", top_dishes: ["Lobster Roll", "Lobster Bisque"])
l.restaurants.create(name: "Lum-Ka-Naad", style: "Thai", neighborhood: "Northridge", notes: "Northern and southern Thai options", top_dishes: ["Gang Jerd Paak Dong Khem", "Yum Ped Yang", "Pladuk Pad Ped"])
l.restaurants.create(name: "Pasjoli", style: "French", neighborhood: "Santa Monica", notes: "Parisian Bistro Dishes", top_dishes: ["Poussin Farci et Champagne", "Steak au Poivre"])
l.restaurants.create(name: "Mizlala", style: "Mediterranean", neighborhood: "Sherman Oaks", notes: "Casual, small plates.", top_dishes: ["Apricot Lamb Tagine", "Grilled Branzino"])
s = City.create(name: "Seattle")
s.restaurants.create(name: "<NAME>", style: "Thai", neighborhood: "Ballard", notes: "Isan Style Thai", top_dishes: ["Kao Soi", "Nam Tok"])
s.restaurants.create(name: "Barrio", style: "Mexican", neighborhood: "Capitol Hill", notes: "Good stop for drinks.", top_dishes: ["Beef Birria Quesadillas", "Tauitos", "Pozole"])
s.restaurants.create(name: "Itto's", style: "Spanish", neighborhood: "West Seattle", notes: "Greate tapas.", top_dishes: ["Tortilla Español", "Berbere Burger"])
s.restaurants.create(name: "<NAME>", style: "Pizza", neighborhood: "Capitol Hill", notes: "Great late night slices.", top_dishes: ["Pepperoni"])
p = City.create(name: "Philadelphia")
|
J5Wood/flavor-town
|
backend/app/serializers/city_serializer.rb
|
<reponame>J5Wood/flavor-town
class CitySerializer
include FastJsonapi::ObjectSerializer
attributes :name, :id
has_many :restaurants
end
|
J5Wood/flavor-town
|
backend/config/routes.rb
|
<filename>backend/config/routes.rb<gh_stars>0
Rails.application.routes.draw do
resources :restaurants
resources :cities do
resources :restaurants, only: [:index]
end
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end
|
J5Wood/flavor-town
|
backend/app/serializers/restaurant_serializer.rb
|
<filename>backend/app/serializers/restaurant_serializer.rb
class RestaurantSerializer
include FastJsonapi::ObjectSerializer
attributes :name, :style, :neighborhood, :notes, :top_dishes, :id
belongs_to :city
end
|
J5Wood/flavor-town
|
backend/app/controllers/cities_controller.rb
|
class CitiesController < ApplicationController
def index
cities = City.all
render json: CitySerializer.new(cities)
end
def create
if city = City.find_by(name: params[:name])
render json: CitySerializer.new(city)
else
city = City.new(city_params)
if city.save
render json: CitySerializer.new(city)
else
render json: {error: "ERROR"}
end
end
end
private
def city_params
params.require(:city).permit(:name, :id)
end
end
|
J5Wood/flavor-town
|
backend/app/models/restaurant.rb
|
<filename>backend/app/models/restaurant.rb
class Restaurant < ApplicationRecord
belongs_to :city
serialize :top_dishes
validates :name, :style, :neighborhood, :notes, presence: true
end
|
J5Wood/flavor-town
|
backend/app/controllers/restaurants_controller.rb
|
<gh_stars>0
class RestaurantsController < ApplicationController
def index
if !!params[:city_id]
city = City.find_by(id: params[:city_id])
restaurants = city.restaurants
else
restaurants = Restaurant.all
end
render json: RestaurantSerializer.new(restaurants)
end
def show
restaurant = Restaurant.find_by(id: params[:id])
render json: restaurant
end
def create
restaurant = Restaurant.new(restaurant_params)
if restaurant.save
render json: RestaurantSerializer.new(restaurant)
else
render json: {error: "ERROR"}
end
end
def update
restaurant = Restaurant.find_by(id: params[:id])
if restaurant.update(restaurant_params)
render json: RestaurantSerializer.new(restaurant)
else
render json: {error: "ERROR"}
end
end
def destroy
restaurant = Restaurant.find_by(id: params[:id])
if restaurant.destroy
render json: {message: "Succesfully deleted #{restaurant.name}"}
else
render json: {error: "ERROR"}
end
end
private
def restaurant_params
params.require(:restaurant).permit(:name, :style, :neighborhood, :notes, :city_id, :top_dishes => [])
end
end
|
PatrickJamesHoban/fido_and_furball
|
config/routes.rb
|
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root 'static_pages#home'
# get 'static_pages/home' # No longer needed as the root route above is the same.
get '/help', to: 'static_pages#help' #, as: 'helf'
get '/about', to: 'static_pages#about'
get '/contact', to: 'static_pages#contact'
# get 'users/new' # This was automatically created when generate was called, changed path to the below.
get '/signup', to: 'users#new'
post '/signup', to: 'users#create'
# allows access to users/1
resources :users
end
|
PatrickJamesHoban/fido_and_furball
|
app/helpers/application_helper.rb
|
module ApplicationHelper
# Returns the full title depending on what is available.
def full_title(custom_title = '', page_title = '')
base_title = "Ellie Farmgirl"
if custom_title.empty?
page_title + ' | ' + base_title
else
custom_title
end
end
end
|
PatrickJamesHoban/fido_and_furball
|
app/controllers/application_controller.rb
|
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
# def hello
# render html: 'Coming soon... Fido and Furball, the greatest thing to ever happen for pets! - An Ellie Farmgirl, <NAME> and <NAME> Production'
# end
end
|
twei55/simple-bookshelf
|
db/migrate/20120622140404_create_groups.rb
|
class CreateGroups < ActiveRecord::Migration
def up
create_table :groups do |t|
t.string :name
t.timestamps
end
add_column :users, :group_id, :integer
add_column :admins, :group_id, :integer
end
def down
drop_table :groups
remove_column :users, :group_id
remove_column :admins, :group_id
end
end
|
twei55/simple-bookshelf
|
db/migrate/20120516165837_add_delta_index_to_books.rb
|
class AddDeltaIndexToBooks < ActiveRecord::Migration
def up
add_column :books, :delta, :boolean, :default => true, :null => false
end
def down
remove_column :books, :delta
end
end
|
twei55/simple-bookshelf
|
spec/requests/signin_spec.rb
|
<gh_stars>0
# encoding: utf-8
require 'spec_helper'
describe "signin" do
let(:admin) { FactoryGirl.create(:admin, :group => Group.first) }
let(:user) { FactoryGirl.create(:user, :group => Group.first) }
it "signs me in as admin" do
visit new_user_session_path
fill_in("user_email", :with => admin.email)
fill_in("user_password", :with => <PASSWORD>)
click_button("Einloggen")
find('ul.nav li', :text => "Suche")
find('ul.nav li', :text => "Titel anlegen")
find('ul.nav li', :text => "Schlagwörter")
find('ul.nav li', :text => "Publikationsarten")
find('ul.nav li', :text => "Ausloggen")
end
it "signs me in as user" do
visit new_user_session_path
fill_in("user_email", :with => user.email)
fill_in("user_password", :with => <PASSWORD>)
click_button("Einloggen")
expect {find('ul.nav li', :text => "Titel anlegen")}.to raise_exception(Capybara::ElementNotFound)
expect {find('ul.nav li', :text => "Schlagwörter")}.to raise_exception(Capybara::ElementNotFound)
expect {find('ul.nav li', :text => "Publikationsarten")}.to raise_exception(Capybara::ElementNotFound)
find('ul.nav li', :text => "Suche")
find('ul.nav li', :text => "Ausloggen")
end
end
|
twei55/simple-bookshelf
|
db/migrate/20120323161637_create_books_formats_join_table.rb
|
<gh_stars>0
class CreateBooksFormatsJoinTable < ActiveRecord::Migration
def up
create_table :books_formats, :id => false, :force => true do |t|
t.column :book_id, :integer
t.column :format_id, :integer
t.timestamps
end
end
def down
drop_table :books_formats
end
end
|
twei55/simple-bookshelf
|
db/schema.rb
|
# encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
ActiveRecord::Schema.define(:version => 20120623134245) do
create_table "authors", :force => true do |t|
t.string "first_name"
t.string "last_name", :null => false
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.string "full_name"
t.string "full_name_reversed"
end
create_table "book_authors", :force => true do |t|
t.integer "author_id"
t.integer "book_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "books", :force => true do |t|
t.string "title", :null => false
t.string "year", :null => false
t.string "publisher", :null => false
t.text "abstract"
t.text "location"
t.boolean "publisher_is_author"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.string "document_file_name"
t.string "document_content_type"
t.integer "document_file_size"
t.datetime "document_updated_at"
t.boolean "delta", :default => true, :null => false
end
create_table "books_formats", :id => false, :force => true do |t|
t.integer "book_id"
t.integer "format_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
add_index "books_formats", ["book_id"], :name => "index_books_formats_on_book_id"
add_index "books_formats", ["format_id"], :name => "index_books_formats_on_format_id"
create_table "books_nested_tags", :id => false, :force => true do |t|
t.integer "book_id"
t.integer "nested_tag_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
add_index "books_nested_tags", ["book_id"], :name => "index_books_nested_tags_on_book_id"
add_index "books_nested_tags", ["nested_tag_id"], :name => "index_books_nested_tags_on_nested_tag_id"
create_table "entries", :force => true do |t|
t.integer "book_id"
t.integer "group_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "formats", :force => true do |t|
t.string "name", :null => false
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "groups", :force => true do |t|
t.string "name"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "nested_tags", :force => true do |t|
t.string "name", :null => false
t.integer "parent_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "users", :force => true do |t|
t.string "email", :default => "", :null => false
t.string "encrypted_password", :default => "", :null => false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", :default => 0
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "group_id"
t.boolean "admin", :default => false
t.string "confirmation_token"
t.datetime "confirmed_at"
t.datetime "confirmation_sent_at"
t.string "unconfirmed_email"
end
add_index "users", ["email"], :name => "index_users_on_email", :unique => true
add_index "users", ["reset_password_token"], :name => "index_users_on_reset_password_token", :unique => true
end
|
twei55/simple-bookshelf
|
config/environment.rb
|
# Load the rails application
require File.expand_path('../application', __FILE__)
# Initialize the rails application
SimpleBookshelf::Application.initialize!
Encoding.default_external = "UTF-8"
# http://groups.google.com/group/thinking-sphinx/browse_thread/thread/66d0cbef8697dd60/76810ccee253ffe9
ThinkingSphinx.updates_enabled = true
ThinkingSphinx.deltas_enabled = true
ThinkingSphinx.suppress_delta_output = true
|
twei55/simple-bookshelf
|
spec/requests/update_book_spec.rb
|
# encoding: utf-8
require 'spec_helper'
describe "create book" do
let(:admin) { FactoryGirl.create(:admin, :group => Group.first) }
let(:user) { FactoryGirl.create(:user, :group => Group.first) }
before(:each) do
visit new_user_session_path
fill_in("user_email", :with => admin.email)
fill_in("user_password", :with => <PASSWORD>)
click_button("Einloggen")
end
it "updates index successfully" do
visit edit_book_path(Book.first.id)
fill_in("book_title", :with => "My updated title")
select("Bildung", :from => "book_nested_tag_ids")
fill_in("book_authors_attributes_0_first_name", :with => "Arjen")
fill_in("book_authors_attributes_0_last_name", :with => "Robben")
click_button("Titel aktualisieren")
page.should have_content("My updated title")
page.should have_content("<NAME>")
end
end
|
twei55/simple-bookshelf
|
app/controllers/nested_tags_controller.rb
|
# encoding: utf-8
class NestedTagsController < ApplicationController
before_filter :authenticate_admin
before_filter :delete_tags_fragment, :only => [:create, :update,:destroy]
before_filter :delete_tags_in_use_fragment, :only => [:update,:destroy]
def index
@nested_tag = NestedTag.new
end
def create
@nested_tag = NestedTag.new(params[:nested_tag])
@nested_tag.parent_id = 0 if params[:nested_tag][:parent_id].blank?
if (@nested_tag.save)
flash[:notice] = I18n.t("sb.flash.notices.create_tag_success")
else
flash[:error] = I18n.t("sb.flash.errors.create_tag_error")
end
redirect_to keywords_path
end
def update
if (params[:book] && params[:book][:nested_tag_ids])
@nt = NestedTag.find(params[:book][:nested_tag_ids][0])
@nt.update_attributes(params[:nested_tag])
flash[:notice] = I18n.t("sb.flash.notices.update_tag_success")
else
flash[:error] = I18n.t("sb.flash.errors.update_tag_error")
end
redirect_to keywords_path
end
def destroy
if (params[:book] && params[:book][:nested_tag_ids])
@nt = NestedTag.find(params[:book][:nested_tag_ids][0])
@nt.destroy
flash[:notice] = I18n.t("sb.flash.notices.delete_tag_success")
else
flash[:error] = I18n.t("sb.flash.errors.delete_tag_error")
end
redirect_to keywords_path
end
private
def delete_tags_fragment
expire_fragment(:controller => "books",
:action => "new",
:action_suffix => 'tag_selection')
end
def delete_tags_in_use_fragment
expire_fragment(:controller => "books",
:action => "new",
:action_suffix => 'tag_in_use_selection')
end
end
|
twei55/simple-bookshelf
|
db/migrate/20120323140925_create_authors.rb
|
<reponame>twei55/simple-bookshelf<gh_stars>0
class CreateAuthors < ActiveRecord::Migration
def up
create_table :authors do |t|
t.string :first_name
t.string :last_name, :null => false
t.timestamps
end
end
def down
drop_table :authors
end
end
|
twei55/simple-bookshelf
|
spec/factories/groups.rb
|
# encoding: utf-8
FactoryGirl.define do
factory :group1, :class => Group do
name "Gruppe 1"
end
factory :group2, :class => Group do
name "Gruppe 2"
end
end
|
twei55/simple-bookshelf
|
db/migrate/20120413102244_add_attachment_document_to_books.rb
|
<reponame>twei55/simple-bookshelf
class AddAttachmentDocumentToBooks < ActiveRecord::Migration
def self.up
add_column :books, :document_file_name, :string
add_column :books, :document_content_type, :string
add_column :books, :document_file_size, :integer
add_column :books, :document_updated_at, :datetime
end
def self.down
remove_column :books, :document_file_name
remove_column :books, :document_content_type
remove_column :books, :document_file_size
remove_column :books, :document_updated_at
end
end
|
twei55/simple-bookshelf
|
app/controllers/users/registrations_controller.rb
|
class Users::RegistrationsController < Devise::RegistrationsController
def create
build_resource
resource.try(:add_to_group, params[:group])
if resource.save
if resource.active_for_authentication?
set_flash_message :notice, :signed_up if is_navigational_format?
sign_in(resource_name, resource)
respond_with resource, :location => after_sign_up_path_for(resource)
else
set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_navigational_format?
expire_session_data_after_sign_in!
respond_with resource, :location => after_inactive_sign_up_path_for(resource)
end
else
clean_up_passwords resource
respond_with resource
end
end
end
|
twei55/simple-bookshelf
|
db/migrate/20120418195637_add_full_name_to_authors.rb
|
<gh_stars>0
class AddFullNameToAuthors < ActiveRecord::Migration
def up
add_column :authors, :full_name, :string
add_column :authors, :full_name_reversed, :string
end
def down
remove_column :authors, :full_name
remove_column :authors, :full_name_reversed
end
end
|
twei55/simple-bookshelf
|
spec/models/format_spec.rb
|
<reponame>twei55/simple-bookshelf<gh_stars>0
require 'spec_helper'
describe Format do
end
|
twei55/simple-bookshelf
|
db/migrate/20120511100424_create_book_authors.rb
|
<reponame>twei55/simple-bookshelf<filename>db/migrate/20120511100424_create_book_authors.rb
class CreateBookAuthors < ActiveRecord::Migration
def up
create_table :book_authors, :force => true do |t|
t.integer :author_id
t.integer :book_id
t.timestamps
end
end
def down
drop_table :book_authors
end
end
|
twei55/simple-bookshelf
|
app/models/user.rb
|
<reponame>twei55/simple-bookshelf
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
belongs_to :group
validates_presence_of :group, :message => I18n.t("sb.user.validations.group_missing")
def add_to_group(params)
return if params["id"].present? && params["name"].present?
if params["id"] && params["id"].present?
self.group = Group.find(params["id"])
end
if params["name"] && params["name"].present?
group = Group.create(:name => params["name"])
self.group = group
self.admin = true
end
end
end
|
twei55/simple-bookshelf
|
spec/requests/registration_spec.rb
|
<reponame>twei55/simple-bookshelf
# encoding: utf-8
require 'spec_helper'
describe "registration process" do
it "should redirect back to form if no group is selected" do
visit new_user_registration_path
fill_in("user_email", :with => "<EMAIL>")
fill_in("user_password", :with => "<PASSWORD>")
fill_in("user_password_confirmation", :with => "<PASSWORD>")
click_button("Registrieren")
current_path.should == user_registration_path
page.should have_content(I18n.t("sb.user.validations.group_missing"))
end
it "should redirect back to form if group is selected and group name is filled in" do
visit new_user_registration_path
fill_in("user_email", :with => "<EMAIL>")
fill_in("user_password", :with => "<PASSWORD>")
fill_in("user_password_confirmation", :with => "<PASSWORD>")
select("Gruppe 1", :form => "group_id")
fill_in("group_name", :with => "Neue Gruppe")
click_button("Registrieren")
current_path.should == user_registration_path
page.should have_content(I18n.t("sb.user.validations.group_missing"))
end
it "should register successfully when group is selected" do
visit new_user_registration_path
fill_in("user_email", :with => "<EMAIL>")
fill_in("user_password", :with => "<PASSWORD>")
fill_in("user_password_confirmation", :with => "<PASSWORD>")
select("Gruppe 1", :form => "group_id")
click_button("Registrieren")
current_path.should == new_user_session_path
end
it "should register successfully when group name is filled in" do
visit new_user_registration_path
fill_in("user_email", :with => "<EMAIL> <EMAIL>")
fill_in("user_password", :with => "<PASSWORD>")
fill_in("user_password_confirmation", :with => "<PASSWORD>")
fill_in("group_name", :with => "Neue Gruppe")
click_button("Registrieren")
current_path.should == new_user_session_path
end
end
|
twei55/simple-bookshelf
|
spec/controllers/formats_controller_spec.rb
|
require 'spec_helper'
describe FormatsController do
end
|
twei55/simple-bookshelf
|
spec/requests/visit_all_pages_spec.rb
|
# encoding: utf-8
require 'spec_helper'
describe "visit all pages" do
let(:admin) { FactoryGirl.create(:admin, :group => Group.first) }
it "raises no errors when visiting pages" do
visit new_user_session_path
fill_in("user_email", :with => admin.email)
fill_in("user_password", :with => <PASSWORD>)
click_button("Einloggen")
expect {visit books_path}.to_not raise_error
expect {visit new_book_path}.to_not raise_error
expect {visit keywords_path}.to_not raise_error
expect {visit formats_path}.to_not raise_error
end
end
|
twei55/simple-bookshelf
|
spec/requests/create_new_book_spec.rb
|
# encoding: utf-8
require 'spec_helper'
describe "create book" do
let(:admin) { FactoryGirl.create(:admin, :group => Group.first) }
let(:user) { FactoryGirl.create(:user, :group => Group.first) }
before(:each) do
visit new_user_session_path
fill_in("user_email", :with => admin.email)
fill_in("user_password", :with => <PASSWORD>)
click_button("Einloggen")
end
it "redirects to new action when form is submitted empty" do
visit new_book_path
click_button("Titel speichern")
page.has_text?("Neuen Titel anlegen").should be_true
end
it "redirects to new action when author is missing" do
visit new_book_path
fill_in("book_title", :with => "something")
fill_in("book_year", :with => "2012")
fill_in("book_publisher", :with => "some publisher")
click_button("Titel speichern")
page.has_text?("Neuen Titel anlegen").should be_true
end
context "Creation of new book succeeds" do
context "if books has an author" do
before(:each) do
visit new_book_path
fill_in("book_title", :with => "My new title")
fill_in("book_year", :with => "2012")
fill_in("book_publisher", :with => "some publisher")
fill_in("book_authors_attributes_0_last_name", :with => "lastname")
select("Bildung", :from => "book_nested_tag_ids")
select("Abbildung", :from => "book_nested_tag_ids")
click_button("Titel speichern")
end
it "redirects to books list when required fields have been filled in" do
page.should have_content("Ergebnisliste")
page.should have_content("Am Beispiel meines Bruders")
end
it "finds new book successfully by title" do
visit books_path
fill_in("query", :with => "My new title")
click_button("Suche")
page.should have_content("My new title")
page.should_not have_content("Am Beispiel meines Bruders")
end
it "finds new book successfully by first keyword/tag" do
fill_in("query", :with => "")
select("Bildung", :from => "book_tag")
click_button("Suche")
page.should have_content("My new title")
end
it "finds new book successfully by second keyword/tag" do
fill_in("query", :with => "")
select("Abbildung", :from => "book_tag")
click_button("Suche")
page.should have_content("My new title")
end
end
context "if publisher is author" do
before(:each) do
visit new_book_path
fill_in("book_title", :with => "My new title")
fill_in("book_year", :with => "2012")
fill_in("book_publisher", :with => "some publisher")
find(:xpath, '//input[@id="book_publisher_is_author"]').set(true)
click_button("Titel speichern")
end
it "redirects to books list when required fields have been filled in" do
page.should have_content("Ergebnisliste")
fill_in("query", :with => "My new title")
click_button("Suche")
page.should have_content("My new title")
end
end
end
end
|
twei55/simple-bookshelf
|
app/helpers/books_helper.rb
|
# encoding: utf-8
module BooksHelper
# Taken from Railscast #197
# http://railscasts.com/episodes/197-nested-model-form-part-2?view=asciicast
def add_new_author_fields(f, association)
new_object = f.object.class.reflect_on_association(association).klass.new
fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
render(association.to_s + "/" + association.to_s.singularize + "_fields", :f => builder)
end
end
def add_post_params(params)
blackList = ["action", "controller", "order", "sort", "commit"]
url_params = params["order"] && params["order"].downcase.eql?("asc") ? "&order=desc" : "&order=asc"
url_params += append(params, blackList)
return url_params
end
def append(args, blackList, objectname = nil)
str = ""
args.each do |key, value|
unless blackList.include?(key)
if value.class.eql?(Hash) || value.class.eql?(ActiveSupport::HashWithIndifferentAccess)
str += append(value, blackList, key)
else
if objectname
str += "&#{objectname}[#{key}]=#{value}"
else
str += "&#{key}=#{value}"
end
end
end
end
return str
end
def add_order_arrow(sort, params)
if (params["sort"] && params["sort"].eql?(sort))
(params["order"] && params["order"].present? && params["order"].downcase.eql?("asc")) ? image_tag("icons/bullet_arrow_up.png",:title=>"Sortierung absteigend") : image_tag("icons/bullet_arrow_down.png",:title=>"Sortierung aufsteigend")
end
end
# # Tree select
# # @params
# # filter_unused = Show only tags that are used by at least one book
# #
def tree_select(categories, model, name, level=-1, selected="", options={})
option_tags = [[I18n.t("sb.forms.select.blank_option"), ""]]
option_tags = option_tags + add_options(categories, level, options)
select_options = {:id => "#{model}_#{name}"}
select_options[:class] = "span5" if options[:multiple]
select_options[:multiple] = options[:multiple] || false
select_tag("#{model}[#{name}]",
options_for_select(option_tags, selected.to_s),
select_options
)
end
#
# Add all available categories and its children to an array
#
def add_options(categories, level, options={})
option_tags = []
if categories.length > 0
level += 1 # keep position
categories.collect do |cat|
if display_category(cat, options)
# Indentation
indent = ""
(0..level*2).each do |i|
indent << " "
end
option_tags << [indent.html_safe + cat.name, cat.id.to_s]
if cat.children.any?
option_tags = option_tags + add_options(cat.children, level, options)
end
end
end
end
option_tags
end
def display_category(cat, options={})
return true unless options[:filter_unused]
show = cat.books.size > 0
if cat.parent_id = 0
cat.children.each do |subcat|
show = subcat.books.size > 0
break if show
end
end
return show
end
def display_nested_tags(tags)
li_tags = ""
for tag in tags
unless tag.parent.nil?
li_tags << content_tag(:li, "#{tag.parent.name} > ")
end
li_tags << content_tag(:li) do
link_to tag.name, books_path + "?query=&book[tag]=" + tag.id.to_s + "&choices[author]=1", :title => "Suche nach Keyword '#{tag.name}'"
end
end
content_tag(:ul, li_tags.html_safe, :class => "tags")
end
def display_linked_authors(authors)
authors = authors.sort_by { |a| a.last_name.downcase }
linked_authors = authors.map { |author|
link_to(author.full_name_reversed, books_path + "?query=#{author.last_name}&choices[author]=1&choices[publisher]=1", :class => "author", :title => "Suche nach Autor '#{author.last_name}'")
}
linked_authors.any? ? linked_authors.join(", ").html_safe : ""
end
def display_formats(book)
html = book.formats.collect{ |format|
link_to format.name, books_path + "?query=&book[format]=#{format.id}"
}.sort.join(", ")
html ? html.html_safe : "keine"
end
def display_number(i)
params[:page] = 1 unless params[:page]
(i+(Book.per_page*(params[:page].to_i-1))+1).to_s
end
#
# Add a citation in the following format
# author1, author2 (year): title, publisher
#
def cite(book)
citation = String.new
citation << book.authors.map { |a| a.full_name_reversed }.join(" / ")
citation << " (#{book.year}): "
citation << book.title.strip
citation << ", #{book.publisher.strip}"
end
end
|
twei55/simple-bookshelf
|
spec/helpers/books_helper_spec.rb
|
# encoding: utf-8
require 'spec_helper'
# Specs in this file have access to a helper object that includes
# the BooksHelper. For example:
#
# describe BooksHelper do
# describe "string concat" do
# it "concats two strings with spaces" do
# helper.concat_strings("this","that").should == "this that"
# end
# end
# end
describe BooksHelper do
describe '#add_post_params' do
it "adds post params to url 1" do
params = {"query" => "Foo", "choices" => {
"author" => "1", "publisher" => "1", "title" => "1"},
"book" => {"tag" => "123", "format" => "456"},
"sort" => 'title', "order" => "asc"
}
res = helper.add_post_params(params)
res.should == "&order=desc&query=Foo&choices[author]=1&choices[publisher]=1&choices[title]=1&book[tag]=123&book[format]=456"
end
it "adds post params to url 2" do
params = {"query" => "Bar", "choices" => {"author" => "1"},
"book" => {"tag" => "123"},
"sort" => 'publisher', "order" => "desc"
}
res = helper.add_post_params(params)
res.should == "&order=asc&query=Bar&choices[author]=1&book[tag]=123"
end
it "adds post params to url 3" do
params = ActiveSupport::HashWithIndifferentAccess.new
params["utf8"] = "1"
params["query"] = ""
params["commit"] = "Suche"
params["book"] = ActiveSupport::HashWithIndifferentAccess.new
params["book"]["format"] = "11"
params["book"]["tag"] = "51"
res = helper.add_post_params(params)
res.should == "&order=asc&utf8=1&query=&book[format]=11&book[tag]=51"
end
end
describe '#add_order_arrow' do
context "Search direction ASC" do
it "adds correct arrow image" do
params = {"order" => "asc", "sort" => "title"}
res = helper.add_order_arrow('title', params)
res.include?("/images/icons/bullet_arrow_up.png").should be_true
res.include?("Sortierung absteigend").should be_true
end
end
context "Search direction DESC" do
it "adds correct arrow image" do
params = {"order" => "desc", "sort" => "title"}
res = helper.add_order_arrow('title', params)
res.include?("/images/icons/bullet_arrow_down.png").should be_true
res.include?("Sortierung aufsteigend").should be_true
end
end
end
context "Tree select" do
describe '#tree_select' do
it "returns select tag with list of indented options" do
res = helper.tree_select([@tag4], "book", "tags", -1, 0, {:multiple => false, :filter_unused => true})
res.include?("select").should be_true
res.include?("multiple").should be_false
end
it "returns multiple select tag" do
res = helper.tree_select([@tag4], "book", "tags", -1, 0, {:multiple => true, :filter_unused => false})
res.include?("multiple").should be_true
end
end
describe '#add_options' do
it "appends all tags to an array" do
res = helper.add_options([@tag4], -1)
res.should == [
[" #{@tag4.name}", @tag4.id.to_s],
["   #{@tag1.name}", @tag1.id.to_s],
["   #{@tag2.name}", @tag2.id.to_s],
["   #{@tag3.name}", @tag3.id.to_s]
]
end
end
end
describe '#display_category' do
end
describe '#display_nested_tags' do
end
describe '#display_linked_authors' do
it "returns a list of links" do
authors = [FactoryGirl.create(:timm), FactoryGirl.create(:gibson)]
res = helper.display_linked_authors(authors)
res.should include("/books?query=Gibson&choices[author]=1&choices[publisher]=1")
res.should include("/books?query=Timm&choices[author]=1&choices[publisher]=1")
res.should include("<NAME></a>")
res.should include("<NAME></a>")
end
end
describe '#display_formats' do
end
describe '#display_number' do
end
end
|
twei55/simple-bookshelf
|
db/migrate/20120623134245_add_confirmable_to_users.rb
|
<reponame>twei55/simple-bookshelf
class AddConfirmableToUsers < ActiveRecord::Migration
def up
## Confirmable
add_column :users, :confirmation_token, :string
add_column :users, :confirmed_at, :datetime
add_column :users, :confirmation_sent_at, :datetime
add_column :users, :unconfirmed_email, :string # Only if using reconfirmable
end
def down
remove_column :users, :confirmation_token
remove_column :users, :confirmed_at
remove_column :users, :confirmation_sent_at
remove_column :users, :unconfirmed_email
end
end
|
twei55/simple-bookshelf
|
db/migrate/20120511180037_remove_authors_books_join_table.rb
|
<gh_stars>0
class RemoveAuthorsBooksJoinTable < ActiveRecord::Migration
def up
drop_table :authors_books
end
def down
create_table :authors_books, {:id => false, :force => true} do |t|
t.integer :author_id
t.integer :book_id
t.timestamps
end
end
end
|
twei55/simple-bookshelf
|
db/migrate/20120419085537_add_indexes.rb
|
class AddIndexes < ActiveRecord::Migration
def up
add_index :authors_books, :author_id
add_index :authors_books, :book_id
add_index :books_formats, :book_id
add_index :books_formats, :format_id
add_index :books_nested_tags, :book_id
add_index :books_nested_tags, :nested_tag_id
end
def down
remove_index :authors_books, :author_id
remove_index :authors_books, :book_id
remove_index :books_formats, :book_id
remove_index :books_formats, :format_id
remove_index :books_nested_tags, :book_id
remove_index :books_nested_tags, :nested_tag_id
end
end
|
twei55/simple-bookshelf
|
app/models/entry.rb
|
class Entry < ActiveRecord::Base
belongs_to :book
belongs_to :group
end
|
twei55/simple-bookshelf
|
app/controllers/books_controller.rb
|
<gh_stars>0
# encoding : utf-8
class BooksController < ApplicationController
before_filter :authenticate_user_or_admin, :only => [:index, :show]
before_filter :authenticate_admin, :only => [:new, :create, :edit, :update, :destroy]
before_filter :delete_tag_in_use_fragment, :only => [:create, :update, :destroy]
before_filter :delete_new_authors_from_params_hash, :only => [:create, :update]
def index
@books = Book.filter(params, current_person)
@current_tag_id = params[:book] ? params[:book][:tag].to_i : 0
end
def show
@book = Book.find(params[:id])
end
def new
@book = Book.new
@book.authors.build
end
def create
@book = Book.new(params[:book])
@book.groups << current_user.group
if params[:book][:format_ids]
@book.formats << Format.find(params[:book][:format_ids])
end
if params[:book][:nested_tag_ids]
begin
@book.nested_tags << NestedTag.find(params[:book][:nested_tag_ids])
rescue ActiveRecord::RecordNotFound
puts "Ignored tag that can´t be found"
end
end
if (@book.save)
flash[:notice] = I18n.t("sb.flash.notices.create_book_success")
redirect_to books_path
else
flash[:error] = I18n.t("sb.flash.errors.create_book_error")
@book.authors.build
render :action => "new"
end
end
def edit
@book = Book.find(params[:id])
end
def update
@book = Book.find(params[:id])
unless (@book.nil?)
@book.update_attributes(params[:book])
end
if params[:book][:format_ids]
@book.formats.clear
@book.formats << Format.find(params[:book][:format_ids])
end
if params[:book][:nested_tag_ids]
@book.nested_tags.clear
begin
@book.nested_tags << NestedTag.find(params[:book][:nested_tag_ids])
rescue ActiveRecord::RecordNotFound
puts "Ignored tag that can´t be found"
end
end
if (@book.save)
flash[:notice] = I18n.t("sb.flash.notices.update_book_success")
redirect_to books_path
else
flash[:error] = I18n.t("sb.flash.errors.update_book_error")
render :action => "edit"
end
end
def destroy
@book = Book.find(params[:id])
@book.destroy
flash[:notice] = I18n.t("sb.flash.notices.delete_book_success")
redirect_to books_path
end
def destroy_document
@book = Book.find(params[:id])
@book.document = nil
@book.save(:validate => false)
flash[:notice] = I18n.t("sb.flash.notices.delete_attachment_success")
redirect_to edit_book_path(@book)
end
#####
# Actions beyond REST
def similar
@books = Book.similar_title(params[:title])
render :template => "books/similar", :layout => false
end
private
def delete_tag_in_use_fragment
expire_fragment(:controller => "books",
:action => "new",
:action_suffix => 'tag_in_use_selection')
end
def delete_new_authors_from_params_hash
params["book"]["authors_attributes"].delete("new_authors")
end
protected
def authenticate_user_or_admin
unless user_signed_in?
redirect_to new_user_session_path
end
end
end
|
twei55/simple-bookshelf
|
spec/models/book_spec.rb
|
<filename>spec/models/book_spec.rb
# encoding: utf-8
require 'spec_helper'
describe Book do
let(:user1) {
FactoryGirl.create(:user, :group => Group.first)
}
let(:user2) {
FactoryGirl.create(:user, :group => Group.last)
}
describe '.filter' do
context "search" do
it "returns only books of the user´s group" do
params = {:query => "",
:choices => {:author => "1", :title => "1", :publisher => "1"}
}
result = Book.filter(params, user1)
result.should have(10).item
end
it "does not return books when they don´t belong to the user´s group" do
params = {:query => "",
:choices => {:author => "1", :title => "1", :publisher => "1"}
}
result = Book.filter(params, user2)
result.should have(0).item
end
end
context "search for title, author, publisher" do
it "returns two books from author <NAME> and one book called <NAME>" do
params = {:query => "Gibson",
:choices => {:author => "1", :title => "1", :publisher => "1"}
}
result = Book.filter(params, user1)
result.should have(3).item
end
end
context "search for title, author" do
it "returns 2 books with query term in title" do
params = {:query => "Erfindung",
:choices => {:author => "1", :title => "1"},
:book => {:format => "", :tag => ""}
}
result = Book.filter(params, user1)
result.should have(2).item
end
it "returns 2 books with query term (special char) in title" do
params = {:query => "Schlüssel",
:choices => {:author => "1", :title => "1"},
:book => {:format => "", :tag => ""}
}
result = Book.filter(params, user1)
result.should have(2).item
end
end
context "search for title, publisher" do
it "returns 2 books from dtv" do
params = {:query => "dtv",
:choices => { :title => "1", :publisher => "1"}
}
result = Book.filter(params, user1)
result.should have(2).item
end
end
context "search for author, publisher" do
it "returns 3 books from <NAME>" do
params = {:query => "Haruki",
:choices => {:author => "1", :publisher => "1"},
:book => {:format => "", :tag => ""}
}
result = Book.filter(params, user1)
result.should have(3).item
end
end
context "search for author only" do
context "last name" do
it "returns 2 books" do
params = {:query => "Timm",
:choices => {:author => "1"}
}
result = Book.filter(params, user1)
result.should have(2).item
end
end
context "full name" do
it "returns 2 books" do
params = {:query => "<NAME>",
:choices => {:author => "1"}
}
result = Book.filter(params, user1)
result.should have(2).item
end
end
context "full name in opposite order" do
it "returns 2 books" do
params = {:query => "<NAME>",
:choices => {:author => "1"}
}
result = Book.filter(params, user1)
result.should have(2).item
end
end
end
context "search for publisher only" do
it "returns 5 books from Suhrkamp" do
params = {:query => "Suhrkamp",
:choices => {:publisher => "1"}
}
result = Book.filter(params, user1)
result.should have(5).item
end
end
context "search for title only" do
it "returns one book called <NAME>" do
params = {:query => "Gibson",
:choices => {:title => "1"}
}
result = Book.filter(params, user1)
result.should have(1).item
end
end
context "search for tag" do
it "returns three books tagged with 'Alleinerziehende'" do
params = {:query => "",
:book => {:tag => NestedTag.find_by_name("Alleinerziehende").id}
}
result = Book.filter(params, user1)
result.should have(3).item
end
it "returns one book tagged with 'Science'" do
params = {:query => "<NAME>",
:choices => {:title => "1"},
:book => {:tag => NestedTag.find_by_name("Science").id}
}
result = Book.filter(params, user1)
result.should have(1).item
end
end
context "search for format" do
end
end
describe ".build_query_string" do
it "includes author, title and publisher in query" do
params = {:query => "Gibson",
:choices => {
:author => "1", :title => "1", :publisher => "1"
}
}
query_string = Book.build_query_string(params)
query_string.should == '@author_first_name "Gibson" | @author_last_name "Gibson" | @author_full_name "Gibson" | @author_full_name_reversed "Gibson" | @title "Gibson" | @publisher "Gibson"'
end
it "includes author and title in query" do
params = {:query => "ABC",
:choices => {:author => "1", :title => "1"}
}
query_string = Book.build_query_string(params)
query_string.should == '@author_first_name "ABC" | @author_last_name "ABC" | @author_full_name "ABC" | @author_full_name_reversed "ABC" | @title "ABC"'
end
it "includes author in query" do
params = {:query => "<NAME>",
:choices => {:author => "1"}
}
query_string = Book.build_query_string(params)
query_string.should == "@author_first_name \"<NAME>\" | @author_last_name \"<NAME>\" | @author_full_name \"<NAME>\" | @author_full_name_reversed \"<NAME>\""
end
end
describe '.add_conditions' do
it "adds tag_id field to condition hash" do
params = {:query => "", :book => {:tag => "1"}}
conditions = Book.add_conditions(params, user1)
conditions.should have(2).item
conditions.should have_key(:tag_id)
end
it "adds format_id field to condition hash" do
params = {:query => "", :book => {:format => "1"}}
conditions = Book.add_conditions(params, user1)
conditions.should have(2).item
conditions.should have_key(:format_id)
end
it "adds tag_id and format_id field to condition hash" do
params = {:query => "", :book => {:tag => "1", :format => "1"}}
conditions = Book.add_conditions(params, user1)
conditions.should have(3).items
end
end
describe '.get_similar_titles' do
end
context "Creation of books" do
describe 'validation' do
it "makes sure entry is not valid without an author" do
params = {"book" => {
"title" => "Test",
"year" => "2010",
"publisher" => "dtv",
"authors_attributes" => {"0" =>
{"first_name" => "", "last_name" => "", "_destroy"=>"false"}
}
}
}
book = Book.new(params["book"])
book.valid?.should be_false
end
it "makes sure entry is valid when publisher is author" do
params = {"book" => {
"title" => "Test",
"year" => "2010",
"publisher" => "dtv",
"publisher_is_author" => true,
"authors_attributes" => {"0" =>
{"first_name" => "", "last_name" => "", "_destroy"=>"false"}
}
}
}
book = Book.new(params["book"])
book.valid?.should be_true
end
end
end
end
|
twei55/simple-bookshelf
|
spec/factories/books.rb
|
# encoding: utf-8
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :book0, :class => Book do
title "Neuromancer"
year "2001"
publisher "Suhrkamp"
publisher_is_author false
end
factory :book1, :class => Book do
title "<NAME>"
year "2001"
publisher "Suhrkamp"
end
factory :book2, :class => Book do
title "Die Erfindung der Currywurst"
year "2001"
publisher "Suhrkamp"
end
factory :book3, :class => Book do
title "Am Beispiel meines Bruders"
year "2001"
publisher "Suhrkamp"
end
factory :book4, :class => Book do
title "Ich, <NAME>."
year "2001"
publisher "Suhrkamp"
end
factory :book5, :class => Book do
title "<NAME>"
year "2001"
publisher "dtv"
end
factory :book6, :class => Book do
title "<NAME>"
year "2001"
publisher "dtv"
end
factory :book7, :class => Book do
title "Die Erfindung der Bratwurst"
year "2005"
publisher "rowohlt"
end
factory :book8, :class => Book do
title "Der Schlüssel zum Erfolg"
year "2008"
publisher "rororo"
end
factory :book9, :class => Book do
title "Der Schlüssel zum Scheitern"
year "2003"
publisher "rororo"
end
end
|
twei55/simple-bookshelf
|
db/migrate/20120323140859_create_books.rb
|
class CreateBooks < ActiveRecord::Migration
def up
create_table :books, :options => "ENGINE=MyISAM" do |t|
t.string :title, :null => false
t.string :year, :null => false
t.string :publisher, :null => false
t.text :abstract
t.text :location
t.boolean :publisher_is_author
t.timestamps
end
end
def down
drop_table :books
end
end
|
twei55/simple-bookshelf
|
spec/requests/formats_spec.rb
|
# encoding: utf-8
require 'spec_helper'
describe "create, update, delete formats" do
let(:admin) { FactoryGirl.create(:admin, :group => Group.first) }
let(:user) { FactoryGirl.create(:user, :group => Group.first) }
before(:each) do
visit new_user_session_path
fill_in("user_email", :with => admin.email)
fill_in("user_password", :with => <PASSWORD>)
click_button("Einloggen")
end
it "creates a new format" do
visit formats_path
within("div#new-format-form") do
fill_in("format_name", :with => "Exklusion")
end
click_button("Hinzufügen")
find("#format-id-update").has_text?("Exklusion").should be_true
find("#format-id-delete").has_text?("Exklusion").should be_true
end
it "updates an existing format" do
visit formats_path
select('Dossier', :from => "format-id-update")
within("div#update-format-form") do
fill_in("format_name", :with => 'New name')
end
click_button("Aktualisieren")
find("#format-id-update").has_text?("New name").should be_true
find("#format-id-delete").has_text?("New name").should be_true
end
it "deletes an existing format" do
visit formats_path
select('New name', :from => "format-id-delete")
click_button("Löschen")
find("#format-id-update").has_text?("New name").should be_false
find("#format-id-delete").has_text?("New name").should be_false
end
end
|
twei55/simple-bookshelf
|
db/migrate/20120323161237_create_authors_books_join_table.rb
|
class CreateAuthorsBooksJoinTable < ActiveRecord::Migration
def up
create_table :authors_books, {:id => false, :force => true} do |t|
t.integer :author_id
t.integer :book_id
t.timestamps
end
end
def down
drop_table :authors_books
end
end
|
twei55/simple-bookshelf
|
app/models/author.rb
|
class Author < ActiveRecord::Base
################################
### ActiveRecord Associations ##
################################
has_many :book_authors
has_many :books, :through => :book_authors
################################
### ActiveRecord Validations ##
################################
validates_presence_of :last_name, :message => I18n.t("sb.author.validations.last_name_missing")
#############
# Hooks
#############
before_save :set_full_name, :set_full_name_reversed
def set_full_name
if first_name.present?
self[:full_name] = "#{first_name} #{last_name}"
else
self[:full_name] = "#{last_name}"
end
end
def set_full_name_reversed
if first_name.present?
self[:full_name_reversed] = "#{last_name}, #{first_name}"
else
self[:full_name_reversed] = "#{last_name}"
end
end
def self.find_or_create(first,last)
find_by_first_name_and_last_name(first,last) || create(:first_name => first,:last_name => last)
end
end
|
twei55/simple-bookshelf
|
app/controllers/application_controller.rb
|
<reponame>twei55/simple-bookshelf<filename>app/controllers/application_controller.rb<gh_stars>0
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :set_locale
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
def default_url_options(options = {})
{ :locale => I18n.locale }
end
def current_person
current_user || current_admin
end
def authenticate_admin
unless user_signed_in? and current_user.admin?
redirect_to new_user_session_path
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.