summaryrefslogtreecommitdiff
path: root/macros/latex/contrib/exceltex/exceltex
blob: 919a0918f658a99f053f02032c57a5c0f9098403 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
#!/usr/bin/perl -w
# $Id: exceltex 155 2006-04-30 11:25:16Z pez $
#
# helper script for the exceltex latex package. reads contents of
# M$ Excel files using the Spreadsheet::ParseExcel perl module.
#
# (c) 2004-2006 by Hans-Peter Doerr <doerr@cip.physik.uni-freiburg.de>
#
# exceltex is free software. you can redistribute or modify it under
# the terms of the GNU GENERAL PUBLIC LICENSE Version 2. See COPYING for
# details.

use strict;

my $VERSION = "0.5.1";
my $DEBUG   = 0;

# this is the default encoding for all files written by exceltex
my $ENCODING = "latin1";

# some lookup tables
my %L2N;
{ my $i = 1; for ('A' .. 'Z') { $L2N{$_} = $i; ++$i } }

my @N2L;
{ for ('A' .. 'Z') { push(@N2L, $_) } }


#XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
#XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
package util;

#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
sub DEBUG
{
    my ($msg) = @_;

    if ($DEBUG)
    {
	chomp($msg);
	print STDERR "DEBUG: $msg\n";
    }
}


#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
sub cell2xy
{
    my ($cell) = @_;

    $cell = uc($cell);
    return undef if (! ($cell =~ m/^([A-Z]+)([0-9]+)$/));

    # return (column, row)
    return (col2x($1), $2-1);
}


#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
sub xy2cell
{
    my ($x, $y) = @_;

    # is is likely to be slow as hell
    return undef if (! ($x =~ m/^[0-9]+$/g && $y =~ m/^[0-9]+$/g));

    ++$y;
    return x2col($x) .  "$y";
}


#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
sub col2x
{
  my ($l) = @_;

    my $len = length($l);
    my @S   = split //, $l;

    my $n = 0;

    if ($len == 1) { $n =  $L2N{$l} - 1 }
    if ($len == 2) { $n =  26 * $L2N{$S[0]} + $L2N{$S[1]} - 1 }

    return $n;
}


#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
sub x2col
{
    my ($n) = @_;

    return undef if (! $n =~ m/[0-9]+/);
    my $l;
    if ($n > 25) { $l =  $N2L[int($n/26)-1] . $N2L[$n % 26] }
    else { $l =  $N2L[$n] }

    return $l;
}





#XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
#XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
package main;

use strict;
use Getopt::Long;
use Encode;

my $Workbooks = {};     # workbook cache
my $nItems    = 0;      # number of processed items
my $nCells    = 0;      # number of processed cells
my $nTabs     = 0;      # number of processed tabs
my $Warnings  = 0;      # number of warnings

my $Jobname    = "";    # jobname of .tex file
my $inputDir   = "";    # data goes here
my $indexFile  = "";


my $optFormat = 1;  # use formatting?
my $optColor  = 1;  # use colors?
my $optComma  = 0;  # use comma for decimals
my $optFmtSci = 0;  # reformat scientific numbers?
my $ignWarn   = 0;  # ignore warnings?
my $euroSymbol  = "EUR"; # use this for the EUR currency symbol

my $cleanup   = 0;      # cleanup inputDir

my $EXTNS = "excltx";

# read global and local config files
# will be overwritten by commandline options
readConfigFile("$ENV{HOME}/.exceltexrc") if (-f "$ENV{HOME}/.exceltexrc");
readConfigFile(".exceltexrc") if (-f ".exceltexrc");

# handle commandline switches
GetOptions('format!'       => \$optFormat,
	   'color!'        => \$optColor,
	   'comma!'        => \$optComma,
	   'reformat-sn!'  => \$optFmtSci,
	   'p|plain'       => sub{$optFormat=0; $optColor=0; $optFmtSci=0;},
	   'd|debug'       => \$DEBUG,
	   'c|cleanup'     => \$cleanup,
           'e|encoding=s'  => \$ENCODING,
           'o|euro-symbol=s' => \$euroSymbol,
	   'h|help'        => sub{ usage(); exit 0;},
	   'v|version'     => sub{ print "exceltex, version $VERSION\n"; exit 0},
	   'w|ignore-warnings' => \$ignWarn,
	   ) || exit 2;

