| 1 | package Excel::Template::XLSX; | ||
| 2 | |||
| 3 | 1 | ▶ | use strict; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 4 | 1 | ▶ | use warnings; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 5 | 1 | ▶ | use base 'Excel::Writer::XLSX'; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 6 | 1 | ▶ | use Excel::Writer::XLSX::Utility; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 7 | |||
| 8 | 1 | ▶ | use version; our $VERSION = version->declare("v1.1.3"); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 9 | |||
| 10 | 1 | ▶ | use Archive::Zip; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 11 | 1 | ▶ | use Graphics::ColorUtils 'rgb2hls', 'hls2rgb'; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 12 | 1 | ▶ | use Scalar::Util 'openhandle'; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 13 | 0 | ▶ | use XML::Twig; |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 14 | |||
| 15 | 1; # Return True from module | ||
| 16 | |||
| 17 | ############################################################################### | ||
| 18 | sub __podhead { | ||
| 19 | |||
| 20 | =for pod | ||
| 21 | |||
| 22 | =head1 NAME | ||
| 23 | |||
| 24 | Excel-Template-XLSX - Create Excel .xlsx files starting from (one or more) template(s). | ||
| 25 | |||
| 26 | =head1 SYNOPSIS | ||
| 27 | |||
| 28 | use Excel::Template::XLSX; | ||
| 29 | my ($self, $workbook) = Excel::Template::XLSX->new('perl.xlsx', 'template1.xlsx', 'template2.xlsx', ...); | ||
| 30 | $self->parse_template(); | ||
| 31 | |||
| 32 | # Add a worksheet, ... and anything else you would do with Excel::Writer::XLSX | ||
| 33 | $worksheet = $workbook->add_worksheet(); | ||
| 34 | |||
| 35 | # Although Excel::Writer::XLSX says the workbook will automatically get | ||
| 36 | # closed during global destruction. This wrapper around Excel::Writer::XLSX may | ||
| 37 | # mess this up, and it is better to specifically close your workbook when you are done. | ||
| 38 | $workbook->close(); | ||
| 39 | |||
| 40 | =head1 DESCRIPTION | ||
| 41 | |||
| 42 | This module is a companion to | ||
| 43 | L<Excel::Writer::XLSX|https://metacpan.org/release/Excel-Writer-XLSX>(EWX), or | ||
| 44 | if you prefer, a wrapper to that module. It uses EWX as a base class. It opens | ||
| 45 | an existing spreadsheet file (.xlsx format), and also creates a new EWX object. | ||
| 46 | As it parses the template file(s), it calls EWX methods to re-create the template | ||
| 47 | contents in the EWX object. | ||
| 48 | |||
| 49 | When parsing is complete, the workbook object is left open for the calling perl | ||
| 50 | script to add additional content. | ||
| 51 | |||
| 52 | The purpose of this module is to separate the roles of content/presentation vs | ||
| 53 | programming in an Excel document, in much the same way that HTML templating | ||
| 54 | engines work. A user who is knowledgeable in Excel can create an Excel file for | ||
| 55 | use as a template, without requiring the skill set of Perl or | ||
| 56 | Excel::Writer::XLSX. Conversely, the Perl programmer who is creating dynamic | ||
| 57 | content does not need design skills to layout the presentation in the template. | ||
| 58 | |||
| 59 | =head1 WHAT IT CAN DO | ||
| 60 | |||
| 61 | Cell Values (strings, numbers, dates, ... ) | ||
| 62 | Cell Formulas | ||
| 63 | Cell Hyperlinks | ||
| 64 | |||
| 65 | Cell Formatting (borders, shading, fonts, font sizes, colors) | ||
| 66 | |||
| 67 | Column Widths | ||
| 68 | Row Widths | ||
| 69 | |||
| 70 | Headers and Footers | ||
| 71 | |||
| 72 | Simple template variables (via callback) See L</"template_callback"> | ||
| 73 | |||
| 74 | =head1 WHAT IT CAN NOT DO | ||
| 75 | |||
| 76 | Excel::Template::Excel can not modify Excel files in place! It is not | ||
| 77 | intended to. Since the parser directly adds content to the EWX workbook object | ||
| 78 | as the contents are parsed, both the template, and the output file must | ||
| 79 | be open at the same time. | ||
| 80 | |||
| 81 | It may be possible to open the output file to a file handle, and | ||
| 82 | after parsing of the template is complete, write the contents of file | ||
| 83 | over the template. The author has not tried this. | ||
| 84 | |||
| 85 | It is not the design of this module to faithfully re-create the entire | ||
| 86 | contents of the template file in the EWX output. If you are using this | ||
| 87 | module to rewrite Excel files, you are on your own. | ||
| 88 | |||
| 89 | These items are completely dropped from the output file: | ||
| 90 | |||
| 91 | Images in the Sheet | ||
| 92 | Images in Headers/Footers | ||
| 93 | Charts | ||
| 94 | Shapes | ||
| 95 | Themes (gradients, fonts, fills, styles) | ||
| 96 | macros | ||
| 97 | modules (vba code) | ||
| 98 | |||
| 99 | And probably other things. See the tests (t directory of the distribution) | ||
| 100 | for examples of what does work. | ||
| 101 | |||
| 102 | =head1 SUBROUTINES AND METHODS | ||
| 103 | |||
| 104 | =head2 __podhead | ||
| 105 | |||
| 106 | Dummy subroutine to allow me to hide this pod documentation when using code | ||
| 107 | folding in the editor. | ||
| 108 | |||
| 109 | =cut | ||
| 110 | |||
| 111 | } | ||
| 112 | ############################################################################### | ||
| 113 | sub new { | ||
| 114 | |||
| 115 | =head2 new | ||
| 116 | |||
| 117 | Creates a new Excel::Template::XLSX object, and also creates a new | ||
| 118 | Excel::Writer::XLSX object. A workbook object is created for the output file. | ||
| 119 | |||
| 120 | Returns the Template object, and the workbook object. Workbook object is also | ||
| 121 | available as $self->{EWX}; If the caller is only expecting a single | ||
| 122 | return value, then just the $self object is returned. | ||
| 123 | |||
| 124 | =cut | ||
| 125 | |||
| 126 | my ( $class, $output_file, @template_files ) = @_; | ||
| 127 | my $self = { | ||
| 128 | CELL_FORMAT => [], | ||
| 129 | FORMATS => [], | ||
| 130 | HYPERLINKS => {}, | ||
| 131 | NEED_PROPS => 1, | ||
| 132 | PRINT_AREA => {}, | ||
| 133 | PRINT_TITLES => {}, | ||
| 134 | MERGED_RANGES => {}, | ||
| 135 | SHARED_STRINGS => [], | ||
| 136 | THEMES => [], | ||
| 137 | ZIP => [], | ||
| 138 | template_callback => undef, | ||
| 139 | }; | ||
| 140 | |||
| 141 | # Create a new Excel workbook | ||
| 142 | $self->{EWX} = Excel::Writer::XLSX->new($output_file); | ||
| 143 | if ( defined $self->{EWX} ) { | ||
| 144 | $self->{DEFAULT_FORMAT} = $self->{EWX}->add_format(); | ||
| 145 | bless $self, $class; | ||
| 146 | } | ||
| 147 | else { | ||
| 148 | die | ||
| 149 | "Can't create new Excel::Writer::XLSX object using file ($output_file) $!"; | ||
| 150 | } | ||
| 151 | |||
| 152 | foreach my $template_file (@template_files) { | ||
| 153 | my $zip = Archive::Zip->new; | ||
| 154 | if ( openhandle($template_file) ) { | ||
| 155 | bless $template_file, 'IO::File' | ||
| 156 | if ref($template_file) eq 'GLOB'; # sigh | ||
| 157 | my $status = $zip->readFromFileHandle($template_file); | ||
| 158 | unless ( $status == Archive::Zip::AZ_OK ) { | ||
| 159 | warn "Can't open filehandle as a zip file, skipping"; | ||
| 160 | $zip = undef; | ||
| 161 | } | ||
| 162 | } | ||
| 163 | elsif ( !ref($template_file) ) { | ||
| 164 | my $status = $zip->read($template_file); | ||
| 165 | unless ( $status == Archive::Zip::AZ_OK ) { | ||
| 166 | $template_file //= '(undef)'; | ||
| 167 | warn "Can't open file '$template_file' as a zip file, skipping"; | ||
| 168 | $zip = undef; | ||
| 169 | } | ||
| 170 | } | ||
| 171 | else { | ||
| 172 | warn | ||
| 173 | "Argument to 'new' must be a filename or open filehandle. skipping $template_file"; | ||
| 174 | $zip = undef; | ||
| 175 | } | ||
| 176 | |||
| 177 | # Create a list of template files to add to the workbook | ||
| 178 | push @{ $self->{ZIP} }, $zip; | ||
| 179 | } | ||
| 180 | if (wantarray) { | ||
| 181 | return ( $self, $self->{EWX} ); | ||
| 182 | } | ||
| 183 | else { | ||
| 184 | return $self; | ||
| 185 | } | ||
| 186 | } | ||
| 187 | ############################################################################### | ||
| 188 | sub parse_template { | ||
| 189 | |||
| 190 | =head2 parse_template | ||
| 191 | |||
| 192 | Parses common elements of the Spreadsheet, such as themes, styles, and strings. | ||
| 193 | These are stored in the main object ($self). | ||
| 194 | |||
| 195 | Finds each sheet in the workbook, and initiates parsing of each sheet. | ||
| 196 | |||
| 197 | Properties for the created workbook are set from the first template that has | ||
| 198 | properties. Properties in subsequent workbooks are ignored. | ||
| 199 | |||
| 200 | =cut | ||
| 201 | |||
| 202 | my $self = shift; | ||
| 203 | |||
| 204 | my $remap = { | ||
| 205 | title => 'title', | ||
| 206 | subject => 'subject', | ||
| 207 | creator => 'author', | ||
| 208 | keywords => 'keywords', | ||
| 209 | description => 'comments', | ||
| 210 | |||
| 211 | manager => 'manager', | ||
| 212 | company => 'company', | ||
| 213 | category => 'category', | ||
| 214 | status => 'status', | ||
| 215 | }; | ||
| 216 | |||
| 217 | for my $z ( 0 .. $#{ $self->{ZIP} } ) { | ||
| 218 | my $zip = $self->{ZIP}[$z] // next; | ||
| 219 | $self->{PRINT_TITLES} = {}; | ||
| 220 | $self->{SHARED_STRINGS} = []; | ||
| 221 | $self->{FORMATS} = []; | ||
| 222 | |||
| 223 | my $files = $self->_extract_files($zip); | ||
| 224 | |||
| 225 | my $callback = $self->{template_callback}; | ||
| 226 | my $call = ref($callback) eq 'CODE'; | ||
| 227 | if ( $self->{NEED_PROPS} ) { | ||
| 228 | if ( my @core_nodes | ||
| 229 | = $files->{core}->find_nodes('//cp:coreProperties') ) | ||
| 230 | { | ||
| 231 | my $core = shift @core_nodes; | ||
| 232 | my %hash = map { | ||
| 233 | my $prop = $core->first_child( "dc:" . $_ ) | ||
| 234 | // $core->first_child( "cp:" . $_ ); | ||
| 235 | my %pair = (); | ||
| 236 | if ($prop) { | ||
| 237 | my $text = $prop->text(); | ||
| 238 | $call and $self->$callback( \$text ); | ||
| 239 | %pair = ( $remap->{$_}, $text ); | ||
| 240 | } | ||
| 241 | %pair; | ||
| 242 | } keys %$remap; | ||
| 243 | $self->{EWX}->set_properties(%hash); | ||
| 244 | $self->{NEED_PROPS} = 0; | ||
| 245 | } | ||
| 246 | } | ||
| 247 | |||
| 248 | $self->{THEMES} | ||
| 249 | = $self->_parse_themes( ( values %{ $files->{themes} } )[0] ); | ||
| 250 | |||
| 251 | $self->_parse_styles( $files->{styles} ); | ||
| 252 | $self->_parse_shared_strings( $files->{strings} ); | ||
| 253 | |||
| 254 | # Defined Names (includes print area, print titles) | ||
| 255 | map { | ||
| 256 | my $name = $_->att('name') // ''; | ||
| 257 | my $address = $_->text(); | ||
| 258 | |||
| 259 | # Print Titles (may contain none, one, or both. Delimited by comma if both supplied) | ||
| 260 | # e.g. Title_Page!$A:$A | ||
| 261 | if ( $name eq '_xlnm.Print_Titles' ) { | ||
| 262 | my @title = split( ',', $address ); | ||
| 263 | foreach (@title) { | ||
| 264 | my ( $sheet_name, $range ) = split('!'); | ||
| 265 | push @{ $self->{PRINT_TITLES}{$sheet_name} }, $range; | ||
| 266 | } | ||
| 267 | |||
| 268 | # Print Area (Save it until sheets are processed) | ||
| 269 | } | ||
| 270 | elsif ( $name eq '_xlnm.Print_Area' ) { | ||
| 271 | my @title = split( ',', $address ); | ||
| 272 | my ( $sheet_name, $range ) = split( '!', $address ); | ||
| 273 | $self->{PRINT_AREA}{$sheet_name} = $range; | ||
| 274 | } | ||
| 275 | else { | ||
| 276 | $self->{EWX}->define_name( $name, $address ); | ||
| 277 | } | ||
| 278 | } $files->{workbook}->find_nodes('//definedNames/definedName'); | ||
| 279 | |||
| 280 | # Sheets: Add a worksheet for each sheet in workbook | ||
| 281 | # Rename sheet if template(s) already has a sheet by that name | ||
| 282 | map { | ||
| 283 | my $name = $_->att('name'); | ||
| 284 | my $test = $name; | ||
| 285 | for ( my $i = 1; ; $i++ ) { | ||
| 286 | last unless $self->{EWX}->get_worksheet_by_name($test); | ||
| 287 | $test = $name . "($i)"; | ||
| 288 | } | ||
| 289 | my $sheet = $self->{EWX}->add_worksheet($test); | ||
| 290 | |||
| 291 | my $range = $self->{PRINT_AREA}{$name}; | ||
| 292 | $sheet->print_area($range) if $range; | ||
| 293 | |||
| 294 | foreach my $range ( @{ $self->{PRINT_TITLES}{$name} } ) { | ||
| 295 | |||
| 296 | if ($range =~ m/[A-Za-z]/) { # Column Range like $A:$A | ||
| 297 | $sheet->repeat_columns( $range ) | ||
| 298 | } else { | ||
| 299 | # Row Range like $1:$1 | ||
| 300 | $range =~ s/\$//g; | ||
| 301 | my ($first, $last) = split('\:', $range); | ||
| 302 | $sheet->repeat_rows( --$first, --$last ); | ||
| 303 | } | ||
| 304 | } | ||
| 305 | |||
| 306 | # Parse the contents of the sheet | ||
| 307 | my $idx = $_->att('r:id'); | ||
| 308 | $self->_parse_sheet( $sheet, $files->{sheets}{$idx} ); | ||
| 309 | } $files->{workbook}->find_nodes('//sheets/sheet'); | ||
| 310 | $self->{ZIP}[$z] = undef; | ||
| 311 | } | ||
| 312 | } | ||
| 313 | ############################################################################### | ||
| 314 | sub template_callback { | ||
| 315 | |||
| 316 | =head2 template_callback | ||
| 317 | |||
| 318 | Place holder method for a callback routine to modify the content of the template | ||
| 319 | before being written to the output spreadsheet. | ||
| 320 | |||
| 321 | This callback is activated for all shared string (both plain and rich text | ||
| 322 | strings), and also for header/footer text. | ||
| 323 | |||
| 324 | The callback is supplied with the two parameters: The object name (since this is | ||
| 325 | a method), and the text to be processed. This is passed as a reference to single | ||
| 326 | scalar. | ||
| 327 | |||
| 328 | This method is called numerous times during processing (e.g. once for each | ||
| 329 | unique string in the spreadsheet, so the user is advised to keep it efficient. | ||
| 330 | |||
| 331 | This callback approach does not force any particular templating system on the | ||
| 332 | user. They are free to use whatever system they choose. | ||
| 333 | |||
| 334 | Note that templating can only do simple scalars. Complex templating (if-then- | ||
| 335 | else, loops, etc) do not make sense in that the callback is supplied with the | ||
| 336 | contents of a single cell. Having said that, remember that the full power of | ||
| 337 | Excel::Writer::XLSX is available to the user to modify the template after it is | ||
| 338 | processed. | ||
| 339 | |||
| 340 | # A snippet of code to replace [% template %] in the | ||
| 341 | # template spreadsheet with 'Output' | ||
| 342 | |||
| 343 | my ($self, $wbk) = Excel::Template::XLSX->new($output_xlsx, $template_xlsx); | ||
| 344 | |||
| 345 | use Template::Tiny; | ||
| 346 | my $template = Template::Tiny->new( TRIM => 1 ); | ||
| 347 | $self->{template_callback} = sub { | ||
| 348 | my ($self, $textref) = @_; | ||
| 349 | $template->process($textref, { template => 'Output' }, $textref ); | ||
| 350 | }; | ||
| 351 | |||
| 352 | $self->parse_template(); | ||
| 353 | |||
| 354 | =cut | ||
| 355 | |||
| 356 | my $self = shift; | ||
| 357 | my ($text) = @_; | ||
| 358 | } | ||
| 359 | ############################################################################### | ||
| 360 | sub _apply_tint { | ||
| 361 | |||
| 362 | =head2 _apply_tint | ||
| 363 | |||
| 364 | Applies tinting to a color object, if the tint attribute is encountered in | ||
| 365 | parsing. | ||
| 366 | |||
| 367 | =cut | ||
| 368 | |||
| 369 | my $self = shift; | ||
| 370 | my ( $color, $tint ) = @_; | ||
| 371 | |||
| 372 | my ( $r, $g, $b ) = map { oct("0x$_") } $color =~ /#(..)(..)(..)/; | ||
| 373 | my ( $h, $l, $s ) = rgb2hls( $r, $g, $b ); | ||
| 374 | |||
| 375 | if ( $tint < 0 ) { | ||
| 376 | $l = $l * ( 1.0 + $tint ); | ||
| 377 | } | ||
| 378 | else { | ||
| 379 | $l = $l * ( 1.0 - $tint ) + ( 1.0 - 1.0 * ( 1.0 - $tint ) ); | ||
| 380 | } | ||
| 381 | |||
| 382 | return scalar hls2rgb( $h, $l, $s ); | ||
| 383 | } | ||
| 384 | ############################################################################### | ||
| 385 | sub _base_path_for { | ||
| 386 | |||
| 387 | =head2 _base_path_for | ||
| 388 | |||
| 389 | Manipulates the path to a member in the zip file, to find the associated | ||
| 390 | rels file. | ||
| 391 | |||
| 392 | =cut | ||
| 393 | |||
| 394 | my $self = shift; | ||
| 395 | my ($file) = @_; | ||
| 396 | |||
| 397 | my @path = split '/', $file; | ||
| 398 | pop @path; | ||
| 399 | |||
| 400 | return join( '/', @path ) . '/'; | ||
| 401 | } | ||
| 402 | ############################################################################### | ||
| 403 | sub _cell_to_row_col { | ||
| 404 | |||
| 405 | =head2 _cell_to_row_col | ||
| 406 | |||
| 407 | Converts an A1 style cell reference to a row and column index. | ||
| 408 | |||
| 409 | =cut | ||
| 410 | |||
| 411 | my $self = shift; | ||
| 412 | my $cell = shift; | ||
| 413 | |||
| 414 | my ( $col, $row ) = $cell =~ /([A-Z]+)([0-9]+)/; | ||
| 415 | |||
| 416 | my $ncol = 0; | ||
| 417 | for my $char ( split //, $col ) { | ||
| 418 | $ncol *= 26; | ||
| 419 | $ncol += ord($char) - ord('A') + 1; | ||
| 420 | } | ||
| 421 | $ncol = $ncol - 1; | ||
| 422 | my $nrow = $row - 1; | ||
| 423 | return ( $nrow, $ncol ); | ||
| 424 | } | ||
| 425 | ############################################################################### | ||
| 426 | sub _color { | ||
| 427 | |||
| 428 | =head2 _color | ||
| 429 | |||
| 430 | Parses color element (rgb, index, theme, and tint) | ||
| 431 | |||
| 432 | =cut | ||
| 433 | |||
| 434 | my $self = shift; | ||
| 435 | my ( $color_node, $fill ) = @_; | ||
| 436 | |||
| 437 | my $themes = $self->{THEMES}; | ||
| 438 | my $color; | ||
| 439 | if ( $color_node && !$color_node->att('auto') ) { | ||
| 440 | my $rgb = $color_node->att('rgb'); | ||
| 441 | my $theme = $color_node->att('theme'); | ||
| 442 | my $index = $color_node->att('indexed'); | ||
| 443 | my $tint = $color_node->att('tint'); | ||
| 444 | |||
| 445 | # see https://rt.cpan.org/Public/Bug/Display.html?id=93065 (still needed for XLSX??) | ||
| 446 | # defined $index and $color = ($fill && $index == 64) ? '#FFFFFF' : $index; | ||
| 447 | $rgb and $color = '#' . substr( $rgb, 2, 6 ); | ||
| 448 | defined $theme and $color = '#' . $themes->{Color}[$theme]; | ||
| 449 | $tint and $color = $self->_apply_tint( $color, $tint ); | ||
| 450 | } | ||
| 451 | return $color; | ||
| 452 | } | ||
| 453 | ############################################################################### | ||
| 454 | sub _extract_files { | ||
| 455 | |||
| 456 | =head2 _extract_files | ||
| 457 | |||
| 458 | Called by parse_template to fetch the xml strings from the zip file. XML | ||
| 459 | strings are parsed, except for worksheets. Individual worksheets are | ||
| 460 | parsed separately. | ||
| 461 | |||
| 462 | =cut | ||
| 463 | |||
| 464 | my $self = shift; | ||
| 465 | my ($zip) = @_; | ||
| 466 | |||
| 467 | my $type_base | ||
| 468 | = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'; | ||
| 469 | |||
| 470 | my $rels = $self->_parse_xml( $zip, $self->_rels_for('') ); | ||
| 471 | |||
| 472 | my $node = qq<//Relationship[\@Type="$type_base/officeDocument"]>; | ||
| 473 | my $wb_name = ( $rels->find_nodes($node) )[0]->att('Target'); | ||
| 474 | my $wb_xml = $self->_parse_xml( $zip, $wb_name ); | ||
| 475 | |||
| 476 | my $path_base = $self->_base_path_for($wb_name); | ||
| 477 | my $wb_rels = $self->_parse_xml( $zip, $self->_rels_for($wb_name) ); | ||
| 478 | |||
| 479 | my $string_xpath = qq<//Relationship[\@Type="$type_base/sharedStrings"]>; | ||
| 480 | my ($strings_xml) = map { | ||
| 481 | $zip->memberNamed( $path_base . $_->att('Target') )->contents | ||
| 482 | } $wb_rels->find_nodes($string_xpath); | ||
| 483 | |||
| 484 | my $style_xpath = qq<//Relationship[\@Type="$type_base/styles"]>; | ||
| 485 | my $style_target | ||
| 486 | = ( $wb_rels->find_nodes($style_xpath) )[0]->att('Target'); | ||
| 487 | my $styles_xml = $self->_parse_xml( $zip, $path_base . $style_target ); | ||
| 488 | |||
| 489 | my %sheet_rels; | ||
| 490 | my $wks_xpath = qq<//Relationship[\@Type="$type_base/worksheet"]>; | ||
| 491 | my %worksheet_xml = map { | ||
| 492 | |||
| 493 | my $sheet_file = $path_base . $_->att('Target'); | ||
| 494 | my $rels_file = $self->_rels_for($sheet_file); | ||
| 495 | my $sheet_rels = ''; | ||
| 496 | if ( $zip->memberNamed($rels_file) ) { | ||
| 497 | $sheet_rels = $self->_parse_xml( $zip, $rels_file ); | ||
| 498 | } | ||
| 499 | |||
| 500 | if ( my $contents = $zip->memberNamed($sheet_file)->contents ) { | ||
| 501 | ( $_->att('Id') => { 'xml' => $contents, 'rels' => $sheet_rels } ); | ||
| 502 | } | ||
| 503 | |||
| 504 | } $wb_rels->find_nodes($wks_xpath); | ||
| 505 | |||
| 506 | my %themes_xml = map { | ||
| 507 | $_->att('Id') => | ||
| 508 | $self->_parse_xml( $zip, $path_base . $_->att('Target') ) | ||
| 509 | } $wb_rels->find_nodes(qq<//Relationship[\@Type="$type_base/theme"]>); | ||
| 510 | |||
| 511 | my $core_base | ||
| 512 | = 'http://schemas.openxmlformats.org/package/2006/relationships/metadata'; | ||
| 513 | my $core_full = qq<//Relationship[\@Type="$core_base/core-properties"]>; | ||
| 514 | my $core_name = ( $rels->find_nodes($core_full) )[0]->att('Target'); | ||
| 515 | my $core_xml = $self->_parse_xml( $zip, $core_name ); | ||
| 516 | |||
| 517 | return { | ||
| 518 | workbook => $wb_xml, | ||
| 519 | styles => $styles_xml, | ||
| 520 | sheets => \%worksheet_xml, | ||
| 521 | themes => \%themes_xml, | ||
| 522 | core => $core_xml, | ||
| 523 | ( $strings_xml ? ( strings => $strings_xml ) : () ), | ||
| 524 | }; | ||
| 525 | } | ||
| 526 | ############################################################################### | ||
| 527 | sub _parse_alignment { | ||
| 528 | |||
| 529 | =head2 _parse_alignment | ||
| 530 | |||
| 531 | Parses horizontal and vertical cell alignments in a sheet. | ||
| 532 | |||
| 533 | =cut | ||
| 534 | |||
| 535 | my $self = shift; | ||
| 536 | my ($node) = @_; | ||
| 537 | |||
| 538 | my %align_map = ( | ||
| 539 | horizontal => 'align', | ||
| 540 | vertical => 'valign', | ||
| 541 | textRotation => 'rotation', | ||
| 542 | indent => 'indent', | ||
| 543 | wrapText => 'text_wrap', | ||
| 544 | shrinkToFit => 'shrink', | ||
| 545 | ); | ||
| 546 | my %align = (); | ||
| 547 | if ( my $alignment = $node->first_child('alignment') ) { | ||
| 548 | map { | ||
| 549 | my $v = $alignment->att($_); | ||
| 550 | if ( defined $v ) { | ||
| 551 | $v = 'vcenter' if ( $_ eq 'vertical' ) and ( $v eq 'center' ); | ||
| 552 | $align{ $align_map{$_} } = $v; | ||
| 553 | } | ||
| 554 | } keys %align_map; | ||
| 555 | } | ||
| 556 | return %align; | ||
| 557 | } | ||
| 558 | ############################################################################### | ||
| 559 | sub _parse_borders { | ||
| 560 | |||
| 561 | =head2 _parse_borders | ||
| 562 | |||
| 563 | Parses cell border and diagonal border styles. Called from _parse_styles. | ||
| 564 | Returns an array of border styles, each one as a hash. | ||
| 565 | |||
| 566 | =cut | ||
| 567 | |||
| 568 | my $self = shift; | ||
| 569 | my ($styles) = @_; | ||
| 570 | |||
| 571 | my $borders = []; | ||
| 572 | my %border_map = ( | ||
| 573 | dashDot => 9, | ||
| 574 | dashDotDot => 11, | ||
| 575 | dashed => 3, | ||
| 576 | dotted => 4, | ||
| 577 | double => 6, | ||
| 578 | hair => 7, | ||
| 579 | medium => 2, | ||
| 580 | mediumDashDot => 10, | ||
| 581 | mediumDashDotDot => 12, | ||
| 582 | mediumDashed => 8, | ||
| 583 | none => 0, | ||
| 584 | slantDashDot => 13, | ||
| 585 | thick => 5, | ||
| 586 | thin => 1, | ||
| 587 | ); | ||
| 588 | push @$borders, map { | ||
| 589 | my $border = $_; | ||
| 590 | |||
| 591 | # XXX specs say "begin" and "end" rather than "left" and "right", | ||
| 592 | # but... that's not what seems to be in the file itself (sigh) | ||
| 593 | |||
| 594 | my %colors = (); | ||
| 595 | map { | ||
| 596 | my $color | ||
| 597 | = $self->_color( | ||
| 598 | $border->first_child($_)->first_child('color') ); | ||
| 599 | $colors{ $_ . '_color' } = $color if $color; | ||
| 600 | } qw(left right top bottom); | ||
| 601 | |||
| 602 | my %types = (); | ||
| 603 | map { | ||
| 604 | my $style = $border->first_child($_)->att('style'); | ||
| 605 | $types{$_} = $border_map{$style} if $style; | ||
| 606 | } qw(left right top bottom); | ||
| 607 | |||
| 608 | my %diag = (); | ||
| 609 | my $down = $border->att('diagonalDown') // 0; | ||
| 610 | my $up = $border->att('diagonalUp') // 0; | ||
| 611 | $down = ($down =~ m/true|1/x) ? 1 : 0; | ||
| 612 | $up = ($up =~ m/true|1/x) ? 1 : 0; | ||
| 613 | $diag{'diag_type'} = 2 * $down + $up if $down + $up; | ||
| 614 | my $dborder = $border->first_child('diagonal')->att('style'); | ||
| 615 | $diag{'diag_border'} = $border_map{$dborder} if $dborder; | ||
| 616 | my $dcolor = $border->first_child('diagonal')->first_child('color'); | ||
| 617 | $diag{'diag_color'} = $self->_color($dcolor) if $dcolor; | ||
| 618 | |||
| 619 | my $border_ref = { %colors, %types, %diag }; | ||
| 620 | |||
| 621 | } $styles->find_nodes('//borders/border'); | ||
| 622 | return $borders; | ||
| 623 | } | ||
| 624 | ############################################################################### | ||
| 625 | sub _parse_fills { | ||
| 626 | |||
| 627 | =head2 _parse_fills | ||
| 628 | |||
| 629 | Parses styles for cell fills (pattern, foreground and background colors. | ||
| 630 | horizontal and horizontal and vertical cell alignments in a sheet. | ||
| 631 | |||
| 632 | Gradients are parsed, but since EWX does not support gradients, a | ||
| 633 | pattern is substituted. | ||
| 634 | |||
| 635 | =cut | ||
| 636 | |||
| 637 | my $self = shift; | ||
| 638 | my ($styles) = @_; | ||
| 639 | my %fill_map = ( | ||
| 640 | darkDown => 7, | ||
| 641 | darkGray => 3, | ||
| 642 | darkGrid => 9, | ||
| 643 | darkHorizontal => 5, | ||
| 644 | darkTrellis => 10, | ||
| 645 | darkUp => 8, | ||
| 646 | darkVertical => 6, | ||
| 647 | gray0625 => 18, | ||
| 648 | gray125 => 17, | ||
| 649 | lightDown => 13, | ||
| 650 | lightGray => 4, | ||
| 651 | lightGrid => 15, | ||
| 652 | lightHorizontal => 11, | ||
| 653 | lightTrellis => 16, | ||
| 654 | lightUp => 14, | ||
| 655 | lightVertical => 12, | ||
| 656 | mediumGray => 2, | ||
| 657 | none => 0, | ||
| 658 | solid => 1, | ||
| 659 | ); | ||
| 660 | |||
| 661 | # Pattern Fills / # Gradient Fills | ||
| 662 | # EWX does not support Gradient fills (yet??) | ||
| 663 | # so, substitute a pattern fill to keep indices aligned | ||
| 664 | my $fills = []; | ||
| 665 | push @$fills, map { | ||
| 666 | my ( $fill, @color ); | ||
| 667 | my $pat = $_->first_child('patternFill'); | ||
| 668 | if ($pat) { | ||
| 669 | for (qw[fg bg]) { | ||
| 670 | my $fgbg = $self->_color( $pat->first_child("${_}Color"), 1 ); | ||
| 671 | push @color, ( "${_}_color", $fgbg ) if $fgbg; | ||
| 672 | } | ||
| 673 | $fill = { pattern => $fill_map{ $pat->att('patternType') }, @color }; | ||
| 674 | } | ||
| 675 | my $gradient = $_->first_child('gradientFill'); | ||
| 676 | if ($gradient) { | ||
| 677 | my @stop_colors = $gradient->find_nodes('stop/color'); | ||
| 678 | my $fg = $self->_color( $stop_colors[0], 1 ); | ||
| 679 | my $bg = $self->_color( $stop_colors[1], 1 ); | ||
| 680 | my %hfg = ( 'fg_color' => ( $fg // 'white' ) ); | ||
| 681 | my %hbg = ( 'bg_color' => ( $bg // 'black' ) ); | ||
| 682 | |||
| 683 | ### ?? Create a lightGrid pattern in place of a gradient for now | ||
| 684 | $fill = { pattern => $fill_map{'lightGrid'}, %hfg, %hbg }; | ||
| 685 | } | ||
| 686 | $fill; | ||
| 687 | } $styles->find_nodes('//fills/fill'); | ||
| 688 | $fills; | ||
| 689 | } | ||
| 690 | ############################################################################### | ||
| 691 | sub _parse_fonts { | ||
| 692 | |||
| 693 | =head2 _parse_fonts | ||
| 694 | |||
| 695 | Parses font information (font name, size, super/sub scripts, alignment | ||
| 696 | colors, underline, bold, italic, and strikeout attributes). | ||
| 697 | |||
| 698 | =cut | ||
| 699 | |||
| 700 | my $self = shift; | ||
| 701 | my ( $styles, $xpath ) = @_; | ||
| 702 | $xpath //= '//fonts/font'; | ||
| 703 | |||
| 704 | my $fonts = []; | ||
| 705 | @$fonts = map { | ||
| 706 | |||
| 707 | my $u = $_->first_child('u'); | ||
| 708 | my $vert = $_->first_child('vertAlign'); | ||
| 709 | my $font; | ||
| 710 | |||
| 711 | my $size = $_->first_child('sz')->att('val'); | ||
| 712 | $font->{'size'} = $size if $size; | ||
| 713 | |||
| 714 | # XXX if color tag is missing is it black?? '#000000' | ||
| 715 | my $color = $_->first_child('color'); | ||
| 716 | $font->{'color'} = $self->_color($color) if $color; | ||
| 717 | |||
| 718 | my $script_map = { | ||
| 719 | 'superscript' => 1, | ||
| 720 | 'subscript' => 2, | ||
| 721 | }; | ||
| 722 | |||
| 723 | if ( defined $vert ) { | ||
| 724 | my $script = $vert->att('val'); | ||
| 725 | $font->{'font_script'} = $script_map->{$script} if $script; | ||
| 726 | } | ||
| 727 | |||
| 728 | my $u_map = { | ||
| 729 | 'single' => 1, | ||
| 730 | 'double' => 2, | ||
| 731 | 'singleAccounting' => 33, | ||
| 732 | 'doubleAccounting' => 34, | ||
| 733 | }; | ||
| 734 | if ( defined $u ) { | ||
| 735 | |||
| 736 | # XXX sometimes style xml files can contain just <u/> with no | ||
| 737 | # val attribute. i think this means single underline, but not sure | ||
| 738 | my $underline = $u->att('val') // 'single'; | ||
| 739 | $font->{'underline'} = $u_map->{$underline} if $underline; | ||
| 740 | } | ||
| 741 | |||
| 742 | my $font_name = $_->first_child('name'); | ||
| 743 | $font->{'font'} = $font_name->att('val') if $font_name; | ||
| 744 | |||
| 745 | # Alternate for rich strings (embedded font) | ||
| 746 | my $rFont = $_->first_child('rFont'); | ||
| 747 | $font->{'font'} = $rFont->att('val') if $rFont; | ||
| 748 | |||
| 749 | my $bold = $_->first_child('b'); | ||
| 750 | $font->{'bold'} = 1 if $bold; | ||
| 751 | |||
| 752 | my $italic = $_->first_child('i'); | ||
| 753 | $font->{'italic'} = 1 if $italic; | ||
| 754 | |||
| 755 | my $strike = $_->first_child('strike'); | ||
| 756 | $font->{'font_strikeout'} = 1 if $strike; | ||
| 757 | |||
| 758 | $font; | ||
| 759 | } $styles->find_nodes($xpath); | ||
| 760 | return $fonts; | ||
| 761 | } | ||
| 762 | ############################################################################### | ||
| 763 | sub _parse_numbers { | ||
| 764 | |||
| 765 | =head2 _parse_numbers | ||
| 766 | |||
| 767 | Parses styles for cell number formats (financial, decimal, exponential, date-time, ...) | ||
| 768 | |||
| 769 | =cut | ||
| 770 | |||
| 771 | my $self = shift; | ||
| 772 | my ($styles) = @_; | ||
| 773 | my $number_format = { 0 => {} }; | ||
| 774 | map { | ||
| 775 | my $id = $_->att('numFmtId') // 0; | ||
| 776 | |||
| 777 | # defaults are from | ||
| 778 | #http://social.msdn.microsoft.com/Forums/en-US/oxmlsdk/thread/e27aaf16-b900-4654-8210-83c5774a179c | ||
| 779 | # Defaults do not need to be re-created. | ||
| 780 | my $code = $_->att('formatCode') // $id; | ||
| 781 | $number_format->{$id} = { num_format => $code } if $id; | ||
| 782 | } $styles->find_nodes('//numFmts/numFmt'); | ||
| 783 | return $number_format; | ||
| 784 | } | ||
| 785 | ############################################################################### | ||
| 786 | sub _parse_protection { | ||
| 787 | |||
| 788 | =head2 _parse_protection | ||
| 789 | |||
| 790 | Parses locked and hidden attributes for a cell. These are only | ||
| 791 | useful if the worksheet is locked. | ||
| 792 | |||
| 793 | This module does not lock the workbook or the worksheet. | ||
| 794 | |||
| 795 | =cut | ||
| 796 | |||
| 797 | my $self = shift; | ||
| 798 | my ($node) = @_; | ||
| 799 | my @protection = qw(locked hidden); | ||
| 800 | my %prot = (); | ||
| 801 | if ( my $protection = $_->first_child('protection') ) { | ||
| 802 | map { | ||
| 803 | my $v = $protection->att($_); | ||
| 804 | $prot{$_} = $v if defined $v; | ||
| 805 | } @protection; | ||
| 806 | } | ||
| 807 | return %prot; | ||
| 808 | } | ||
| 809 | ############################################################################### | ||
| 810 | sub _parse_shared_strings { | ||
| 811 | |||
| 812 | =head2 _parse_shared_strings | ||
| 813 | |||
| 814 | Parses the shared strings file. Excel does not directly store | ||
| 815 | string values with the cell, but stores an index into the shared | ||
| 816 | strings table instead, to save memory, if a string value is | ||
| 817 | referenced more than once. Shared strings also contain | ||
| 818 | formatting if multiple formats are applied within a cell (See | ||
| 819 | write_rich_string in EWX. | ||
| 820 | |||
| 821 | =cut | ||
| 822 | |||
| 823 | my $self = shift; | ||
| 824 | my ($strings) = @_; | ||
| 825 | |||
| 826 | return unless $strings; | ||
| 827 | my $xml = XML::Twig->new( | ||
| 828 | twig_handlers => { | ||
| 829 | 'si' => sub { | ||
| 830 | my ( $twig, $si ) = @_; | ||
| 831 | |||
| 832 | my $callback = $self->{template_callback}; | ||
| 833 | my $call = ref($callback) eq 'CODE'; | ||
| 834 | |||
| 835 | # plain text strings | ||
| 836 | my $t = $si->first_child('t'); | ||
| 837 | if ($t) { | ||
| 838 | my $text = $t->text(); | ||
| 839 | $call and $self->$callback( \$text ); | ||
| 840 | push @{ $self->{SHARED_STRINGS} }, $text; | ||
| 841 | } | ||
| 842 | |||
| 843 | # rich text strings; String item (si) with multiple | ||
| 844 | # text elements, with optional formatting | ||
| 845 | my $rich = []; | ||
| 846 | for my $r ( $si->find_nodes('r') ) { | ||
| 847 | my $text = $r->first_child('t')->text(); | ||
| 848 | $call and $self->$callback( \$text ); | ||
| 849 | my $rPr = $r->first_child('rPr'); | ||
| 850 | |||
| 851 | if ($rPr) { | ||
| 852 | my $xml = $r->first_child('rPr')->outer_xml(); | ||
| 853 | my $twig = XML::Twig->parse($xml); | ||
| 854 | my $fonts = $self->_parse_fonts( $twig, '//rPr' ); | ||
| 855 | my $format = $self->{EWX}->add_format( %{ $fonts->[0] } ); | ||
| 856 | push @$rich, $format, $text; | ||
| 857 | } | ||
| 858 | else { | ||
| 859 | push @$rich, $text; | ||
| 860 | } | ||
| 861 | } | ||
| 862 | push( @{ $self->{SHARED_STRINGS} }, $rich ) if scalar(@$rich); | ||
| 863 | $twig->purge; | ||
| 864 | } | ||
| 865 | } | ||
| 866 | ); # } twig_handlers ) new | ||
| 867 | $xml->parse($strings); | ||
| 868 | } | ||
| 869 | ############################################################################### | ||
| 870 | sub _parse_sheet { | ||
| 871 | |||
| 872 | =head2 _parse_sheet | ||
| 873 | |||
| 874 | Parses an individual worksheet. This is done in two passes. | ||
| 875 | See _parse_sheet_pass1 and _parse_sheet_pass2 for what elements are | ||
| 876 | parsed. This is necessary because the parse order of XML::Twig callbacks | ||
| 877 | are in the wrong order for some sheet information (header/footer information, | ||
| 878 | hyperlinks, and merged cells). | ||
| 879 | |||
| 880 | =cut | ||
| 881 | |||
| 882 | my $self = shift; | ||
| 883 | my ( $sheet, $sheet_file ) = @_; | ||
| 884 | |||
| 885 | # Hyperlinks are local to each sheet | ||
| 886 | $self->{HYPERLINKS} = {}; | ||
| 887 | my $pass1 | ||
| 888 | = XML::Twig->new( twig_roots => $self->_parse_sheet_pass1($sheet) ); | ||
| 889 | $pass1->parse( $sheet_file->{xml} ); | ||
| 890 | |||
| 891 | # Half time show - track down the URLs for hyperlinks found in pass 1 | ||
| 892 | |||
| 893 | # warn "Sheet is $sheet->{_index}: ", dumper ( $self->{MERGED_RANGES} ); | ||
| 894 | |||
| 895 | while ( my ( $a1, $rid ) = each %{ $self->{HYPERLINKS} } ) { | ||
| 896 | my $xpath = qq<//Relationship[\@Id="$rid"]>; | ||
| 897 | my $url = ( $sheet_file->{rels}->find_nodes($xpath) )[0]; | ||
| 898 | if ($url) { | ||
| 899 | my $target = $url->att('Target'); | ||
| 900 | my $mode = lc( $url->att('TargetMode') ); | ||
| 901 | $self->{HYPERLINKS}{$a1} = "$target"; | ||
| 902 | } | ||
| 903 | } | ||
| 904 | |||
| 905 | # 2nd pass: cell/row building is dependent on having parsed the merge definitions | ||
| 906 | # beforehand. Also header/footer margins must be parsed before setting header/footer | ||
| 907 | my $pass2 | ||
| 908 | = XML::Twig->new( twig_roots => $self->_parse_sheet_pass2($sheet) ); | ||
| 909 | $pass2->parse( $sheet_file->{xml} ); | ||
| 910 | |||
| 911 | # EndGame: Process any merge ranges that exist, but have no cell content. | ||
| 912 | $self->_parse_final_pass($sheet); | ||
| 913 | } | ||
| 914 | ############################################################################### | ||
| 915 | sub _parse_sheet_pass1 { | ||
| 916 | |||
| 917 | =head2 _parse_sheet_pass1 | ||
| 918 | |||
| 919 | Parses some elements in a worksheet ( pageMargins, headerFooter, | ||
| 920 | hyperlinks, pageSetup, Merged Cells, Sheet Formatting Row and Column | ||
| 921 | heights, Sheet selection, and Tab Color) | ||
| 922 | |||
| 923 | =cut | ||
| 924 | |||
| 925 | my $self = shift; | ||
| 926 | my ($sheet) = @_; | ||
| 927 | |||
| 928 | my $default_row_height = 15; | ||
| 929 | my $default_column_width = 10; | ||
| 930 | my %hf_margin; | ||
| 931 | |||
| 932 | return { | ||
| 933 | 'pageMargins' => sub { | ||
| 934 | my ( $twig, $margin ) = @_; | ||
| 935 | map { | ||
| 936 | my $method = "set_margin_" . $_; | ||
| 937 | $sheet->$method( $margin->att($_) // 0 ); | ||
| 938 | } qw( left right top bottom ); | ||
| 939 | |||
| 940 | # Capture header/footer margin, for use with headerFooter callback | ||
| 941 | $hf_margin{Header} = $margin->att('header'); | ||
| 942 | $hf_margin{Footer} = $margin->att('footer'); | ||
| 943 | $twig->purge; | ||
| 944 | }, | ||
| 945 | |||
| 946 | # Headers/Footers | ||
| 947 | 'headerFooter' => sub { | ||
| 948 | my ( $twig, $hf ) = @_; | ||
| 949 | |||
| 950 | my $callback = $self->{template_callback}; | ||
| 951 | my $call = ref($callback) eq 'CODE'; | ||
| 952 | for (qw[Header Footer]) { | ||
| 953 | my $child = $hf->first_child( 'odd' . $_ ); | ||
| 954 | my $text = $child ? $child->text() : ''; | ||
| 955 | $call and $self->$callback( \$text ); | ||
| 956 | my $method = 'set_' . lc($_); | ||
| 957 | $sheet->$method( $text, $hf_margin{$_} ); | ||
| 958 | } | ||
| 959 | |||
| 960 | $twig->purge; | ||
| 961 | }, | ||
| 962 | |||
| 963 | # Hyperlinks | ||
| 964 | 'hyperlinks/hyperlink ' => sub { | ||
| 965 | my ( $twig, $link ) = @_; | ||
| 966 | my $a1 = $link->att('ref'); | ||
| 967 | $self->{HYPERLINKS}{$a1} = $link->att('r:id'); | ||
| 968 | $twig->purge; | ||
| 969 | }, | ||
| 970 | |||
| 971 | # Paper/page setup | ||
| 972 | 'pageSetup' => sub { | ||
| 973 | my ( $twig, $setup ) = @_; | ||
| 974 | my %lookup = ( | ||
| 975 | orientation => => 'set_portrait', | ||
| 976 | firstPageNumber => 'set_start_page', | ||
| 977 | scale => 'set_print_scale', | ||
| 978 | paperSize => 'set_paper' | ||
| 979 | |||
| 980 | # horizontalDpi ?? | ||
| 981 | # verticalDpi | ||
| 982 | ); | ||
| 983 | |||
| 984 | my @page | ||
| 985 | = qw(scale orientation horizontalDpi verticalDpi paperSize firstPageNumber scale); | ||
| 986 | foreach (@page) { | ||
| 987 | |||
| 988 | # Ignore if we do not have a EWX method for this attribute | ||
| 989 | my $method = $lookup{$_} // next; | ||
| 990 | |||
| 991 | # Ignore if no value defined for this attribute | ||
| 992 | next unless my $set = $setup->att($_); | ||
| 993 | |||
| 994 | # Special case; no generic method to set portrait/landscape | ||
| 995 | $method = 'set_landscape' if $set eq 'landscape'; | ||
| 996 | $sheet->$method($set); | ||
| 997 | } | ||
| 998 | |||
| 999 | $twig->purge; | ||
| 1000 | }, | ||
| 1001 | |||
| 1002 | # Merged cells (Create the ranges: content will be added later) | ||
| 1003 | 'mergeCells/mergeCell' => sub { | ||
| 1004 | my ( $twig, $merge_area ) = @_; | ||
| 1005 | |||
| 1006 | if ( my $ref = $merge_area->att('ref') ) { | ||
| 1007 | my ( $topleft, $bottomright ) = $ref =~ /([^:]+):([^:]+)/; | ||
| 1008 | # my ( $tr, $lc ) = $self->_cell_to_row_col($topleft); | ||
| 1009 | # my ( $br, $rc ) = $self->_cell_to_row_col($bottomright); | ||
| 1010 | |||
| 1011 | # Merged Ranges/Areas: save the address for pass 2. | ||
| 1012 | # cells within the merged range will be processed with | ||
| 1013 | # merge_range_type(), instead of write() | ||
| 1014 | $self->{MERGED_RANGES}{$sheet->{_index}}{$topleft} = $ref; | ||
| 1015 | } | ||
| 1016 | $twig->purge; | ||
| 1017 | }, | ||
| 1018 | |||
| 1019 | # Default row height | ||
| 1020 | 'dimension' => sub { | ||
| 1021 | my ( $twig, $format ) = @_; | ||
| 1022 | my $ref = $format->att('ref'); | ||
| 1023 | $self->_cell_to_row_col($ref); | ||
| 1024 | |||
| 1025 | $self->{_dim_rowmin} = undef; | ||
| 1026 | $self->{_dim_rowmax} = undef; | ||
| 1027 | $self->{_dim_colmin} = undef; | ||
| 1028 | $self->{_dim_colmax} = undef; | ||
| 1029 | |||
| 1030 | |||
| 1031 | $sheet->set_default_row($default_row_height); | ||
| 1032 | $twig->purge; | ||
| 1033 | }, | ||
| 1034 | |||
| 1035 | # Default row height | ||
| 1036 | 'sheetFormatPr' => sub { | ||
| 1037 | my ( $twig, $format ) = @_; | ||
| 1038 | $default_row_height //= $format->att('defaultRowHeight'); | ||
| 1039 | $default_column_width //= $format->att('baseColWidth'); | ||
| 1040 | $sheet->set_default_row($default_row_height); | ||
| 1041 | $twig->purge; | ||
| 1042 | }, | ||
| 1043 | |||
| 1044 | # Sets (one or more) column widths | ||
| 1045 | 'col' => sub { | ||
| 1046 | my ( $twig, $col ) = @_; | ||
| 1047 | |||
| 1048 | my $min = $col->att('min') - 1; | ||
| 1049 | my $max = $col->att('max') - 1; | ||
| 1050 | $sheet->set_column( $min, $max, $col->att('width') ); | ||
| 1051 | $twig->purge; | ||
| 1052 | }, | ||
| 1053 | |||
| 1054 | 'row' => sub { | ||
| 1055 | my ( $twig, $row ) = @_; | ||
| 1056 | |||
| 1057 | # ?? just sets row height. No formatting yet | ||
| 1058 | # set_row( $row, $height, $format, $hidden, $level, $collapsed ) | ||
| 1059 | $sheet->set_row( $row->att('r') - 1, $row->att('ht') ); | ||
| 1060 | $twig->purge; | ||
| 1061 | }, | ||
| 1062 | |||
| 1063 | 'sheetView/selection' => sub { | ||
| 1064 | my ( $twig, $selection ) = @_; | ||
| 1065 | my $range = $selection->att('sqref') | ||
| 1066 | // $selection->att('activeCell') // 'A1'; | ||
| 1067 | $sheet->set_selection($range); | ||
| 1068 | $twig->purge; | ||
| 1069 | }, | ||
| 1070 | |||
| 1071 | 'sheetPr/tabColor' => sub { | ||
| 1072 | my ( $twig, $tab_color ) = @_; | ||
| 1073 | $sheet->set_tab_color( $tab_color->att('rgb') ); | ||
| 1074 | $twig->purge; | ||
| 1075 | } | ||
| 1076 | |||
| 1077 | } # return hashref | ||
| 1078 | } | ||
| 1079 | ############################################################################### | ||
| 1080 | sub _parse_sheet_pass2 { | ||
| 1081 | |||
| 1082 | =head2 _parse_sheet_pass2 | ||
| 1083 | |||
| 1084 | Parses cell contents (first by row, then by column). Cells can contain | ||
| 1085 | inline strings, string references, direct string values, formulas, | ||
| 1086 | and hyperlinks. Each cell may also contain formatting information. | ||
| 1087 | The format is in an index to formatting for borders, shading, alignment, | ||
| 1088 | font, and number formats. | ||
| 1089 | |||
| 1090 | =cut | ||
| 1091 | |||
| 1092 | my $self = shift; | ||
| 1093 | my ($sheet) = @_; | ||
| 1094 | |||
| 1095 | return { | ||
| 1096 | 'sheetData/row' => sub { | ||
| 1097 | my ( $twig, $row_elt ) = @_; | ||
| 1098 | my $sheet_idx = $sheet->{_index}; | ||
| 1099 | for my $cell ( $row_elt->children('c') ) { | ||
| 1100 | |||
| 1101 | my $string_index = 0; | ||
| 1102 | my $a1 = $cell->att('r'); # Cell Address | ||
| 1103 | my $t = $cell->att('t') || 'n'; # Cell Type | ||
| 1104 | my $s = $cell->att('s') // 0; # Cell Format Index (e.g. styles) | ||
| 1105 | my ($r, $c) = $self->_cell_to_row_col($a1); | ||
| 1106 | $self->{CELL_FORMAT}->[$r][$c] = $s; | ||
| 1107 | my $val_xml | ||
| 1108 | = $t eq 'inlineStr' | ||
| 1109 | ? $cell->first_child('is')->first_child('t') | ||
| 1110 | : $cell->first_child('v'); | ||
| 1111 | my $val = $val_xml ? $val_xml->text() : undef; | ||
| 1112 | |||
| 1113 | |||
| 1114 | my $format_idx = $s; | ||
| 1115 | my $format = $self->{FORMATS}[$format_idx]; | ||
| 1116 | # Formatted cell, no contents | ||
| 1117 | if ( !defined($val) ) { | ||
| 1118 | $sheet->write_blank($a1, $format); | ||
| 1119 | next; | ||
| 1120 | } | ||
| 1121 | |||
| 1122 | if ( $t eq 's' ) { | ||
| 1123 | $string_index = $val; | ||
| 1124 | $val = $self->{SHARED_STRINGS}[$val]; | ||
| 1125 | |||
| 1126 | my $is_array = ref($val) eq 'ARRAY'; | ||
| 1127 | my @aval = $is_array ? @$val : ($val); | ||
| 1128 | if ( my $ref = $self->{MERGED_RANGES}{$sheet_idx}{$a1} ) { | ||
| 1129 | my $type = $is_array ? 'rich_string' : 'string'; | ||
| 1130 | $sheet->merge_range_type($type, $ref, @aval, $format ); | ||
| 1131 | $self->{MERGED_RANGES}{$sheet_idx}{$a1} = 0; # Flag it as used. Handle unused ranges at end | ||
| 1132 | next; | ||
| 1133 | } | ||
| 1134 | |||
| 1135 | # Special case for multiple formats in a cell | ||
| 1136 | # see _parse_shared_strings for rPr nodes | ||
| 1137 | if ( $is_array ) { | ||
| 1138 | $sheet->write_rich_string( $a1, @aval ); | ||
| 1139 | next; | ||
| 1140 | } | ||
| 1141 | if ( my $url = $self->{HYPERLINKS}{$a1} ) { | ||
| 1142 | $sheet->write_url( $a1, $url, $format, $val ); | ||
| 1143 | next; | ||
| 1144 | } | ||
| 1145 | $sheet->write_string( $a1, $val, $format ); | ||
| 1146 | next; | ||
| 1147 | } | ||
| 1148 | |||
| 1149 | # In-line string (not seen in practice) | ||
| 1150 | elsif ( $t eq 'str' ) { | ||
| 1151 | $val = '=' . $cell->first_child('f')->text(); | ||
| 1152 | } | ||
| 1153 | |||
| 1154 | # Formulas | ||
| 1155 | elsif ( $t eq 'n' ) { | ||
| 1156 | if ( my $form_child = $cell->first_child('f') ) { | ||
| 1157 | my $is_array = $form_child->att('t'); | ||
| 1158 | my $ref = $form_child->att('ref'); | ||
| 1159 | my $formula = $form_child->text() // q[="No Formula Found"]; | ||
| 1160 | if ($is_array and $ref) { | ||
| 1161 | $sheet->write_array_formula( $ref, "=${formula}", $format, $val ); | ||
| 1162 | } | ||
| 1163 | else { | ||
| 1164 | if ( my $ref = $self->{MERGED_RANGES}{$sheet_idx}{$a1} ) { | ||
| 1165 | $sheet->merge_range_type('formula', $ref, "=${formula}", $format, $val); | ||
| 1166 | $self->{MERGED_RANGES}{$sheet_idx}{$a1} = 0; # Flag it as used. Handle unused ranges at end | ||
| 1167 | } else { | ||
| 1168 | $sheet->write_formula( $a1, "=${formula}", $format, $val ); | ||
| 1169 | } | ||
| 1170 | } | ||
| 1171 | next; | ||
| 1172 | } | ||
| 1173 | |||
| 1174 | } | ||
| 1175 | elsif ( $t eq 'b' ) { | ||
| 1176 | $val = $val ? "TRUE" : "FALSE"; | ||
| 1177 | } | ||
| 1178 | elsif ( $t eq 'e' ) { | ||
| 1179 | } | ||
| 1180 | elsif ( $t eq 'str' || $t eq 'inlineStr' ) { | ||
| 1181 | } | ||
| 1182 | else { | ||
| 1183 | warn "unimplemented type $t found in cell $a1"; # XXX | ||
| 1184 | } | ||
| 1185 | |||
| 1186 | $sheet->write( $a1, $val, $format ); | ||
| 1187 | } | ||
| 1188 | |||
| 1189 | $twig->purge; | ||
| 1190 | } | ||
| 1191 | }; | ||
| 1192 | } | ||
| 1193 | ############################################################################### | ||
| 1194 | sub _parse_final_pass { | ||
| 1195 | |||
| 1196 | =head2 _parse_final_pass | ||
| 1197 | |||
| 1198 | Make a final pass to process merge_ranges that do not have any cell contents. | ||
| 1199 | This is it for now, but more may be added in the future. | ||
| 1200 | |||
| 1201 | =cut | ||
| 1202 | |||
| 1203 | my $self = shift; | ||
| 1204 | my ($sheet) = @_; | ||
| 1205 | my $idx = $sheet->{_index}; | ||
| 1206 | |||
| 1207 | foreach my $r (keys %{ $self->{MERGED_RANGES}->{ $idx } } ) { | ||
| 1208 | my $ref = $self->{MERGED_RANGES}->{ $idx }->{$r}; | ||
| 1209 | next unless $ref; # Only process merged ranges that have not been referenced yet. | ||
| 1210 | $sheet->merge_range_type('blank', $ref, $self->{FORMATS}[0]); | ||
| 1211 | my ($first, $last) = split('\:', $ref); | ||
| 1212 | my ($rf, $cf) = $self->_cell_to_row_col($first); | ||
| 1213 | my ($rl, $cl) = $self->_cell_to_row_col($last); | ||
| 1214 | for my $r ($rf .. $rl) { | ||
| 1215 | for my $c ($cf .. $cl) { | ||
| 1216 | my $fid = $self->{CELL_FORMAT}->[$r][$c] // 0; | ||
| 1217 | $sheet->write_blank($r, $c, $self->{FORMATS}[$fid] ); | ||
| 1218 | } | ||
| 1219 | } | ||
| 1220 | } | ||
| 1221 | } | ||
| 1222 | ############################################################################### | ||
| 1223 | sub _parse_styles { | ||
| 1224 | |||
| 1225 | =head2 _parse_styles | ||
| 1226 | |||
| 1227 | Parses style information. | ||
| 1228 | Parses number formats directly. Calls subroutines to parse | ||
| 1229 | fonts, fills, and borders, alignment, and protection. | ||
| 1230 | |||
| 1231 | Finally, parses Cell Xfs elements to Combine fonts, borders, number formats, | ||
| 1232 | alignment, patterns, into a single format specification. | ||
| 1233 | |||
| 1234 | Calls EWX add_formats to create a format, and stores the format information | ||
| 1235 | in a FORMAT array within the object. | ||
| 1236 | |||
| 1237 | =cut | ||
| 1238 | |||
| 1239 | my $self = shift; | ||
| 1240 | my ($styles) = @_; | ||
| 1241 | |||
| 1242 | # Number Formats | ||
| 1243 | my $numfmt = $self->_parse_numbers($styles); | ||
| 1244 | |||
| 1245 | # Fonts / Fills / Borders | ||
| 1246 | my $fonts = $self->_parse_fonts( $styles, '//fonts/font' ); | ||
| 1247 | my $fills = $self->_parse_fills($styles); | ||
| 1248 | my $borders = $self->_parse_borders($styles); | ||
| 1249 | |||
| 1250 | # Cell Xfs | ||
| 1251 | # Combine fonts, borders, number formats, alignment, patterns, into a single format spec | ||
| 1252 | map { | ||
| 1253 | # Also has applyAlignment property, which we do not examine | ||
| 1254 | # same for ApplyFont, ApplyBorder ApplyProtection | ||
| 1255 | |||
| 1256 | my %halign = $self->_parse_alignment($_); | ||
| 1257 | my %hprot = $self->_parse_protection($_); | ||
| 1258 | my %hfont = %{ $fonts->[ $_->att('fontId') // 0 ] }; | ||
| 1259 | |||
| 1260 | my $numFmtId = $_->att('numFmtId') // 0; | ||
| 1261 | # Use custom format, or built-in if custom not found | ||
| 1262 | my $ref = $numfmt->{$numFmtId} // { num_format => $numFmtId }; | ||
| 1263 | my %hnumfmt = %$ref; | ||
| 1264 | |||
| 1265 | my %hbord = %{ $borders->[ $_->att('borderId') // 0 ] }; | ||
| 1266 | my %hfill = %{ $fills->[ $_->att('fillId') // 0 ] }; | ||
| 1267 | |||
| 1268 | my $fmt | ||
| 1269 | = $self->{EWX} | ||
| 1270 | ->add_format( %hfont, %hnumfmt, %hbord, %halign, %hprot, %hfill ); | ||
| 1271 | push @{ $self->{FORMATS} }, $fmt; | ||
| 1272 | } $styles->find_nodes('//cellXfs/xf'); | ||
| 1273 | } | ||
| 1274 | ############################################################################### | ||
| 1275 | sub _parse_themes { | ||
| 1276 | |||
| 1277 | =head2 _parse_themes | ||
| 1278 | |||
| 1279 | Parses theme information. Some color settings are referenced by an | ||
| 1280 | index to the theme. | ||
| 1281 | |||
| 1282 | =cut | ||
| 1283 | |||
| 1284 | my $self = shift; | ||
| 1285 | my ($themes) = @_; | ||
| 1286 | |||
| 1287 | return {} unless $themes; | ||
| 1288 | |||
| 1289 | my @color | ||
| 1290 | = map { $_->name eq 'a:sysClr' ? $_->att('lastClr') : $_->att('val') } | ||
| 1291 | $themes->find_nodes('//a:clrScheme/*/*'); | ||
| 1292 | |||
| 1293 | # this shouldn't be necessary, but the documentation is wrong here | ||
| 1294 | # see http://stackoverflow.com/questions/2760976/theme-confusion-in-spreadsheetml | ||
| 1295 | ( $color[0], $color[1] ) = ( $color[1], $color[0] ); | ||
| 1296 | ( $color[2], $color[3] ) = ( $color[3], $color[2] ); | ||
| 1297 | |||
| 1298 | return { Color => \@color }; | ||
| 1299 | } | ||
| 1300 | ############################################################################### | ||
| 1301 | sub _parse_xml { | ||
| 1302 | |||
| 1303 | =head2 _parse_xml | ||
| 1304 | |||
| 1305 | Low level subroutine to parse an entire member of a zip file. Used | ||
| 1306 | for small files, such as xxx.xml.rels, where the entire file is parsed. | ||
| 1307 | |||
| 1308 | For larger files, XML::Twig::twig_handlers are used. | ||
| 1309 | |||
| 1310 | =cut | ||
| 1311 | |||
| 1312 | my $self = shift; | ||
| 1313 | my ( $zip, $subfile ) = @_; | ||
| 1314 | |||
| 1315 | my $member = $zip->memberNamed($subfile); | ||
| 1316 | die "no subfile named $subfile" unless $member; | ||
| 1317 | |||
| 1318 | my $xml = XML::Twig->new; | ||
| 1319 | $xml->parse( scalar $member->contents ); | ||
| 1320 | return $xml; | ||
| 1321 | } | ||
| 1322 | ############################################################################### | ||
| 1323 | sub _rels_for { | ||
| 1324 | |||
| 1325 | =head2 _rels_for | ||
| 1326 | |||
| 1327 | Returns the .rels file name for a sibling workbook or worksheet. | ||
| 1328 | |||
| 1329 | =cut | ||
| 1330 | |||
| 1331 | my $self = shift; | ||
| 1332 | my ($file) = @_; | ||
| 1333 | |||
| 1334 | my @path = split '/', $file; | ||
| 1335 | my $name = pop @path; | ||
| 1336 | $name = '' unless defined $name; | ||
| 1337 | push @path, '_rels'; | ||
| 1338 | push @path, "$name.rels"; | ||
| 1339 | |||
| 1340 | return join '/', @path; | ||
| 1341 | } | ||
| 1342 | ############################################################################### | ||
| 1343 | sub zzpodtail { | ||
| 1344 | |||
| 1345 | =for pod | ||
| 1346 | |||
| 1347 | =head2 zzpodtail | ||
| 1348 | |||
| 1349 | Dummy subroutine to allow me to hide pod documentation when using code | ||
| 1350 | folding in the editor. | ||
| 1351 | |||
| 1352 | =head1 INSTALLATION | ||
| 1353 | |||
| 1354 | Install with CPAN | ||
| 1355 | |||
| 1356 | cpan Excel::Template::XLSX | ||
| 1357 | |||
| 1358 | or, use the standard Unix style installation. | ||
| 1359 | |||
| 1360 | Unzip and untar the module as follows: | ||
| 1361 | |||
| 1362 | tar -zxvf Excel::Template::XLSX-nnn.tar.gz | ||
| 1363 | |||
| 1364 | The module can be installed using the standard Perl procedure: | ||
| 1365 | |||
| 1366 | perl Makefile.PL | ||
| 1367 | make | ||
| 1368 | make test | ||
| 1369 | make install # As sudo/root | ||
| 1370 | |||
| 1371 | =head1 BUGS | ||
| 1372 | |||
| 1373 | =over 4 | ||
| 1374 | |||
| 1375 | =item Large spreadsheets may cause segfaults on perl 5.14 and earlier | ||
| 1376 | |||
| 1377 | This module internally uses XML::Twig, which makes it potentially subject to | ||
| 1378 | L<Bug #71636 for XML-Twig: Segfault with medium-sized document|https://rt.cpan.org/Public/Bug/Display.html?id=71636> | ||
| 1379 | on perl versions 5.14 and below (the underlying bug with perl weak references | ||
| 1380 | was fixed in perl 5.15.5). The larger and more complex the spreadsheet, the | ||
| 1381 | more likely to be affected, but the actual size at which it segfaults is | ||
| 1382 | platform dependent. On a 64-bit perl with 7.6gb memory, it was seen on | ||
| 1383 | spreadsheets about 300mb and above. You can work around this adding | ||
| 1384 | C<XML::Twig::_set_weakrefs(0)> to your code before parsing the spreadsheet, | ||
| 1385 | although this may have other consequences such as memory leaks. | ||
| 1386 | |||
| 1387 | Please report any bugs to GitHub Issues at | ||
| 1388 | L<https://github.com/davidsclarke/Excel-Template-XLSX/issues>. | ||
| 1389 | |||
| 1390 | =back | ||
| 1391 | |||
| 1392 | =head1 SUPPORT | ||
| 1393 | |||
| 1394 | You can find this documentation for this module with the perldoc command. | ||
| 1395 | |||
| 1396 | perldoc Excel::Template::XLSX | ||
| 1397 | |||
| 1398 | You can also look for information at: | ||
| 1399 | |||
| 1400 | =over 4 | ||
| 1401 | |||
| 1402 | =item * MetaCPAN | ||
| 1403 | |||
| 1404 | L<https://metacpan.org/release/Excel-Template-XLSX> | ||
| 1405 | |||
| 1406 | =item * RT: CPAN's request tracker | ||
| 1407 | |||
| 1408 | L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Excel-Template-XLSX> | ||
| 1409 | |||
| 1410 | =item * Github | ||
| 1411 | |||
| 1412 | L<https://github.com/davidsclarke/Excel-Template-XLSX> | ||
| 1413 | |||
| 1414 | =item * CPAN Ratings | ||
| 1415 | |||
| 1416 | L<http://cpanratings.perl.org/d/Excel-Template-XLSX> | ||
| 1417 | |||
| 1418 | =back | ||
| 1419 | |||
| 1420 | =head1 DEBUGGING TIPS | ||
| 1421 | |||
| 1422 | Using the Perl debugger gets complicated because of XML::Twig. The objects | ||
| 1423 | created by XML::Twig are HUGE. Also, stepping through the code often results | ||
| 1424 | in exceeding a stack depth of >100. The author found it helpful to take | ||
| 1425 | advantage of the simplify() method in XML::Twig when using the debugger 'x' | ||
| 1426 | command to examine variables. | ||
| 1427 | |||
| 1428 | x $node->simplify() | ||
| 1429 | |||
| 1430 | Also, it is helpful to use the 'c' command to jump over XML::Twig subroutine calls and callbacks. | ||
| 1431 | |||
| 1432 | =head1 BUGS | ||
| 1433 | |||
| 1434 | Please report any bugs or feature requests to the author. | ||
| 1435 | |||
| 1436 | =head1 TO DO | ||
| 1437 | |||
| 1438 | Worksheet Activation | ||
| 1439 | Table Formatting/Styles | ||
| 1440 | Calculation Mode | ||
| 1441 | |||
| 1442 | =head1 REPOSITORY | ||
| 1443 | |||
| 1444 | The Excel::Template::XLSX source code is hosted on github: | ||
| 1445 | L<http://github.com/davidsclarke/Excel-Template-xlsx>. | ||
| 1446 | |||
| 1447 | =head1 SEE ALSO | ||
| 1448 | |||
| 1449 | Excel::Writer::XLSX | ||
| 1450 | |||
| 1451 | This module does not provide much documentation on the capabilites of methods | ||
| 1452 | for creating Excel content. The documentation provided with EWX is excellent, | ||
| 1453 | and also has numerous examples included. | ||
| 1454 | |||
| 1455 | Spreadsheet::ParseXLSX | ||
| 1456 | |||
| 1457 | Although this module does not use Spreadsheet::ParseXLSX, the parsing and | ||
| 1458 | comments regarding issues involved with parsing spreadsheets came from this module. | ||
| 1459 | |||
| 1460 | XML::Twig and Archive::Zip | ||
| 1461 | |||
| 1462 | Excel .xlsx files are zippped .xml files. These two modules are used to | ||
| 1463 | unzip the .xlsx file, extract the members, and parse the relative portions | ||
| 1464 | of the .xml files inside. | ||
| 1465 | |||
| 1466 | =head1 ACKNOWLEDGEMENTS | ||
| 1467 | |||
| 1468 | This module leverages the methods in L<Excel::Writer::XLSX|https://metacpan.org/release/Excel-Writer-XLSX>, maintained by L<John McNamara|https://metacpan.org/author/JMCNAMARA> | ||
| 1469 | to recreate the template. | ||
| 1470 | |||
| 1471 | The parser was developed using L<Spreadsheet::ParseXLSX|https://metacpan.org/release/Spreadsheet-ParseXLSX> as a starting point, maintained by L<Jesse Luehrs|https://metacpan.org/author/DOY>. | ||
| 1472 | This parser calls methods in EWX directly when a token is resolved rather than building | ||
| 1473 | up an object representing the parsed content. | ||
| 1474 | |||
| 1475 | =head1 LICENSE AND COPYRIGHT | ||
| 1476 | |||
| 1477 | Either the Perl Artistic Licence L<http://dev.perl.org/licenses/artistic.html> | ||
| 1478 | or the GPL L<http://www.opensource.org/licenses/gpl-license.php>. | ||
| 1479 | |||
| 1480 | AUTHOR | ||
| 1481 | |||
| 1482 | David Clarke dclarke@cpan.org | ||
| 1483 | |||
| 1484 | =cut | ||
| 1485 | |||
| 1486 | } | ||
| 1487 | |||