]> git.donarmstrong.com Git - bin.git/blob - txt2xls
output cvs error diagnostics and increment overflow
[bin.git] / txt2xls
1 #! /usr/bin/perl
2 # txt2xls turns text files into excel workbooks, and is released
3 # under the terms of the GPL version 2, or any later version, at your
4 # option. See the file README and COPYING for more information.
5 # Copyright 2008 by Don Armstrong <don@donarmstrong.com>.
6 # $Id: perl_script 1153 2008-04-08 00:04:20Z don $
7
8
9 use warnings;
10 use strict;
11
12 use Getopt::Long;
13 use Pod::Usage;
14
15 =head1 NAME
16
17 txt2xls - Turns a (set of) text file(s) into an excel workbook
18
19 =head1 SYNOPSIS
20
21  [options]
22
23  Options:
24   --tsv, -t tab separated value mode (Default)
25   --ssv, -s space separated value mode
26   --csv, -c comma separated value mode
27   --r-mode, -r R mode (Default)
28   --auto-format Auto format (Default)
29   --sci-format Scientific format formatting string (Default 0.00E+0)
30   --max-digits Maximum digits to use for auto-format (Default 4)
31   --debug, -d debugging level (Default 0)
32   --help, -h display this help
33   --man, -m display manual
34
35 =head1 OPTIONS
36
37 =over
38
39 =item B<--auto-format>
40
41 Attempt to automatically format the excel file. Currently, this does
42 nothing for non-numeric entries. For numeric entries, if the number is
43 very large (> 9999), or less than 0.001, but not 0, the cell is put
44 into scientific format (B<--sci-format>, default C<0.00E+0>).
45 Otherwise, the cell is formatted to use at maximum B<--max-digits>
46 (default 4) digits.
47
48 To disable, use B<--no-auto-format>
49
50 =item B<--sci-format>
51
52 Excel format string to use for scientific format. See
53 L<http://office.microsoft.com/en-us/excel-help/number-format-codes-HP005198679.aspx>
54 for details. (Default C<'0.00E+0'>)
55
56 =item B<--max-digits>
57
58 Maximum number digits to display for non-scientific formats. (Default 4)
59
60 =item B<--debug, -d>
61
62 Debug verbosity. (Default 0)
63
64 =item B<--help, -h>
65
66 Display brief useage information.
67
68 =item B<--man, -m>
69
70 Display this manual.
71
72 =back
73
74 =head1 EXAMPLES
75
76
77 =cut
78
79
80 use vars qw($DEBUG);
81
82 use Text::CSV;
83 use Spreadsheet::WriteExcel;
84 use Scalar::Util qw(looks_like_number);
85 use POSIX qw(floor);
86
87 my %options = (debug           => 0,
88                help            => 0,
89                man             => 0,
90                auto_format     => 1,
91                sci_format      => '0.00E+0',
92                max_digits      => 4,
93                remove_name     => [],
94                );
95
96 GetOptions(\%options,
97            'tsv|t',
98            'ssv|s',
99            'csv|c',
100            'auto_format|auto-format!',
101            'sci_format|sci-format=s',
102            'max_digits|max-digits=i',
103            'rmode|r-mode|r!',
104            'remove_name|remove-name=s@',
105            'debug|d+','help|h|?','man|m');
106
107 pod2usage() if $options{help};
108 pod2usage({verbose=>2}) if $options{man};
109
110 $DEBUG = $options{debug};
111
112 my @USAGE_ERRORS;
113 if (0 == grep {exists $options{$_}} qw(tsv ssv csv)) {
114     $options{tsv} = 1
115 }
116 if (1 < grep {exists $options{$_}} qw(tsv ssv csv)) {
117      push @USAGE_ERRORS,"You can only pass one of --tsv, --ssv, or --csv";
118 }
119
120 pod2usage(join("\n",@USAGE_ERRORS)) if @USAGE_ERRORS;
121
122 if (not @ARGV) {
123     # we'll use this as a special indicator to read stdin
124     push @ARGV,undef;
125 }
126
127 my $sep_char = "\t";
128 if ($options{csv}) {
129     $sep_char = ',';
130 }
131 elsif ($options{ssv}) {
132     $sep_char = ' ';
133 }
134
135 my %wb_formats = ();
136 my $csv = Text::CSV->new({sep_char=>$sep_char});
137 my $wb = Spreadsheet::WriteExcel->new(\*STDOUT);
138 for my $file (@ARGV) {
139     my $fh;
140     if (not defined $file) {
141         $fh = \*STDIN;
142         $file = "STDIN";
143     }
144     else {
145         $fh = IO::File->new($file,'r') or
146             die "Unable to open $file for reading: $!";
147     }
148     my $ws_name = $file;
149     foreach my $remove (@{$options{remove_name}}) {
150         $ws_name =~ s{\Q$remove\E}{}g;
151     }
152     $ws_name =~ s{\.[^\.]+$}{}g;
153     $ws_name =~ s/_+/ /g;
154     $ws_name =~ s{[\]:*?\/\] ]+}{ }g;
155     $ws_name =~ s{(?:^\s+|\s+$)}{}g;
156     $ws_name =~ s{^(.{0,31}).*$}{$1};
157     my $ws = $wb->add_worksheet($ws_name) or
158         die "Unable to add worksheet to workbook";
159     my $row = 1;
160     my @header_row;
161     my $overflow = 0;
162     my $r_mode = $options{r_mode} // 0;
163     # set to 1 if we have attempted to autodetect R mode
164     my $r_mode_autodetected = 0;
165     while (<$fh>) {
166         chomp;
167         # parse the line
168         die "Unable to parse line $. of $file: ".$csv->error_diag() unless $csv->parse($_);
169         my @row = $csv->fields();
170         if ($row==1 and not $r_mode_autodetected) {
171             @header_row = @row;
172             $row++;
173             next;
174         }
175         if ($row==2 and not $r_mode_autodetected) {
176             $r_mode_autodetected = 1;
177             if (@row == (@header_row+1)) {
178                 $r_mode = 1 unless exists $options{r_mode} and defined $options{r_mode};
179             }
180             if ($r_mode) {
181                 # R doesn't output headers for rownames
182                 unshift @header_row,'';
183             }
184             output_row(\@header_row,1,$ws,$wb,\%wb_formats,\%options);
185         }
186         if ($row > 65536) { # ok, we're going to overflow here
187             my $t_ws_name = $ws_name;
188             my $maxlen = 31-length('.'.$overflow);
189             $t_ws_name =~ s{^(.{0,$maxlen}).*$}{$1};
190             $ws = $wb->add_worksheet($ws_name.'.'.$overflow);
191             $overflow++;
192             $row=1;
193             output_row(\@header_row,$row,$ws,$wb,\%wb_formats,\%options);
194             $row++;
195         }
196         if ($row==1) {
197             @header_row = @row;
198         }
199         output_row(\@row,$row,$ws,$wb,\%wb_formats,\%options);
200         $row++;
201     }
202 }
203
204 sub output_row{
205     my ($data,$row,$ws,$wb,$formats,$options) = @_;
206     my @columns = ('A'..'Z','AA'..'ZZ');
207     for my $i (0..$#{$data}) {
208         my $format;
209         if ($options->{auto_format}) {
210             if (looks_like_number($data->[$i])) {
211                 my $format_string;
212                 # use scientific format?
213                 if ($data->[$i] != 0 && (abs($data->[$i]) > 9999 ||
214                                          abs($data->[$i]) < 0.001)) {
215                     $format_string = $options->{sci_format};
216                 } else {
217                     $format_string = '0';
218                     my $digits = length(floor(abs($data->[$i])));
219                     if ($options->{max_digits} - $digits > 0 and
220                         abs($data->[$i]) != abs(floor($data->[$i]))) {
221                         # if there are digits left over, use them for
222                         # decimal places, but don't require them
223                         $format_string = $format_string.'.'.('#'x($options->{max_digits} - $digits))
224                     }
225                 }
226                 if (not exists $formats->{$format_string}) {
227                     $formats->{$format_string} =
228                         $wb->add_format();
229                     $formats->{$format_string}->
230                         set_num_format($format_string);
231                 }
232                 $format = $formats->{$format_string};
233             }
234         }
235         $ws->write($columns[$i].$row,$data->[$i],defined $format?$format:())
236     }
237 }
238
239 __END__