if (@ARGV == 0) {
    usage();
    exit 2;
}



# encoding of output files
$ENCODING = lc($ENCODING);
if (! ($ENCODING eq "latin1"      ||
       $ENCODING eq "iso-8859-1"  ||
       $ENCODING eq "latin9"      ||
       $ENCODING eq "iso-8859-15" ||
       $ENCODING eq "utf8"))
{
    print STDERR "Unsupported encoding: $ENCODING\n";
    print STDERR "currently supported: iso-8859-1 (latin1), iso-8859-15 "
	. "(latin9), utf8\n";
    exit_error();
}

print "exceltex helper script, version $VERSION\n";


# get jobname from first argument
if ($ARGV[0] =~ m/(\w+)\.tex/g) {
    $Jobname = $1;
}
else { $Jobname = $ARGV[0]; }

if (! defined($Jobname))
{
    print STDERR "can't determine jobname.\n";
    exit_error();
}

util::DEBUG("jobname is: $Jobname\n");


# data from spreadsheet goes here
$inputDir  = $Jobname . '-' . $EXTNS;
$indexFile = $Jobname . '.' . $EXTNS;

# cleanup?
if ($cleanup)
{
    cleanup();
    exit 0;
}

if (! -f $indexFile)
{
    print STDERR "can't read index '$indexFile: $!.\n";
    print STDERR "run latex first to create the index.\n";
    exit_error();
}

# create data dir
if (! -d $inputDir)
{
    if (! mkdir $inputDir)
    {
	print STDERR "can't create data directory '$inputDir': $!\n";
	exit_error();
    }
}


# rock'n'roll
processIndex($indexFile);


# exiting message
if ($Warnings)
{
    print STDERR "exceltex finished with $nItems items ($nCells cells "
	. "and $nTabs tabulars)\n";
    print STDERR "*** not all items proccessed fine, there were "
	. "$Warnings Warnings\n";
    exit 0 if ($ignWarn);
    exit 1;
}
else
{
    print "exceltex successfully finished with $nItems items ($nCells cells "
	. "and $nTabs tabulars)\n";
}

exit 0;



#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
sub exit_error
{
    print STDERR "aborting.\n";
    exit 2;
}

#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
sub usage
{
  print <<__EOF;
exceltex version $VERSION
usage: exceltex [options] file[.tex]
options:
   -h|--help             show this help
   -v|--version          show program version and exit
   -c|--cleanup          remove temporary files created by previous runs
   -w|--ignore-warnings  exit with status zero, even on warnings
   -o|--euro-symbol=sym  use sym for displaying the euro currency symbol [EUR]
   -e|--encoding=enc     set encoding to enc. Currently supported
                         encodings are: latin1, latin9, utf8 [latin1]
   --[no]reformat-sn     (dont) reformat scientific numbers to A X 10^B notation
   --[no]comma           (dont) use comma for decimal numbers
   --[no]format          (dont) use formatting
   --[no]nocolor         (dont) use colors
   -p|--plain            shorthand for --noformat --nocolor --noreformat-sn
__EOF
}


#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
sub readConfigFile
{
    my ($file) = @_;

    open(I, "<$file") || return;
    while(<I>)
    {
	chomp();
	my ($key, $val) = split('=', $_);

	if ($key eq "encoding")        { $ENCODING  = $val }
	elsif ($key eq "reformat-sn")  { $optFmtSci = $val }
	elsif ($key eq "color")        { $optColor  = $val }
	elsif ($key eq "format")       { $optFormat = $val }
	elsif ($key eq "comma")        { $optComma  = $val }
	elsif ($key eq "euro-symbol")  { $euroSymbol = $val }
	elsif ($key eq "plain")        { $optColor=0; $optFormat=0}
	else  { print STDERR "unsupported config option in '$file': "
		    . "$key, ignoring\n"  }
    }
    close(I);
}



