| 1 | package EAI::File 1.921; | ||
| 2 | |||
| 3 | 1 | ▶ | use strict; use feature 'unicode_strings'; use warnings; no warnings 'uninitialized'; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
Subroutine
BEGIN: called CC=1 SCAR=0.0
Subroutine
BEGIN: called CC=1 SCAR=0.0
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 4 | 0 | ▶ | use Exporter qw(import); use Text::CSV(); use Data::XLSX::Parser(); use Spreadsheet::ParseExcel(); use Spreadsheet::WriteExcel(); use Excel::Writer::XLSX(); use XML::LibXML(); use XML::LibXML::Debugging(); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.1
Subroutine
BEGIN: called CC=1 SCAR=0.1
Subroutine
BEGIN: called CC=1 SCAR=0.1
| |||
| 5 | use Carp qw(confess longmess); use Data::Dumper qw(Dumper); use Log::Log4perl qw(get_logger); use Time::localtime; use Scalar::Util qw(looks_like_number); use EAI::DateUtil; use EAI::Common; | ||
| 6 | |||
| 7 | our @EXPORT = qw(readText readExcel readXML writeText writeExcel); | ||
| 8 | |||
| 9 | # get common read procedure parameters from $File config, used in readText, readExcel and readXML | ||
| 10 | sub getcommon ($) { | ||
| 11 | my ($File) = @_; | ||
| 12 | my $lineProcessing = $File->{lineCode}; | ||
| 13 | my $fieldProcessing = $File->{fieldCode}; | ||
| 14 | my $firstLineProc = $File->{firstLineProc}; | ||
| 15 | my $thousandsep = "\\".$File->{format_thousandsep}; # add backslash to quote thousandsep for regexp (in case it is a ".") | ||
| 16 | my $decimalsep = "\\".$File->{format_decimalsep}; # add backslash to quote decimalsep for regexp (in case it is a ".") | ||
| 17 | my $skip = $File->{format_skip} if $File->{format_skip}; | ||
| 18 | my $sep = $File->{format_sep} if $File->{format_sep}; | ||
| 19 | $sep = $File->{format_defaultsep} if !$sep; # use default if not given | ||
| 20 | $sep = "" if !$sep; # use empty if not given | ||
| 21 | # for fixed format and non existing separator, header and targetheader strings are parsed/split using tab as separator | ||
| 22 | my @header = split(($sep =~ /^fix/ || !$sep ? "\t" : $sep), $File->{format_header}) if $File->{format_header}; | ||
| 23 | my @targetheader = split(($sep =~ /^fix/ || !$sep ? "\t" : $sep), $File->{format_targetheader}) if $File->{format_targetheader}; | ||
| 24 | $Data::Dumper::Terse = 1; | ||
| 25 | get_logger()->debug("\$skip:$skip\n\$sep:".Data::Dumper::qquote($sep)."\n\@header:@header\n\@targetheader:@targetheader\n\$lineProcessing:$lineProcessing\n\$fieldProcessing:$fieldProcessing\n\$firstLineProc:$firstLineProc\n\$thousandsep:$thousandsep\n\$decimalsep:$decimalsep"); | ||
| 26 | $Data::Dumper::Terse = 0; | ||
| 27 | return ($lineProcessing,$fieldProcessing,$firstLineProc,$thousandsep,$decimalsep,$sep,$skip,\@header,\@targetheader); | ||
| 28 | } | ||
| 29 | |||
| 30 | # read text files | ||
| 31 | sub readText ($$$;$$) { | ||
| 32 | my ($File,$data,$filenames,$redoSubDir,$countPercent) = @_; | ||
| 33 | my $logger = get_logger(); | ||
| 34 | my @filenames = @{$filenames} if $filenames; | ||
| 35 | if (!@filenames) { | ||
| 36 | $logger->error("no filenames passed".longmess()); | ||
| 37 | return 0; | ||
| 38 | } | ||
| 39 | # read format configuration | ||
| 40 | my ($lineProcessing,$fieldProcessing,$firstLineProc,$thousandsep,$decimalsep,$sep,$skip,$header,$targetheader) = getcommon($File); | ||
| 41 | my @header = @$header; my @targetheader = @$targetheader; | ||
| 42 | my ($poslen, $isFixLen); | ||
| 43 | if ($sep =~ /^fix/) { | ||
| 44 | # positions/length definitions from poslen definition: e.g. "format_poslen => [[0,3],[3,3]]" | ||
| 45 | $poslen = $File->{format_poslen}; | ||
| 46 | if (!$poslen) { | ||
| 47 | $logger->error("no format_poslen array given for parsing fix length format".longmess()); | ||
| 48 | return 0; | ||
| 49 | } | ||
| 50 | $isFixLen = 1; | ||
| 51 | } else { | ||
| 52 | if (!$sep) { | ||
| 53 | $logger->error("no separator set in ".Dumper($File).longmess()); | ||
| 54 | return 0; | ||
| 55 | } | ||
| 56 | if ($File->{format_quotedcsv} and ref($sep) eq "Regexp") { | ||
| 57 | $logger->error("no regex separator allowed with format_quotedcsv".longmess()); | ||
| 58 | return 0; | ||
| 59 | } | ||
| 60 | $logger->warn("string separator assumed to be a regular expression for splitting textfile without format_quotedcsv, this may produce unexpected results".longmess()) if (!$File->{format_quotedcsv} and !$File->{format_autoheader} and !(ref($sep) eq "Regexp")); | ||
| 61 | } | ||
| 62 | my $autoheader = $File->{format_autoheader} if $File->{format_autoheader}; | ||
| 63 | @targetheader = @header if !@targetheader; # if no specific targetheader defined use header instead | ||
| 64 | # read all files with same format | ||
| 65 | for my $filename (@filenames) { | ||
| 66 | my $lines = 0; my $buffer; | ||
| 67 | open my($fh), '<:raw', $redoSubDir.$filename; | ||
| 68 | while( sysread $fh, $buffer, 4096 ) { | ||
| 69 | $lines += ($buffer =~ s!$/!!g); | ||
| 70 | } | ||
| 71 | close $fh; | ||
| 72 | $logger->debug("reading $redoSubDir$filename"); | ||
| 73 | open (FILE, "<".$File->{format_encoding}, $redoSubDir.$filename) or do { # | ||
| 74 | if (! -e $redoSubDir.$filename) { | ||
| 75 | $logger->error("no file $redoSubDir$filename to process...".longmess()) unless ($File->{optional}); | ||
| 76 | $logger->warn("no file $redoSubDir$filename found... ".longmess()); | ||
| 77 | } else { | ||
| 78 | $logger->error("file open error: $!".longmess()); | ||
| 79 | } | ||
| 80 | return 0; | ||
| 81 | }; | ||
| 82 | my $sv = Text::CSV->new ({ | ||
| 83 | binary => 1, | ||
| 84 | auto_diag => 1, | ||
| 85 | sep_char => $sep, | ||
| 86 | eol => ($File->{format_eol} ? $File->{format_eol} : $/), | ||
| 87 | }); | ||
| 88 | # local context for special line record separator | ||
| 89 | { | ||
| 90 | my $newRecSep; | ||
| 91 | if ($File->{format_allowLinefeedInData}) { | ||
| 92 | # enable binmode and set line record separator to CRLF, so line feeds in values don't create artificial new lines/records | ||
| 93 | binmode(FILE, ":raw".$File->{format_encoding}); # raw so not to swallow CRLF | ||
| 94 | $newRecSep = "\015\012"; | ||
| 95 | $logger->debug("binmode"); | ||
| 96 | } | ||
| 97 | # change record separator (standard CRLF), if needed | ||
| 98 | local $/ = $newRecSep if $newRecSep; | ||
| 99 | my @layers = PerlIO::get_layers(FILE); | ||
| 100 | $logger->info("reading file $redoSubDir$filename, layers: @layers"); | ||
| 101 | if ($firstLineProc) { | ||
| 102 | $_ = <FILE>; | ||
| 103 | eval $firstLineProc; | ||
| 104 | $logger->error("eval firstLineProc: ".$firstLineProc.$@.longmess()) if ($@); | ||
| 105 | $logger->debug("evaled: ".$firstLineProc); | ||
| 106 | $lines--; | ||
| 107 | } | ||
| 108 | if ($skip) { | ||
| 109 | $skip-- if $firstLineProc; # if consumed already by firstLineProc skip one row less | ||
| 110 | $logger->debug("skipping ".($skip =~ /^\d+$/ ? " $skip lines" : "until line contains $skip (inclusive)")); | ||
| 111 | # skip first $skip rows in file (e.g. report header) if $skip is an integer, if $skip is non-integer, skip until the text $skip appears (inclusive) | ||
| 112 | if ($skip =~ /^\d+$/) { | ||
| 113 | for (1 .. $skip) { | ||
| 114 | $_ = <FILE>; | ||
| 115 | $logger->trace("skipping: $_") if $logger->is_trace; | ||
| 116 | } | ||
| 117 | $lines-=$skip; | ||
| 118 | } else { | ||
| 119 | while (<FILE>) { | ||
| 120 | $logger->trace("skipping: $_") if $logger->is_trace; | ||
| 121 | $lines--; | ||
| 122 | last if /$skip/; | ||
| 123 | } | ||
| 124 | } | ||
| 125 | } | ||
| 126 | # assumption: header exists in file and format_header should be derived from there | ||
| 127 | if ($autoheader) { | ||
| 128 | $sep = "," if !$sep; | ||
| 129 | $_ = <FILE>; chomp; | ||
| 130 | @header = split $sep; | ||
| 131 | @targetheader = @header; | ||
| 132 | $logger->debug("autoheader set, sep: [".$sep."], headings: @header"); | ||
| 133 | } | ||
| 134 | # iterate through all rows of file | ||
| 135 | my $lineno = 0; | ||
| 136 | my (@line,@previousline); | ||
| 137 | LINE: | ||
| 138 | while (<FILE>) { | ||
| 139 | chomp; | ||
| 140 | # in case lineProcessing or addtlProcessing needs access to whole row -> $rawline | ||
| 141 | my $rawline = $_; | ||
| 142 | # skip empty rows | ||
| 143 | next LINE if $_ eq ""; | ||
| 144 | @previousline = @line; | ||
| 145 | if ($isFixLen) { | ||
| 146 | @line = undef; | ||
| 147 | for (my $i=0;$i < scalar @header; $i++) { | ||
| 148 | $line[$i] = substr ($_, $poslen->[$i][0],$poslen->[$i][1]-$poslen->[$i][0]); | ||
| 149 | } | ||
| 150 | } else { | ||
| 151 | if ($File->{format_quotedcsv}) { | ||
| 152 | if ($sv->parse($_)) { | ||
| 153 | @line = $sv->fields(); | ||
| 154 | } else { | ||
| 155 | $logger->error("couldn't parse quoted csv row: ".$sv->error_diag().longmess()); | ||
| 156 | } | ||
| 157 | } else { | ||
| 158 | @line = split $sep; | ||
| 159 | } | ||
| 160 | } | ||
| 161 | $lineno++; | ||
| 162 | print "EAI::File::readText read $lineno of $lines\r" if ($countPercent and ($lineno % (int($lines * ($countPercent / 100)) == 0 ? 1 : int($lines * ($countPercent / 100))) == 0)) or $countPercent >= 100; | ||
| 163 | next LINE if $line[0] eq "" and !$lineProcessing; | ||
| 164 | readRow($data,\@line,\@header,\@targetheader,$rawline,$lineProcessing,$fieldProcessing,$thousandsep,$decimalsep,$lineno); | ||
| 165 | } | ||
| 166 | } | ||
| 167 | close FILE; | ||
| 168 | } | ||
| 169 | if (!$data or !@{$data}) { | ||
| 170 | if ($File->{emptyOK}) { | ||
| 171 | $logger->warn("no data retrieved from file(s): @filenames, will be ignored because \$File{emptyOK}".longmess()); | ||
| 172 | } else { | ||
| 173 | $logger->error("no data retrieved from file(s): @filenames".longmess()); | ||
| 174 | } | ||
| 175 | return 0; | ||
| 176 | } | ||
| 177 | if ($logger->is_trace) { | ||
| 178 | $logger->trace("amount of rows:".scalar(@{$data})) if $data; | ||
| 179 | $Data::Dumper::Deepcopy = 1; | ||
| 180 | $logger->trace(Dumper($data)); | ||
| 181 | $Data::Dumper::Deepcopy = 0; | ||
| 182 | } | ||
| 183 | return 1; | ||
| 184 | } | ||
| 185 | |||
| 186 | # global variables for excel parsing | ||
| 187 | my $startRowHeader; # header row for check (if format_header is defined), needed globally to avoid accidental date formatting | ||
| 188 | my %dateColumn; # lookup for columns with date values (key: excel column, numeric, starting with 1, value: 1 (boolean)) | ||
| 189 | my %headerColumn; # lookup for header (key: excel column, numeric, starting with 1, actual column of header field, value: 1 (boolean)) | ||
| 190 | my $worksheet; # worksheet to be read, old format (numeric, starting with 1) | ||
| 191 | my %dataRows; # intermediate storage for row values | ||
| 192 | my $maxRow; # bottom most row | ||
| 193 | my $stoppedOnEmptyValue; | ||
| 194 | my $stopOnEmptyValueColumn; | ||
| 195 | |||
| 196 | # event handler for readExcel (xls format) | ||
| 197 | sub cell_handler { | ||
| 198 | my $workbook = $_[0]; | ||
| 199 | # for the Spreadsheet::ParseExcel index, rows and columns are 0 based, generally row semantics is 1 based | ||
| 200 | my $sheet_index = $_[1]+1; | ||
| 201 | my $row = $_[2]+1; | ||
| 202 | my $col = $_[3]+1; | ||
| 203 | my $cell = $_[4]; | ||
| 204 | my $logger = get_logger(); | ||
| 205 | return unless $sheet_index eq $worksheet; # only parse desired worksheet | ||
| 206 | if ($headerColumn{$col}) { | ||
| 207 | if (($stopOnEmptyValueColumn eq $col and !$cell) or $stoppedOnEmptyValue) { | ||
| 208 | $logger->warn("empty cell in row $row / column $col and stopOnEmptyValueColumn is set to $col, skipping from here now".longmess()) if !$stoppedOnEmptyValue; # pass warning only once | ||
| 209 | $stoppedOnEmptyValue = 1; | ||
| 210 | } else { | ||
| 211 | $logger->trace("Row $row, Column $col:\n".Dumper($cell)) if $logger->is_trace; | ||
| 212 | if ($dateColumn{$col} and $row != $startRowHeader) { | ||
| 213 | # with date values need value(), otherwise (unformatted) a julian date (decimal representing date and time) is returned | ||
| 214 | # parse from US date format into YYYYMMDD, time parts are still ignored! | ||
| 215 | if ($cell) { | ||
| 216 | my ($m,$d,$y) = ($cell->value() =~ /(\d+?)\/(\d+?)\/(\d{4})/); | ||
| 217 | $dataRows{$row}{$col} = sprintf("%04d%02d%02d",$y,$m,$d); | ||
| 218 | } | ||
| 219 | } else { | ||
| 220 | # non date values are fetched unformatted | ||
| 221 | $dataRows{$row}{$col} = $cell->unformatted() if $cell; | ||
| 222 | } | ||
| 223 | $maxRow = $row if $maxRow < $row; | ||
| 224 | #$logger->info(Dumper($cell)); | ||
| 225 | #my $stopHere = <STDIN>; # for step debugging, uncomment these 2 lines | ||
| 226 | } | ||
| 227 | } | ||
| 228 | } | ||
| 229 | |||
| 230 | my $countPercentExcel; | ||
| 231 | # event handler for readExcel (xlsx format) | ||
| 232 | sub row_handlerXLSX { | ||
| 233 | my $rowDetails = $_[1]; | ||
| 234 | my $logger = get_logger(); | ||
| 235 | # for the Data::XLSX::Parser index, rows and columns are 1 based | ||
| 236 | for my $cellDetail (@$rowDetails) { | ||
| 237 | my $row = $cellDetail->{"row"}; | ||
| 238 | my $col = $cellDetail->{"c"}; | ||
| 239 | my $value = $cellDetail->{"v"}; | ||
| 240 | if ($headerColumn{$col}) { | ||
| 241 | if (($stopOnEmptyValueColumn eq $col and !$value) or $stoppedOnEmptyValue) { | ||
| 242 | $logger->warn("empty cell in row $row / column $col and stopOnEmptyValueColumn is set to $col, skipping from here now".longmess()) if !$stoppedOnEmptyValue; # pass warning only once | ||
| 243 | $stoppedOnEmptyValue = 1; | ||
| 244 | } else { | ||
| 245 | $logger->trace("Row $row, Column $col:\n".Dumper($cellDetail)) if $logger->is_trace; | ||
| 246 | if ($dateColumn{$col} and $row != $startRowHeader) { | ||
| 247 | # date fields are converted from epoch format ! | ||
| 248 | $dataRows{$row}{$col} = convertEpochToYYYYMMDD($value); | ||
| 249 | } else { | ||
| 250 | # non date values taken directly | ||
| 251 | $dataRows{$row}{$col} = $value; | ||
| 252 | } | ||
| 253 | $maxRow = $row if $maxRow < $row; | ||
| 254 | } | ||
| 255 | } | ||
| 256 | print "EAI::File::readExcel read $row rows\r" if $countPercentExcel and ($row % 50 == 0); | ||
| 257 | } | ||
| 258 | } | ||
| 259 | |||
| 260 | # read Excel file (format depends on setting) | ||
| 261 | sub readExcel ($$$;$$) { | ||
| 262 | my ($File,$data,$filenames,$redoSubDir,$countPercent) = @_; | ||
| 263 | $countPercentExcel = $countPercent if $countPercent; | ||
| 264 | my $logger = get_logger(); | ||
| 265 | $stopOnEmptyValueColumn = $File->{format_stopOnEmptyValueColumn}; | ||
| 266 | $stoppedOnEmptyValue = 0; # reset | ||
| 267 | my @filenames = @{$filenames} if $filenames; | ||
| 268 | if (!@filenames) { | ||
| 269 | $logger->error("no filenames passed".longmess()); | ||
| 270 | return 0; | ||
| 271 | } | ||
| 272 | # reset module global variables | ||
| 273 | undef %dateColumn; | ||
| 274 | undef %headerColumn; | ||
| 275 | # read format configuration | ||
| 276 | my ($lineProcessing,$fieldProcessing,$firstLineProc,$thousandsep,$decimalsep,$sep,$skip,$header,$targetheader) = getcommon($File); | ||
| 277 | my @header = @$header; my @targetheader = @$targetheader; | ||
| 278 | if (!@targetheader) { | ||
| 279 | $logger->error("no targetheader defined".longmess()); # targetheader has to be given, excel source header (@header) optional | ||
| 280 | return 0; | ||
| 281 | } | ||
| 282 | $logger->debug("skip: $skip,headerskip: ". $File->{format_headerskip}.", header: @header \ntargetheader: @targetheader\ndateColumns: ".($File->{format_dateColumns} ? @{$File->{format_dateColumns}} : "")."\nheaderColumns: ".($File->{format_headerColumns} ? @{$File->{format_headerColumns}} : "")); | ||
| 283 | # prepare dateColumn definition if needed/given | ||
| 284 | if ($File->{format_dateColumns} and ref($File->{format_dateColumns}) eq "ARRAY") { | ||
| 285 | for my $col (@{$File->{format_dateColumns}}) { | ||
| 286 | $dateColumn{$col} = 1; | ||
| 287 | } | ||
| 288 | } | ||
| 289 | # prepare headerColumn definition | ||
| 290 | if ($File->{format_headerColumns} and ref($File->{format_headerColumns}) eq "ARRAY") { | ||
| 291 | if (@{$File->{format_headerColumns}} != @header or @{$File->{format_headerColumns}} != @targetheader) { | ||
| 292 | $logger->error("format_headerColumns has different length than format_header or format_targetheader definitions".longmess()); | ||
| 293 | return 0; | ||
| 294 | } | ||
| 295 | for my $col (@{$File->{format_headerColumns}}) { | ||
| 296 | $headerColumn{$col} = 1; | ||
| 297 | } | ||
| 298 | } else { | ||
| 299 | if (@header and @header != @targetheader) { | ||
| 300 | $logger->error("format_header has different length than format_targetheader definition".longmess()); | ||
| 301 | return 0; | ||
| 302 | } | ||
| 303 | $logger->debug("no format_headerColumns given, assuming simple list starting with column 1, having \@header length columns and a header row") if @header; | ||
| 304 | $logger->debug("no format_headerColumns and no header definition given, assuming simple list starting with column 1, having \@targetheader length columns and no header row") if !@header; | ||
| 305 | for (my $i = 0; $i < @targetheader; $i++) { | ||
| 306 | $headerColumn{$i+1} = 1; | ||
| 307 | } | ||
| 308 | } | ||
| 309 | $logger->debug("headerColumn:".Dumper(\%headerColumn).",dateColumn:".Dumper(\%dateColumn)); | ||
| 310 | @header = @targetheader if !@header; # in the end only target header is important | ||
| 311 | # read all files with same format | ||
| 312 | for my $filename (@filenames) { | ||
| 313 | my $startRow = 1; # starting data row | ||
| 314 | $startRowHeader = 1; # starting header row for check (if format_header is defined) | ||
| 315 | if ($skip =~ /^\d+$/) { | ||
| 316 | $logger->debug("skipping ".$skip." rows for data begin"); | ||
| 317 | $startRow += $skip; # skip additional rows for data begin, row semantics is 1 based | ||
| 318 | } | ||
| 319 | if ($File->{format_headerskip}) { | ||
| 320 | $logger->debug("skipping ".$File->{format_headerskip}." rows for header row (1)"); | ||
| 321 | $startRowHeader += $File->{format_headerskip}; # skip additional rows for header row, row semantics is 1 based | ||
| 322 | } | ||
| 323 | if (!$skip and $File->{format_header}) { | ||
| 324 | $logger->debug("setting data begin to \$startRowHeader ($startRowHeader) + 1 as format_header given and no format_skip found"); | ||
| 325 | $startRow = $startRowHeader + 1; # set to header following row if format_skip not defined and format_header given | ||
| 326 | } | ||
| 327 | # reset module global variables | ||
| 328 | %dataRows = (); | ||
| 329 | $maxRow = 1; | ||
| 330 | # check excel file existence | ||
| 331 | if (! -e $redoSubDir.$filename) { | ||
| 332 | $logger->error("no excel file ($filename) to process: $!") unless ($File->{optional}); | ||
| 333 | $logger->warn("no file $redoSubDir$filename found".longmess()); | ||
| 334 | return 0; | ||
| 335 | } | ||
| 336 | # read in excel file/sheet completely, both formats utilize read handlers (row_handlerXLSX or cell_handler) | ||
| 337 | my $parser; | ||
| 338 | if ($File->{format_xlformat} =~ /^xlsx$/i) { | ||
| 339 | $logger->debug("open xlsx file $redoSubDir$filename ... "); | ||
| 340 | $parser = Data::XLSX::Parser->new; | ||
| 341 | $parser->open($redoSubDir.$filename); | ||
| 342 | $parser->add_row_event_handler(\&row_handlerXLSX); | ||
| 343 | if ($File->{format_worksheet}) { | ||
| 344 | $worksheet = $parser->workbook->sheet_id($File->{format_worksheet}); | ||
| 345 | if (!$worksheet) { | ||
| 346 | $logger->error("no xlsx worksheet found named ".$File->{format_worksheet}.", maybe try {format_worksheetID} (numerically ordered place)".longmess()); | ||
| 347 | return 0; | ||
| 348 | } | ||
| 349 | } elsif ($File->{format_worksheetID}) { | ||
| 350 | $worksheet = $File->{format_worksheetID}; | ||
| 351 | } else { | ||
| 352 | $logger->error("neither worksheetname nor worksheetID (numerically ordered place) given for xlsx workbook".longmess()); | ||
| 353 | return 0; | ||
| 354 | } | ||
| 355 | $logger->debug("starting parser for xlsx sheet name: ".$File->{format_worksheet}.", id:".$worksheet); | ||
| 356 | eval { $parser->sheet_by_id($worksheet); }; | ||
| 357 | if ($@) { | ||
| 358 | $logger->error("Error parsing xlsx sheet: ".$@.longmess()); | ||
| 359 | return 0; | ||
| 360 | } | ||
| 361 | } elsif ($File->{format_xlformat} =~ /^xls$/i) { | ||
| 362 | $logger->warn("worksheets can't be found by name for the old xls format, please pass numerically ordered place in {format_worksheetID}".longmess()) if ($File->{format_worksheet}); | ||
| 363 | $worksheet = $File->{format_worksheetID} if $File->{format_worksheetID}; | ||
| 364 | $logger->debug("starting parser for xls file $redoSubDir$filename ... "); | ||
| 365 | $parser = Spreadsheet::ParseExcel->new( | ||
| 366 | CellHandler => \&cell_handler, | ||
| 367 | NotSetCell => 1 | ||
| 368 | ); | ||
| 369 | my $workbook = $parser->parse($redoSubDir.$filename); | ||
| 370 | if (!defined $workbook) { | ||
| 371 | $logger->error("excel xls parsing error: ".$parser->error().longmess()); | ||
| 372 | return 0; | ||
| 373 | } | ||
| 374 | } else { | ||
| 375 | $logger->error("unrecognised excel format passed in \$File->{format_xlformat}:".$File->{format_xlformat}.longmess()); | ||
| 376 | return 0; | ||
| 377 | } | ||
| 378 | # check header row if format_header given | ||
| 379 | if ($File->{format_header}) { | ||
| 380 | $logger->info("checking header info in row $startRowHeader"); | ||
| 381 | if ($File->{format_headerColumns}) { | ||
| 382 | my $i = 0; | ||
| 383 | for (@{$File->{format_headerColumns}}) { | ||
| 384 | $logger->error("expected header '".$header[$i]."' not in column ".$_.", instead got:".$dataRows{$startRowHeader}{$_}.longmess()) if $header[$i] ne $dataRows{$startRowHeader}{$_}; | ||
| 385 | $i++; | ||
| 386 | } | ||
| 387 | } else { | ||
| 388 | for (my $i = 0; $i < @header; $i++) { | ||
| 389 | $logger->error("expected header '".$header[$i]."' not in column ".($i+1).", instead got:".$dataRows{$startRowHeader}{$i+1}.longmess()) if $header[$i] ne $dataRows{$startRowHeader}{$i+1}; | ||
| 390 | } | ||
| 391 | } | ||
| 392 | } | ||
| 393 | # now iterate data rows | ||
| 394 | my (@line,@previousline); | ||
| 395 | $logger->debug("(data) start row: $startRow, (data) end row: $maxRow"); | ||
| 396 | LINE: | ||
| 397 | # $maxRow is being set when reading in the sheet | ||
| 398 | my $lines = $maxRow - $startRow; | ||
| 399 | for my $lineno ($startRow .. $maxRow) { | ||
| 400 | @previousline = @line; | ||
| 401 | @line = undef; | ||
| 402 | # get @line from stored values | ||
| 403 | if ($File->{format_headerColumns}) { | ||
| 404 | my $i = 0; | ||
| 405 | for (@{$File->{format_headerColumns}}) { | ||
| 406 | $line[$i] = $dataRows{$lineno}{$_}; | ||
| 407 | $i++; | ||
| 408 | } | ||
| 409 | } else { | ||
| 410 | for (my $i = 0; $i < @header; $i++) { | ||
| 411 | $line[$i] = $dataRows{$lineno}{$i+1}; | ||
| 412 | } | ||
| 413 | } | ||
| 414 | readRow($data,\@line,\@header,\@targetheader,undef,$lineProcessing,$fieldProcessing,$thousandsep,$decimalsep,$lineno); | ||
| 415 | print "EAI::File::readExcel parsed $lineno of $lines\r" if $countPercent and ($lineno % (int($lines * ($countPercent / 100)) == 0 ? 1 : int($lines * ($countPercent / 100))) == 0); | ||
| 416 | } | ||
| 417 | close FILE; | ||
| 418 | if (scalar(@{$data}) == 0 and !$File->{emptyOK}) { | ||
| 419 | $logger->error("Empty file: $filename, no data returned !!".longmess()); | ||
| 420 | return 0; | ||
| 421 | } | ||
| 422 | } | ||
| 423 | $logger->trace("amount of rows: ".scalar(@{$data})) if $logger->is_trace; | ||
| 424 | $logger->trace(Dumper($data)) if $logger->is_trace; | ||
| 425 | return 1; | ||
| 426 | } | ||
| 427 | |||
| 428 | # read XML file | ||
| 429 | sub readXML ($$$;$) { | ||
| 430 | my ($File,$data,$filenames,$redoSubDir) = @_; | ||
| 431 | my $logger = get_logger(); | ||
| 432 | my @filenames = @{$filenames} if $filenames; | ||
| 433 | if (!@filenames) { | ||
| 434 | $logger->error("no filenames passed".longmess()); | ||
| 435 | return 0; | ||
| 436 | } | ||
| 437 | # read format configuration | ||
| 438 | my ($lineProcessing,$fieldProcessing,$firstLineProc,$thousandsep,$decimalsep,$sep,$skip,$header,$targetheader) = getcommon($File); | ||
| 439 | my @header = @$header; my @targetheader = @$targetheader; | ||
| 440 | if (!@header) { | ||
| 441 | $logger->error("no header defined".longmess()); # targetheader has to be given, excel source header (@header) optional | ||
| 442 | return 0; | ||
| 443 | } | ||
| 444 | $Data::Dumper::Terse = 1; | ||
| 445 | $logger->debug("sep:".Data::Dumper::qquote($sep).",header:@header\ntargetheader:@targetheader"); | ||
| 446 | $Data::Dumper::Terse = 0; | ||
| 447 | @targetheader = @header if !@targetheader; # if no specific targetheader defined use header instead | ||
| 448 | # read all files with same format | ||
| 449 | for my $filename (@filenames) { | ||
| 450 | if (! -e $redoSubDir.$filename) { | ||
| 451 | $logger->error("no XML file ($redoSubDir$filename) found to process".longmess()) unless ($File->{optional}); | ||
| 452 | $logger->warn("file $redoSubDir$filename not found".longmess()); | ||
| 453 | return 0; | ||
| 454 | } | ||
| 455 | my $xmldata = XML::LibXML->load_xml(location => $redoSubDir.$filename, no_blanks => 1); | ||
| 456 | my $xpc = XML::LibXML::XPathContext->new($xmldata); | ||
| 457 | if (ref($File->{format_namespaces}) eq 'HASH') { | ||
| 458 | $xpc->registerNs($_, $File->{format_namespaces}{$_}) for keys (%{$File->{format_namespaces}}); | ||
| 459 | } | ||
| 460 | $logger->error("no format_xpathRecordLevel passed".longmess()) unless ($File->{format_xpathRecordLevel}); | ||
| 461 | $logger->error("no format_fieldXpath hash passed".longmess()) unless ($File->{format_fieldXpath} && ref($File->{format_fieldXpath}) eq 'HASH'); | ||
| 462 | $logger->trace("format_xpathRecordLevel: ".$File->{format_xpathRecordLevel}) if $logger->is_trace; | ||
| 463 | $logger->trace("format_fieldXpath: ".Dumper($File->{format_fieldXpath})) if $logger->is_trace; | ||
| 464 | my @records = $xpc->findnodes($File->{format_xpathRecordLevel}); | ||
| 465 | $logger->warn("no records found".longmess()) if @records == 0; | ||
| 466 | $logger->trace("total document content: ".$xpc->getContextNode->toClarkML()) if $logger->is_trace; | ||
| 467 | # iterate through all rows of file | ||
| 468 | my $lineno = 0; | ||
| 469 | foreach my $record (@records) { | ||
| 470 | my @line; | ||
| 471 | # get @line from stored values | ||
| 472 | if (ref($record) eq "XML::LibXML::Element") { | ||
| 473 | $logger->trace("node content: ".$record->toClarkML()) if $logger->is_trace; | ||
| 474 | my @headerColumns = keys (%{$File->{format_fieldXpath}}); | ||
| 475 | for (my $i = 0; $i < @headerColumns; $i++) { | ||
| 476 | $logger->trace("field:".$header[$i].",\$File->{format_fieldXpath}{".$header[$i]."}:".$File->{format_fieldXpath}{$header[$i]}) if $logger->is_trace; | ||
| 477 | if ($File->{format_fieldXpath}{$header[$i]} =~ /^\//) { | ||
| 478 | # absolute paths -> leave context node and find in the root doc (no context node argument) | ||
| 479 | $logger->trace("absolute fieldXpath:".$File->{format_fieldXpath}{$header[$i]}) if $logger->is_trace; | ||
| 480 | $line[$i] = $xpc->findvalue($File->{format_fieldXpath}{$header[$i]}); | ||
| 481 | } else { | ||
| 482 | # relative paths -> context node is current record node | ||
| 483 | $logger->trace("relative fieldXpath:".$File->{format_fieldXpath}{$header[$i]}) if $logger->is_trace; | ||
| 484 | $line[$i] = $xpc->findvalue($File->{format_fieldXpath}{$header[$i]}, $record); | ||
| 485 | } | ||
| 486 | } | ||
| 487 | } | ||
| 488 | $lineno++; | ||
| 489 | readRow($data,\@line,\@header,\@targetheader,$xpc,$lineProcessing,$fieldProcessing,$thousandsep,$decimalsep,$lineno); | ||
| 490 | } | ||
| 491 | if (!$data and !$File->{emptyOK}) { | ||
| 492 | $logger->error("empty file: $filename, no data returned".longmess()); | ||
| 493 | return 0; | ||
| 494 | } | ||
| 495 | } | ||
| 496 | return 1; | ||
| 497 | } | ||
| 498 | |||
| 499 | # to be able to access these variables in fieldCode and/or lineCode anonymous subs, they have to be package global. Access in anon sub is then done with %EAI::File::line, @EAI::File::header or $EAI::File::i (this column loop var is only meaningful in fieldCode) | ||
| 500 | our (%line,%templine,$i,@line,@header,@targetheader,$skipLineAssignment,$lineno,$rawline); | ||
| 501 | |||
| 502 | # read row into final line hash (including special "hook" code) | ||
| 503 | sub readRow ($$$$$$$$$$) { | ||
| 504 | my ($data,$line,$header,$targetheader,$lineProcessing,$fieldProcessing,$thousandsep,$decimalsep); | ||
| 505 | ($data,$line,$header,$targetheader,$rawline,$lineProcessing,$fieldProcessing,$thousandsep,$decimalsep,$lineno) = @_; | ||
| 506 | @line = @$line; | ||
| 507 | @header = @$header; | ||
| 508 | @targetheader = @$targetheader; | ||
| 509 | my $logger = get_logger(); | ||
| 510 | $skipLineAssignment = 0; # can be set in fieldCode, to avoid further assignment to data. | ||
| 511 | %line=(); %templine=(); | ||
| 512 | |||
| 513 | $logger->trace("line:@{$line},header:@{$header},targetheader:@{$targetheader},rawline:$rawline,lineProcessing:$lineProcessing,thousandsep:$thousandsep,decimalsep:$decimalsep,lineno:$lineno") if $logger->is_trace; | ||
| 514 | # iterate through fields of current row | ||
| 515 | for ($i = 0; $i < @line; $i++) { | ||
| 516 | # first trim leading and trailing spaces | ||
| 517 | $line[$i] =~ s/^ *//; | ||
| 518 | $line[$i] =~ s/ *$//; | ||
| 519 | # remove thousand separators for numerals based on configured thousand/decimal separator and change decimal separator to \d+\.?\d* | ||
| 520 | $line[$i] =~ s/$thousandsep//g if $line[$i] =~ /^-?\d{1,3}($thousandsep\d{3})+($decimalsep\d*)?$/; | ||
| 521 | if ($decimalsep ne "\\.") { | ||
| 522 | $line[$i] =~ s/$decimalsep/\./ if $line[$i] =~ /^-?\d+$decimalsep\d+$/ or $line[$i] =~ /^-*\d*$decimalsep?\d+E*[-+]*\d*$/; | ||
| 523 | } | ||
| 524 | |||
| 525 | # only process as targetheader, if they are not the same as the original header (allows special access to original header via $templine/$previoustempline) | ||
| 526 | if ($header[$i] ne $targetheader[$i]) { | ||
| 527 | # prevent autovivification of hash entries, if $i is potentially > @header or > @targetheader | ||
| 528 | $line{$targetheader[$i]} = $line[$i] if $targetheader[$i]; | ||
| 529 | $templine{$header[$i]} = $line[$i] if $header[$i]; | ||
| 530 | } else { | ||
| 531 | $line{$header[$i]} = $line[$i] if $header[$i]; | ||
| 532 | } | ||
| 533 | # field specific processing set, augments processing for a single specific field specified by targetheader... | ||
| 534 | if ($fieldProcessing->{$targetheader[$i]}) { | ||
| 535 | $logger->trace('specific fieldProcessing: $targetheader['.$i.'],$line{'.$targetheader[$i].'}:'.$line{$targetheader[$i]}.',fieldProcessing{',$targetheader[$i],'}:'.$fieldProcessing->{$targetheader[$i]}) if $logger->is_trace; | ||
| 536 | if (ref($fieldProcessing->{$targetheader[$i]}) eq "CODE") { | ||
| 537 | eval {$fieldProcessing->{$targetheader[$i]}->()}; | ||
| 538 | } else { | ||
| 539 | eval $fieldProcessing->{$targetheader[$i]}; | ||
| 540 | } | ||
| 541 | $logger->error("eval of ".(ref($fieldProcessing->{$targetheader[$i]}) eq "CODE" ? "defined sub" : "'".$fieldProcessing->{$targetheader[$i]}."'")." returned error:$@".longmess()) if ($@); | ||
| 542 | } elsif ($fieldProcessing->{""}) { # special case: if empty key is defined with processing code, do for all fields | ||
| 543 | $logger->trace('general fieldProcessing: $targetheader['.$i.'],$line{'.$targetheader[$i].'}:'.$line{$targetheader[$i]}.',fieldProcessing{',$targetheader[$i],'}:'.$fieldProcessing->{$targetheader[$i]}) if $logger->is_trace; | ||
| 544 | if (ref($fieldProcessing->{""}) eq "CODE") { | ||
| 545 | eval {$fieldProcessing->{""}->()}; | ||
| 546 | } else { | ||
| 547 | eval $fieldProcessing->{""}; | ||
| 548 | } | ||
| 549 | $logger->error("eval of ".(ref($fieldProcessing->{""}) eq "CODE" ? "defined sub" : "'".$fieldProcessing->{""}."'")." returned error:$@".longmess()) if ($@); | ||
| 550 | } | ||
| 551 | } | ||
| 552 | # additional row processing defined | ||
| 553 | if ($lineProcessing) { | ||
| 554 | if (ref($lineProcessing) eq "CODE") { | ||
| 555 | eval {$lineProcessing->()}; | ||
| 556 | } else { | ||
| 557 | eval $lineProcessing; | ||
| 558 | } | ||
| 559 | $logger->error("eval of ".(ref($lineProcessing) eq "CODE" ? "defined sub" : "'".$lineProcessing."'")." returned error:$@".longmess()) if ($@); | ||
| 560 | } | ||
| 561 | $logger->trace("\$skipLineAssignment: $skipLineAssignment, \%line:\n".Dumper(\%line)) if $logger->is_trace; | ||
| 562 | # add reference to created line (don't do push @{$data}, \%line here as then subsequent lines will overwrite all before!) | ||
| 563 | push @{$data}, {%line} if keys %line > 0 and !$skipLineAssignment; | ||
| 564 | } | ||
| 565 | |||
| 566 | our $value; | ||
| 567 | # write text file | ||
| 568 | sub writeText ($$;$) { | ||
| 569 | my ($File,$data,$countPercent) = @_; | ||
| 570 | my $logger = get_logger(); | ||
| 571 | my $filename = $File->{filename}; | ||
| 572 | my $writemode = ($File->{append} ? ">>" : ">"); | ||
| 573 | my $format_sepHead = ($File->{format_sepHead} ? $File->{format_sepHead} : ""); | ||
| 574 | my $format_sep = ($File->{format_sep} ? $File->{format_sep} : ""); | ||
| 575 | $logger->debug("sepHead: ".Data::Dumper::qquote($format_sepHead).", sep: ".Data::Dumper::qquote($format_sep)); | ||
| 576 | if (ref($data) ne 'ARRAY') { | ||
| 577 | $logger->error("passed data in \$data is not a ref to array (you have to initialize it as an array):".Dumper($data).longmess()); | ||
| 578 | return 0; | ||
| 579 | } | ||
| 580 | # in case we need to print out csv/quoted values | ||
| 581 | my $sv; | ||
| 582 | if ($File->{format_quotedcsv}) { | ||
| 583 | $sv = Text::CSV->new ({ | ||
| 584 | binary => 1, | ||
| 585 | auto_diag => 1, | ||
| 586 | sep_char => $File->{format_sep}, | ||
| 587 | eol => ($File->{format_eol} ? $File->{format_eol} : $/), | ||
| 588 | }); | ||
| 589 | } | ||
| 590 | my @columnnames; my @paddings; | ||
| 591 | if (ref($File->{columns}) eq 'HASH') { | ||
| 592 | @columnnames = map {$File->{columns}{$_}} sort keys %{$File->{columns}}; | ||
| 593 | } elsif (ref($File->{columns}) eq 'ARRAY') { | ||
| 594 | @columnnames = @{$File->{columns}}; | ||
| 595 | } else { | ||
| 596 | $logger->error("no field information given (columns should be ref to array or ref to hash, you have to initialize it as that)".longmess()); | ||
| 597 | return 0; | ||
| 598 | } | ||
| 599 | if (ref($File->{format_padding}) eq 'ARRAY') { | ||
| 600 | @paddings = @{$File->{format_padding}}; | ||
| 601 | } elsif (ref($File->{format_padding}) eq 'HASH') { | ||
| 602 | @paddings = map {$File->{format_padding}{$_}} sort keys %{$File->{format_padding}}; | ||
| 603 | } else { | ||
| 604 | if ($File->{format_fix}) { | ||
| 605 | $logger->error("no padding information given for fixed length format (padding => ref to array or hash)".longmess()); | ||
| 606 | return 0; | ||
| 607 | } | ||
| 608 | } | ||
| 609 | $logger->debug("fields: @columnnames"); | ||
| 610 | $logger->debug("paddings: @paddings"); | ||
| 611 | my $headerRow; | ||
| 612 | my $col = 0; # iterate through @paddings in parallel. | ||
| 613 | my $firstcol = 1; | ||
| 614 | for my $colname (@columnnames) { | ||
| 615 | if (!$File->{columnskip}{$colname}) { | ||
| 616 | if ($File->{format_quotedcsv}) { | ||
| 617 | push @$headerRow, $colname; | ||
| 618 | } else { | ||
| 619 | # first column has no separator before. if there is a special separator for heading, then use it, else the standard one | ||
| 620 | $headerRow = $headerRow.($firstcol ? "" : ($format_sepHead ? $format_sepHead : $format_sep)).$colname if (!$File->{format_fix}); | ||
| 621 | $headerRow = $headerRow.sprintf("%-*s%s", $paddings[$col],$colname) if ($File->{format_fix}); | ||
| 622 | $firstcol = 0; | ||
| 623 | } | ||
| 624 | } | ||
| 625 | $col++; | ||
| 626 | } | ||
| 627 | # open file for writing | ||
| 628 | $logger->info("writing to $filename ($writemode)"); | ||
| 629 | open (FHOUT, $writemode.$File->{format_encoding},$filename) or do { | ||
| 630 | $logger->error("couldn't open $filename for writing (writemode $writemode): $!".longmess()); | ||
| 631 | return 0; | ||
| 632 | }; | ||
| 633 | # write header | ||
| 634 | print FHOUT $File->{format_beforeHeader} if $File->{format_beforeHeader}; | ||
| 635 | unless ($File->{format_suppressHeader}) { | ||
| 636 | if ($File->{format_quotedcsv}) { | ||
| 637 | if (!$sv->print(\*FHOUT, $headerRow)) { | ||
| 638 | $logger->error("error writing quoted csv header row: ".$sv->error_diag().longmess()); | ||
| 639 | return 0; | ||
| 640 | } | ||
| 641 | } else { | ||
| 642 | print FHOUT $headerRow."\n"; | ||
| 643 | } | ||
| 644 | } | ||
| 645 | # write data | ||
| 646 | $logger->trace("passed data:\n".Dumper($data)) if $logger->is_trace; | ||
| 647 | my $lines = scalar(@{$data}); | ||
| 648 | for (my $i=0; $i<$lines; $i++) { | ||
| 649 | # data row | ||
| 650 | my $row = $data->[$i]; | ||
| 651 | my $lineRow; | ||
| 652 | # chain all data in a row | ||
| 653 | my $col = 0; $firstcol = 1; | ||
| 654 | for my $colname (@columnnames) { | ||
| 655 | if (!$File->{columnskip}{$colname}) { | ||
| 656 | if (ref($row) ne "HASH") { | ||
| 657 | $logger->error("row passed in (\$data) is no ref to hash! should be \$VAR1 = {'key' => 'value', ...}:\n".Dumper($row).longmess()); | ||
| 658 | return 0; | ||
| 659 | } | ||
| 660 | $value = $row->{$colname}; | ||
| 661 | $logger->trace("\$value for \$colname $colname: $value") if $logger->is_trace; | ||
| 662 | if ($File->{addtlProcessingTrigger} && $File->{addtlProcessing}) { | ||
| 663 | my $doAddtlProcessing = eval $File->{addtlProcessingTrigger}; | ||
| 664 | if ($@) { | ||
| 665 | $logger->error("error in eval addtlProcessingTrigger: ".$File->{addtlProcessingTrigger}.":".$@.longmess()); | ||
| 666 | return 0; | ||
| 667 | } | ||
| 668 | if ($doAddtlProcessing) { | ||
| 669 | if (ref( $File->{addtlProcessing}) eq "CODE") { | ||
| 670 | eval {$File->{addtlProcessing}->()}; | ||
| 671 | } else { | ||
| 672 | eval $File->{addtlProcessing}; | ||
| 673 | } | ||
| 674 | if ($@) { | ||
| 675 | $logger->error("error in eval addtlProcessing: ".$File->{addtlProcessing}.":".$@.longmess()); | ||
| 676 | return 0; | ||
| 677 | } | ||
| 678 | $logger->trace("\$value after addtlProcessing: $value") if $logger->is_trace; | ||
| 679 | } | ||
| 680 | } | ||
| 681 | if ($File->{format_quotedcsv}) { | ||
| 682 | push @$lineRow, $value; | ||
| 683 | } else { | ||
| 684 | # last column ($columnnames[@columnnames-1]) should not have a separator afterwards | ||
| 685 | $lineRow = $lineRow.($firstcol ? "" : $File->{format_sep}).sprintf("%s", $value) if (!$File->{format_fix}); | ||
| 686 | # additional padding for fixed length format | ||
| 687 | $lineRow = $lineRow.sprintf("%-*s%s", $paddings[$col],$value) if ($File->{format_fix}); | ||
| 688 | $firstcol = 0; | ||
| 689 | } | ||
| 690 | } | ||
| 691 | $col++; | ||
| 692 | } | ||
| 693 | if ($File->{format_quotedcsv}) { | ||
| 694 | if (!$sv->print(\*FHOUT, $lineRow)) { | ||
| 695 | $logger->error("error writing quoted csv row: ".$sv->error_diag().longmess()); | ||
| 696 | return 0; | ||
| 697 | } | ||
| 698 | $logger->trace("row: @$lineRow") if $logger->is_trace; | ||
| 699 | } else { | ||
| 700 | print FHOUT $lineRow."\n"; | ||
| 701 | $logger->trace("row: ".$lineRow) if $logger->is_trace; | ||
| 702 | } | ||
| 703 | print "EAI::File::writeText written $i of $lines\r" if $countPercent and ($i % (int($lines * ($countPercent / 100)) == 0 ? 1 : int($lines * ($countPercent / 100))) == 0); | ||
| 704 | } | ||
| 705 | close FHOUT; | ||
| 706 | return 1; | ||
| 707 | } | ||
| 708 | |||
| 709 | # write Excel file | ||
| 710 | sub writeExcel ($$;$) { | ||
| 711 | my ($File,$data,$countPercent) = @_; | ||
| 712 | my $logger = get_logger(); | ||
| 713 | |||
| 714 | if (ref($data) ne 'ARRAY') { | ||
| 715 | $logger->error("passed data in \$data is not a ref to array:".Dumper($data).longmess()); | ||
| 716 | return 0; | ||
| 717 | } | ||
| 718 | my @columnnames; | ||
| 719 | if (ref($File->{columns}) eq 'HASH') { | ||
| 720 | @columnnames = map {$File->{columns}{$_}} sort keys %{$File->{columns}}; | ||
| 721 | } elsif (ref($File->{columns}) eq 'ARRAY') { | ||
| 722 | @columnnames = @{$File->{columns}}; | ||
| 723 | } else { | ||
| 724 | $logger->error("no field information given (columns should be ref to array or ref to hash, you have to initialize it as that)".longmess()); | ||
| 725 | return 0; | ||
| 726 | } | ||
| 727 | my ($workbook,$worksheet); | ||
| 728 | if ($File->{format_xlformat} =~ /^xls$/i) { | ||
| 729 | $logger->debug("writing to xls format file ".$File->{filename}); | ||
| 730 | $workbook = Spreadsheet::WriteExcel->new($File->{filename}) or do { | ||
| 731 | $logger->error("xls file creation error: $!".longmess()); | ||
| 732 | return 0; | ||
| 733 | }; | ||
| 734 | } elsif ($File->{format_xlformat} =~ /^xlsx$/i) { | ||
| 735 | $logger->debug("writing to xlsx format file ".$File->{filename}); | ||
| 736 | $workbook = Excel::Writer::XLSX->new($File->{filename}) or do { | ||
| 737 | $logger->error("xlsx file creation error: $!".longmess()); | ||
| 738 | return 0; | ||
| 739 | }; | ||
| 740 | } else { | ||
| 741 | $logger->error("unrecognised excel format passed in \$File->{format_xlformat}:".$File->{format_xlformat}." (allowed: xls and xlsx)".longmess()); | ||
| 742 | return 0; | ||
| 743 | } | ||
| 744 | # Add a worksheet | ||
| 745 | $worksheet = $workbook->add_worksheet(); | ||
| 746 | $logger->debug("fields: @columnnames"); | ||
| 747 | my @headerRow; | ||
| 748 | for my $colname (@columnnames) { | ||
| 749 | if (!$File->{columnskip}{$colname}) { | ||
| 750 | push @headerRow, $colname; | ||
| 751 | } | ||
| 752 | } | ||
| 753 | # write header | ||
| 754 | unless ($File->{format_suppressHeader}) { | ||
| 755 | for my $col (0 .. @headerRow) { | ||
| 756 | $worksheet->write(0,$col,$headerRow[$col]); | ||
| 757 | } | ||
| 758 | } | ||
| 759 | # write data | ||
| 760 | $logger->trace("passed data:\n".Dumper($data)) if $logger->is_trace; | ||
| 761 | my $lines = scalar(@{$data}); | ||
| 762 | for (my $i=0; $i<$lines; $i++) { | ||
| 763 | # data row | ||
| 764 | my $row = $data->[$i]; | ||
| 765 | my @lineRow; | ||
| 766 | # chain all data in a row | ||
| 767 | for my $colname (@columnnames) { | ||
| 768 | if (!$File->{columnskip}{$colname}) { | ||
| 769 | $logger->error("row passed in (\$data) is no ref to hash! should be \$VAR1 = {'key' => 'value', ...}:\n".Dumper($row).longmess()) if (ref($row) ne "HASH"); | ||
| 770 | my $value = $row->{$colname}; | ||
| 771 | $logger->trace("\$value for \$colname $colname: $value") if $logger->is_trace; | ||
| 772 | if ($File->{addtlProcessingTrigger} && $File->{addtlProcessing}) { | ||
| 773 | eval $File->{addtlProcessingTrigger} if (eval $File->{addtlProcessingTrigger}); | ||
| 774 | $logger->error("error in eval addtlProcessing: ".$File->{addtlProcessingTrigger}.":".$@.longmess()) if ($@); | ||
| 775 | } | ||
| 776 | push @lineRow, $value; | ||
| 777 | } | ||
| 778 | } | ||
| 779 | for my $col (0 .. @lineRow) { | ||
| 780 | $worksheet->write($i+1,$col,$lineRow[$col]); | ||
| 781 | } | ||
| 782 | print "EAI::File::writeExcel written $i of $lines\r" if $countPercent and ($i % (int($lines * ($countPercent / 100)) == 0 ? 1 : int($lines * ($countPercent / 100))) == 0); | ||
| 783 | $logger->trace("row: @lineRow") if $logger->is_trace(); | ||
| 784 | } | ||
| 785 | $workbook->close(); | ||
| 786 | return 1; | ||
| 787 | } | ||
| 788 | 1; | ||
| 789 | __END__ | ||