Debian Codegraph @

examples/csv2xls

raw
1 #!/pro/bin/perl
2
3 # csv2xls: Convert csv to xls
4 # (m)'23 [14 Nov 2023] Copyright H.M.Brand 2007-2026
5
6 use 5.012000;
7 use warnings;
8
9 our $VERSION = "1.81";
10
11 sub usage {
12 my $err = shift and select STDERR;
13 print <<"EOU";
14 usage: csv2xls [-s <sep>] [-q <quot>] [-w <width>] [-d <dtfmt>]
15 [-o <xls>] [file.csv]
16 -s <sep> use <sep> as seperator char, auto-detect, default = ','
17 The string "tab" is allowed.
18 -e <esc> use <esc> as escape char, auto-detect, default = '"'
19 The string "undef" is allowed.
20 -q <quot> use <quot> as quotation char, default = '"'
21 The string "undef" will disable quotation.
22 -w <width> use <width> as default minimum column width default = 4
23 -o <xls> write output to file named <xls>, defaults
24 to input file name with .csv replaced with .xls
25 if from standard input, defaults to csv2xls.xls
26 -F allow formula's. Otherwise fields starting with
27 an equal sign are forced to string
28 --Fa=aaa Define formula action: die/croak/diag/empty/undef
29 --Fd Formula's will cause a die
30 --Fc Formula's will cause a croak
31 --FD Formula's will cause a warning (this is the default)
32 --Fe Formula's will be replaced by the empty string
33 --Fu Formula's will be replaced with an undefined cell
34 -f force usage of <xls> if already exists (unlink before use)
35 -d <dtfmt> use <dtfmt> as date formats. Default = 'dd-mm-yyyy'
36 -C <C:fmt> use <fmt> as currency formats for currency <C>, no default
37 -D cols only convert dates in columns <cols>. Default is everywhere.
38 -u CSV is UTF8
39 -v [<lvl>] verbosity (default = 1)
40 EOU
41 exit $err;
42 } # usage
43
44 use Getopt::Long qw(:config bundling nopermute noignorecase passthrough);
45 my $sep; # Set after reading first line in a flurry attempt to auto-detect
46 my $quo = '"';
47 my $esc = '"';
48 my $wdt = 4; # Default minimal column width
49 my $xls; # Excel out file name
50 my $frc = 0; # Force use of file
51 my $utf = 0; # Data is encoded in Unicode
52 my $frm = 0; # Allow formula's
53 my $fac = "diag"; # Formula action (default is warn only)
54 my $dtf = "dd-mm-yyyy"; # Date format
55 my $crf = ""; # Currency format, e.g.: $:### ### ##0.00
56 my $opt_v = 1;
57 my $dtc;
58
59 GetOptions (
60 "help|?" => sub { usage (0); },
61
62 "c|s|sep=s" => \$sep,
63 "q|quo=s" => \$quo,
64 "e|esc=s" => \$esc,
65 "w|width=i" => \$wdt,
66 "o|x|out=s" => \$xls,
67 "d|date-fmt=s" => \$dtf,
68 "D|date-col=s" => \$dtc,
69 "C|curr-fmt=s" => \$crf,
70 "f|force!" => \$frc,
71 "F|formulas!" => \$frm,
72 "Fa=s" => \$fac,
73 "Fd" => sub { $fac = "die"; },
74 "Fc" => sub { $fac = "croak"; },
75 "FD" => sub { $fac = "diag"; },
76 "Fe" => sub { $fac = "empty"; },
77 "Fu" => sub { $fac = "undef"; },
78 "u|utf-8!" => \$utf,
79 "v|verbose:1" => \$opt_v,
80 ) or usage (1);
81
82 my $title = @ARGV && -f $ARGV[0] ? $ARGV[0] : "csv2xls";
83 ($xls ||= $title) =~ s/(?:\.csv)?$/.xls/i;
84
85 -s $xls && $frc and unlink $xls;
86 if (-s $xls) {
87 print STDERR "File '$xls' already exists. Overwrite? [y/N] > N\b";
88 scalar <STDIN> =~ m/^[yj](?:es|a)?$/i or exit;
89 }
90
91 # Don't split ourselves when modules do it _much_ better, and follow the standards
92 use Text::CSV_XS;
93 use Date::Calc qw( Delta_Days Days_in_Month );
94 use Spreadsheet::WriteExcel;
95 use Encode qw( from_to encode );
96
97 my $wbk = Spreadsheet::WriteExcel->new ($xls);
98 my $snm = $title;
99 $snm =~ s{\.csv$}{}i;
100 $snm =~ s{.*/}{};
101 $snm ||= "Sheet 1";
102 ($_ = length $snm) > 31 and substr $snm, 31, $_ - 31, "";
103 my $wks = $wbk->add_worksheet ($snm);
104 $dtf =~ s/j/y/g;
105 my %fmt = (
106 date => $wbk->add_format (align => "center", num_format => $dtf),
107 rest => $wbk->add_format (align => "left"),
108 wrap => $wbk->add_format (text_wrap => 1),
109 );
110 $crf =~ s/^([^:]+):(.*)/$1/ and $fmt{currency} = $wbk->add_format (
111 num_format => "$1 $2",
112 align => "right",
113 );
114
115 my ($h, $w, @w) = (0, 1); # data height, -width, and default column widths
116 my $row;
117 my $firstline;
118 unless ($sep) { # No sep char passed, try to auto-detect;
119 while (<>) {
120 m/\S/ or next; # Skip empty leading blank lines
121 $sep = # start auto-detect with quoted strings
122 m/["\d];["\d;]/ ? ";" :
123 m/["\d],["\d,]/ ? "," :
124 m/["\d]\t["\d,]/ ? "\t" :
125 # If neither, then for unquoted strings
126 m/\w;[\w;]/ ? ";" :
127 m/\w,[\w,]/ ? "," :
128 m/\w\t[\w,]/ ? "\t" :
129 ";" ;
130 # Yeah I know it should be a ',' (hence Csv), but the majority
131 # of the csv files to be shown comes from fucking Micky$hit,
132 # that uses semiColon ';' instead.
133 $firstline = $_;
134 last;
135 }
136 $firstline or die "The sourcefile does not contain any usable data\n";
137 }
138 my $csv = Text::CSV_XS-> new ({
139 sep_char => $sep eq "tab" ? "\t" : $sep,
140 quote_char => $quo eq "undef" ? undef : $quo,
141 escape_char => $esc eq "undef" ? undef : $esc,
142 binary => 1,
143 keep_meta_info => 1,
144 auto_diag => 1,
145 formula => $fac,
146 });
147 if ($firstline) {
148 $csv->parse ($firstline) or die $csv->error_diag ();
149 $row = [ $csv->fields ];
150 }
151 if ($opt_v > 3) {
152 foreach my $k (qw( sep_char quote_char escape_char )) {
153 my $c = $csv->$k () || "undef";
154 $c =~ s/\t/\\t/g;
155 $c =~ s/\r/\\r/g;
156 $c =~ s/\n/\\n/g;
157 $c =~ s/\0/\\0/g;
158 $c =~ s/([\x00-\x1f\x7f-\xff])/sprintf"\\x{%02x}",ord$1/ge;
159 printf STDERR "%-11s = %s\n", $k, $c;
160 }
161 }
162
163 if (my $rows = $dtc) {
164 $rows =~ s/-$/-999/; # 3,6-
165 $rows =~ s/-/../g;
166 eval "\$dtc = { map { \$_ => 1 } $rows }";
167 }
168
169 while ($row && @$row or $row = $csv->getline (*ARGV)) {
170 my @row = @$row;
171 @row > $w and push @w, ($wdt) x (($w = @row) - @w);
172 foreach my $c (0 .. $#row) {
173 my $val = $row[$c] // "";
174 my $l = length $val;
175 $l > ($w[$c] // -1) and $w[$c] = $l;
176
177 if ($utf and $csv->is_binary ($c)) {
178 eval { # from_to requires raw
179 my $raw = encode ("UTF-8", $val, Encode::FB_CROAK);
180 $val = $raw;
181 };
182 from_to ($val, "utf-8", "ucs2");
183 $wks->write_unicode ($h, $c, $val);
184 next;
185 }
186
187 if ($csv->is_quoted ($c)) {
188 if ($utf) {
189 from_to ($val, "utf-8", "ucs2");
190 $val =~ m/\n/
191 ? $wks->write_unicode ($h, $c, $val, $fmt{wrap})
192 : $wks->write_unicode ($h, $c, $val);
193 }
194 else {
195 $val =~ m/\n/
196 ? $wks->write_string ($h, $c, $val, $fmt{wrap})
197 : $wks->write_string ($h, $c, $val);
198 }
199 next;
200 }
201
202 if (!$dtc or $dtc->{$c + 1}) {
203 my @d = (0, 0, 0); # Y, M, D
204 $val =~ m/^(\d{4})(\d{2})(\d{2})$/ and @d = ($1, $2, $3);
205 $val =~ m/^(\d{2})-(\d{2})-(\d{4})$/ and @d = ($3, $2, $1);
206 if ( $d[2] >= 1 && $d[2] <= 31 &&
207 $d[1] >= 1 && $d[1] <= 12 &&
208 $d[0] >= 1900 && $d[0] <= 2199) {
209 my $dm = Days_in_Month (@d[0,1]);
210 $d[2] < 1 and $d[2] = 1;
211 $d[2] > $dm and $d[2] = $dm;
212 my $dt = 2 + Delta_Days (1900, 1, 1, @d);
213 $wks->write ($h, $c, $dt, $fmt{date});
214 next;
215 }
216 }
217 if ($crf and $val =~ m/^\s*\Q$crf\E\s*([0-9.]+)$/) {
218 $wks->write ($h, $c, $1 + 0, $fmt{currency});
219 next;
220 }
221
222 if (!$frm && $val =~ m/^=/) {
223 $wks->write_string ($h, $c, $val);
224 }
225 else {
226 $wks->write ($h, $c, $val);
227 }
228 }
229 ++$h % 100 or $opt_v && printf STDERR "%6d x %6d\r", $w, $h;
230 } continue { $row = undef }
231 $opt_v && printf STDERR "%6d x %6d\n", $w, $h;
232
233 $wks->set_column ($_, $_, $w[$_]) for 0 .. $#w;
234 $wbk->close ();