#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
sub cleanup
{
    if (-f $indexFile)
    {
	print "removing $indexFile\n";
	unlink($indexFile);
    }
    return if (! defined($inputDir));
    return if (! -d $inputDir);

    print "cleaning up $inputDir/\n";
    unlink <$inputDir/c-*>;
    unlink <$inputDir/t-*>;
}



# read index file, extract data, write to files
#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
sub processIndex
{
    my ($index) = @_;

    if (! open(I, "< $index"))
    {
	print STDERR "can't read index '$index': $!. Run latex first?\n";
	exit_error();
    }

    my $cellrefs = 0;
    while(<I>)
    {
	chomp($_);

	# if cellrefs is switched on, we store data in files with name
	# inputDir/[c,t]-file!sheet!cell
	if ($. == 1 && $_ eq ";cellrefs")
	{
	    print "using cell referencing by name\n";
	    $cellrefs = 1;
	}

	# ignore lines beginning with ;
	next if ($_ =~ m/^;/);

	my $type;
	my $idx = undef;
	my $source;
	my @flags;

	if ($cellrefs == 1) {($type, $source, @flags)       = split(':', $_)}
	else                {($type, $idx, $source, @flags) = split(':', $_)}

	# parse flags
	# not used yet
	if (@flags != 0)
	{
	    my $ok  = 0;
	    foreach (@flags)
	    {
		$ok = 1 if ($_ eq 'plain');
	    }
	    print STDERR "Index '$indexFile' corrupt at line $.: bad flag\n";
	    exit_error();
	}

	if (! defined($source))
	{
	    print STDERR "Index '$indexFile' corrupt at line $.\n";
	    exit_error();
	}

	my ($f, $s, $c1, $c2) = parseSource($source, $type);
	if (! $s)
	{
	    print STDERR "Index '$indexFile' corrupt at line $.\n";
	    exit_error();
	}

	my $string = "";
	if ($type eq 't')
	{
	    $string = getTabString($f, $s, $c1, $c2);
	}
	elsif ($type eq 'c')
	{
	    $string = getCellString($f, $s, $c1);
	}
	else
	{
	    print STDERR "Index '$indexFile' corrupt at line $.: "
		. "unknown $type '$type'\n";
	    exit_error();
	}

	# no need to write empty data
	next if (! defined($string));

	$string = decode_utf8($string, 0);
	$string = encode($ENCODING, $string, 0);

	if (! writeBuf($type, $idx, $string, $source))
	{
	    print STDERR "can't write cell data: $!.\n";
	    exit_error();
	}
    }
    close(I);

    return 1;
}


#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
sub getFile
{
    my $file = $Jobname . ".xls";
    return $file if (-f $file);
    return undef;
}

#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
sub parseSource
{
    my ($string, $type) = @_;

    my @tokens = split('!', $string);

    my $file;
    my $sheet;
    my $cel1;
    my $cel2;

    if ($type eq 'c')
    {
	if (@tokens == 2)
	{
	    $file   = getFile();
	    $sheet  = $tokens[0];
	    $cel1   = $tokens[1];
	}
	elsif (@tokens == 3)
	{
	    $file   = $tokens[0];
	    $sheet  = $tokens[1];
	    $cel1   = $tokens[2];
	}
	else { return  undef; }
    }
    elsif ($type eq 't')
    {
	if (@tokens == 3)
	{
	    $file  = getFile();
	    $sheet = $tokens[0];
	    $cel1  = $tokens[1];
	    $cel2  = $tokens[2];
	}
	elsif (@tokens == 4)
	{
	    $file  = $tokens[0];
	    $sheet = $tokens[1];
	    $cel1  = $tokens[2];
	    $cel2  = $tokens[3];
	}
	else { return undef; }
    }
    else { return (undef, undef, undef, undef); }

    return ($file, $sheet, $cel1, $cel2);
}


#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
sub writeBuf
{
    my ($type, $idx, $string, $source) = @_;
    return 1 if ($string eq "");

    my $wfile;

    if (! defined($idx)) { $wfile = $inputDir . "/" . $type . "-" . $source }
    else                 { $wfile = $inputDir . "/" . $type . "-" . $idx    }

    return 0 if (! open (O, ">$wfile"));
    return 0 if (! print O $string);
    return 0 if (! close(O));
    return 1;
}


#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
sub getWorkbook
{
    my ($file) = @_;

    if (! -f $file) {
	print STDERR "can't read '$file': it does not exists.\n";
	exit_error();
    }

    if (! defined($Workbooks->{$file}))
    {
	my $type = "xls";
	if ($file =~ m/^\w+\.(\w+)$/g) { $type = $1 };

	if ($type eq "xls")
	{
	    print("reading '$file'\n");
	    # readExcel->new() will exit, if anything bad happens
	    $Workbooks->{$file} = readExcel->new($file);
	}
    }

    return $Workbooks->{$file};
}


#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
sub texifyCell
{
    my ($cel) = @_;

    my $MATH   = 0; # wether to enclose string in $$ for math mode
    my $string = $cel->{value};

    return "" if (! defined($string) || $string eq "");

    # escape latex control characters
    $string =~ s/\{/\\\{/g;
    $string =~ s/\}/\\\}/g;
    # escape backslash if not followed by { or }
    $string =~ s/\\(?!({|}))/\\ensuremath\{\\backslash\}/g;
    $string =~ s/#/\\#/g;
    $string =~ s/\$/\\\$/g;
    $string =~ s/%/\\%/g;
    $string =~ s/&/\\&/g;
    $string =~ s/~/\\~/g;
    $string =~ s/_/\\_/g;
    $string =~ s/\^/\{\\verb ^ \}/g;

    # FIXME: needs more testing!
    # hack for EUR sign, works for me but is definetly ugly :(
    # will need some information on how exactly this
    # user-entered formatting stuff works (in excel)
    $string =~ s/\[.+\xac-{0,1}\d{1,3}\]/$euroSymbol/g;  # EUR in currency cells
    $string =~ s/\[.+EUR\]/$euroSymbol/g;                # "
    $string =~ s/.{1,1}\xac/$euroSymbol/g;               # single EUR sign
   

    # use decimal comma if requested
    $string =~ s/(\d)\.(\d)/$1,$2/g if ($optComma == 1);
    
    # reformat scientific numbers if requested
    if ($optFmtSci == 1)
    {
	$MATH =  1 if ($string =~ s/([0-9]+)[eE]([+-][0-9]+)/
		       simplifyScientificNumber($1, $2)/ge);
    }

    # apply cell formatting and colors if not requested otherweise
    $string = applyFormatting($string, $cel, $MATH) if($optFormat == 1);

    # same goes for colors
    $string = applyColor($string, $cel) if ($optColor == 1);

    util::DEBUG "  texified => '$string'";

    return "\$$string\$" if ($MATH);
    return $string;
}


#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
sub applyFormatting
{
    my ($s, $c, $m) = @_;

    # font bold?
    if    ($c->{bold} && $m) { $s = "\\mathbf{$s}"; }
    elsif ($c->{bold})       { $s = "\\textbf{$s}"; }

    # font italic?
    if    ($c->{italic} && $m) { $s = "\\mathit{$s}"; }
    elsif ($c->{italic})       { $s = "\\textit{$s}"; }

    # underlined? striked out?
    $s = "\\uline{$s}" if ($c->{underline});
    $s = "\\sout{$s}"  if ($c->{strikeout});

    return $s;
}


#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
sub applyColor
{
    my ($s, $c) = @_;

    # only evaluate color if it is not black anyway
    if ($c->{color} != 8)
    {
	# convert rrggbb hex color triplet to float rgb
  	$s = "\\textcolor[rgb]{" . colormap($c->{color}) . "}{$s}";
    }

    return $s;
}

#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
sub colormap
{
    my ($color) = @_;

    util::DEBUG("  color => $color\n");

    # get rgb triplet as floats
    return join(', ', map {hex($_)/255.0}
	    unpack('a2a2a2', Spreadsheet::ParseExcel->ColorIdxToRGB($color)));
}



#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
sub simplifyScientificNumber
{
    my ($f, $e) = @_;

    # extract signum
    my $s = substr($e, 0, 1);
    $s = '' if ($s eq "+");

    # remove signum & trailing zeros
    $e =~ s/^[+-]*//;
    $e =~ s/^0*(\d+)/$1/;

    return $f if ($e == 0);
    return sprintf("%s \\times 10^{%s%s}", $f, $s, $e);
}


#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
sub warning
{
    my ($msg) = @_;

    chomp($msg);
    print STDERR "warning: "  . $msg . "\n";
    ++$Warnings;
}


#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
sub getCellString
{
    my ($file, $sheet, $cell) = @_;

    util::DEBUG("get $file -> $sheet -> $cell\n");

    my $w = getWorkbook($file);
    return undef if (! defined($w));

    my ($x, $y) = util::cell2xy($cell);
    if (! defined($x) || ! defined($y)) {
	warning("cell '$cell' is invalid\n");
	return undef;
    }

    my $c = $w->getCell($sheet, $x, $y);
    warning($w->error()) if (! defined($c->{value}));

    ++$nItems;
    ++$nCells;
    return texifyCell($c);
}


#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
sub getTabString
{
    my ($file, $sheet, $cell1, $cell2) = @_;

    # cell1 is upper-left and cell2 is lower-right corner
    # of the selected cell-range
    my ($lfx, $upy) = util::cell2xy($cell1);
    my ($rtx, $loy) = util::cell2xy($cell2);

    if (! defined($lfx))
    {
	warning "cell '$cell1' is invalid\n";
	return undef;
    }
    if (! defined($rtx))
    {
	warning "cell '$cell2' is invlaid\n";
	return undef;
    }

    my $book = getWorkbook($file);
    my $buf;

    my $empty = 1;

    for (my $y = $upy; $y <= $loy; ++$y)
    {
	for (my $x = $lfx; $x <= $rtx; ++$x)
	{
	    my $c = $book->getCell($sheet, $x, $y);

	    warning($book->error()) if (! defined($c));
	    $empty = 0 if(defined($c->{value}));
	    $buf .= texifyCell($c);
	    $buf .= " & " if ($x < $rtx);
	}
	$buf .= " \\\\\n";
    }

    warning("table $cell1!$cell2 is empty\n") if ($empty);

    ++$nItems;
    ++$nTabs;
    return $buf;
}





#XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
#XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
package readExcel;

use strict;
use Spreadsheet::ParseExcel;
use Encode;

#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
sub new
{
    my ($class, $file) = @_;

    my $self = {};
    $self->{ERROR} = "";

    if (! -f $file)
    {
	print STDERR "can't read '$file', it does not exists.\n";
	exit_error();
    }

    $self->{book} = 
    Spreadsheet::ParseExcel::Workbook->Parse($file);

    if (! defined($self->{book}))
    {
	print STDERR "SpreadSheet::ParseExcel Error: "
	    . "can't parse '$file' : $!\n";
	exit_error();
    }

    $self->{file} = $file;
    bless $self, $class;

    return $self;
}


#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
sub getCell
{
    my ($self, $sheet, $x, $y) = @_;

    my $ws = $self->{book}->Worksheet($sheet);
    if (! defined($ws))
    {
	$self->_setError("sheet '$sheet' does not exist");
	return undef;
    }

    my $cell = $ws->Cell($y, $x);

    if(! $cell)
    {
	$self->_setError("cell '$sheet!" . util::xy2cell($x, $y) . "' is emtpy "
			 . "or out of range");

	return { value => undef }
    }

    # we're internally operating with utf8, for now
    my $value = encode_utf8($cell->Value());
    util::DEBUG "  value => '$value'";

    # return hash containing value and formatting
    return { value     => $value,
	     bold      => $cell->{Format}->{Font}->{Bold},
	     italic    => $cell->{Format}->{Font}->{Italic},
	     color     => $cell->{Format}->{Font}->{Color},
	     underline => $cell->{Format}->{Font}->{Underline},
	     strikeout => $cell->{Format}->{Font}->{Strikeout}
	   };
}


#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
sub _setError
{
    my ($self, $err) = @_;
    $self->{ERROR} = $err;
}


#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
sub error
{
    my $self = shift;
    my $err = $self->{ERROR};
    $self->{ERROR} = undef;
    return $err;
}