/usr/share/perl5/Excel/Writer/XLSX/Workbook.pm is in libexcel-writer-xlsx-perl 0.76-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 | package Excel::Writer::XLSX::Workbook;
###############################################################################
#
# Workbook - A class for writing Excel Workbooks.
#
#
# Used in conjunction with Excel::Writer::XLSX
#
# Copyright 2000-2013, John McNamara, jmcnamara@cpan.org
#
# Documentation after __END__
#
# perltidy with the following options: -mbl=2 -pt=0 -nola
use 5.008002;
use strict;
use warnings;
use Carp;
use IO::File;
use File::Find;
use File::Temp qw(tempfile);
use File::Basename 'fileparse';
use Archive::Zip;
use Excel::Writer::XLSX::Worksheet;
use Excel::Writer::XLSX::Chartsheet;
use Excel::Writer::XLSX::Format;
use Excel::Writer::XLSX::Shape;
use Excel::Writer::XLSX::Chart;
use Excel::Writer::XLSX::Package::Packager;
use Excel::Writer::XLSX::Package::XMLwriter;
use Excel::Writer::XLSX::Utility qw(xl_cell_to_rowcol xl_rowcol_to_cell);
our @ISA = qw(Excel::Writer::XLSX::Package::XMLwriter);
our $VERSION = '0.76';
###############################################################################
#
# Public and private API methods.
#
###############################################################################
###############################################################################
#
# new()
#
# Constructor.
#
sub new {
my $class = shift;
my $self = Excel::Writer::XLSX::Package::XMLwriter->new();
$self->{_filename} = $_[0] || '';
$self->{_tempdir} = undef;
$self->{_1904} = 0;
$self->{_activesheet} = 0;
$self->{_firstsheet} = 0;
$self->{_selected} = 0;
$self->{_fileclosed} = 0;
$self->{_filehandle} = undef;
$self->{_internal_fh} = 0;
$self->{_sheet_name} = 'Sheet';
$self->{_chart_name} = 'Chart';
$self->{_sheetname_count} = 0;
$self->{_chartname_count} = 0;
$self->{_worksheets} = [];
$self->{_charts} = [];
$self->{_drawings} = [];
$self->{_sheetnames} = [];
$self->{_formats} = [];
$self->{_xf_formats} = [];
$self->{_xf_format_indices} = {};
$self->{_dxf_formats} = [];
$self->{_dxf_format_indices} = {};
$self->{_palette} = [];
$self->{_font_count} = 0;
$self->{_num_format_count} = 0;
$self->{_defined_names} = [];
$self->{_named_ranges} = [];
$self->{_custom_colors} = [];
$self->{_doc_properties} = {};
$self->{_localtime} = [ localtime() ];
$self->{_num_vml_files} = 0;
$self->{_num_comment_files} = 0;
$self->{_optimization} = 0;
$self->{_x_window} = 240;
$self->{_y_window} = 15;
$self->{_window_width} = 16095;
$self->{_window_height} = 9660;
$self->{_tab_ratio} = 500;
# Structures for the shared strings data.
$self->{_str_total} = 0;
$self->{_str_unique} = 0;
$self->{_str_table} = {};
$self->{_str_array} = [];
bless $self, $class;
# Add the default cell format.
$self->add_format( xf_index => 0 );
# Check for a filename unless it is an existing filehandle
if ( not ref $self->{_filename} and $self->{_filename} eq '' ) {
carp 'Filename required by Excel::Writer::XLSX->new()';
return undef;
}
# If filename is a reference we assume that it is a valid filehandle.
if ( ref $self->{_filename} ) {
$self->{_filehandle} = $self->{_filename};
$self->{_internal_fh} = 0;
}
elsif ( $self->{_filename} eq '-' ) {
# Support special filename/filehandle '-' for backward compatibility.
binmode STDOUT;
$self->{_filehandle} = \*STDOUT;
$self->{_internal_fh} = 0;
}
else {
my $fh = IO::File->new( $self->{_filename}, 'w' );
return undef unless defined $fh;
$self->{_filehandle} = $fh;
$self->{_internal_fh} = 1;
}
# Set colour palette.
$self->set_color_palette();
return $self;
}
###############################################################################
#
# _assemble_xml_file()
#
# Assemble and write the XML file.
#
sub _assemble_xml_file {
my $self = shift;
# Prepare format object for passing to Style.pm.
$self->_prepare_format_properties();
$self->xml_declaration;
# Write the root workbook element.
$self->_write_workbook();
# Write the XLSX file version.
$self->_write_file_version();
# Write the workbook properties.
$self->_write_workbook_pr();
# Write the workbook view properties.
$self->_write_book_views();
# Write the worksheet names and ids.
$self->_write_sheets();
# Write the workbook defined names.
$self->_write_defined_names();
# Write the workbook calculation properties.
$self->_write_calc_pr();
# Write the workbook extension storage.
#$self->_write_ext_lst();
# Close the workbook tag.
$self->xml_end_tag( 'workbook' );
# Close the XML writer filehandle.
$self->xml_get_fh()->close();
}
###############################################################################
#
# close()
#
# Calls finalization methods.
#
sub close {
my $self = shift;
# In case close() is called twice, by user and by DESTROY.
return if $self->{_fileclosed};
# Test filehandle in case new() failed and the user didn't check.
return undef if !defined $self->{_filehandle};
$self->{_fileclosed} = 1;
$self->_store_workbook();
# Return the file close value.
if ( $self->{_internal_fh} ) {
return $self->{_filehandle}->close();
}
else {
# Return true and let users deal with their own filehandles.
return 1;
}
}
###############################################################################
#
# DESTROY()
#
# Close the workbook if it hasn't already been explicitly closed.
#
sub DESTROY {
my $self = shift;
local ( $@, $!, $^E, $? );
$self->close() if not $self->{_fileclosed};
}
###############################################################################
#
# sheets(slice,...)
#
# An accessor for the _worksheets[] array
#
# Returns: an optionally sliced list of the worksheet objects in a workbook.
#
sub sheets {
my $self = shift;
if ( @_ ) {
# Return a slice of the array
return @{ $self->{_worksheets} }[@_];
}
else {
# Return the entire list
return @{ $self->{_worksheets} };
}
}
###############################################################################
#
# worksheets()
#
# An accessor for the _worksheets[] array.
# This method is now deprecated. Use the sheets() method instead.
#
# Returns: an array reference
#
sub worksheets {
my $self = shift;
return $self->{_worksheets};
}
###############################################################################
#
# add_worksheet($name)
#
# Add a new worksheet to the Excel workbook.
#
# Returns: reference to a worksheet object
#
sub add_worksheet {
my $self = shift;
my $index = @{ $self->{_worksheets} };
my $name = $self->_check_sheetname( $_[0] );
my $fh = undef;
# Porters take note, the following scheme of passing references to Workbook
# data (in the \$self->{_foo} cases) instead of a reference to the Workbook
# itself is a workaround to avoid circular references between Workbook and
# Worksheet objects. Feel free to implement this in any way the suits your
# language.
#
my @init_data = (
$fh,
$name,
$index,
\$self->{_activesheet},
\$self->{_firstsheet},
\$self->{_str_total},
\$self->{_str_unique},
\$self->{_str_table},
$self->{_1904},
$self->{_palette},
$self->{_optimization},
$self->{_tempdir},
);
my $worksheet = Excel::Writer::XLSX::Worksheet->new( @init_data );
$self->{_worksheets}->[$index] = $worksheet;
$self->{_sheetnames}->[$index] = $name;
return $worksheet;
}
###############################################################################
#
# add_chart( %args )
#
# Create a chart for embedding or as as new sheet.
#
sub add_chart {
my $self = shift;
my %arg = @_;
my $name = '';
my $index = @{ $self->{_worksheets} };
my $fh = undef;
# Type must be specified so we can create the required chart instance.
my $type = $arg{type};
if ( !defined $type ) {
croak "Must define chart type in add_chart()";
}
# Ensure that the chart defaults to non embedded.
my $embedded = $arg{embedded} || 0;
# Check the worksheet name for non-embedded charts.
if ( !$embedded ) {
$name = $self->_check_sheetname( $arg{name}, 1 );
}
my @init_data = (
$fh,
$name,
$index,
\$self->{_activesheet},
\$self->{_firstsheet},
\$self->{_str_total},
\$self->{_str_unique},
\$self->{_str_table},
$self->{_1904},
$self->{_palette},
$self->{_optimization},
);
my $chart = Excel::Writer::XLSX::Chart->factory( $type, $arg{subtype} );
# If the chart isn't embedded let the workbook control it.
if ( !$embedded ) {
my $drawing = Excel::Writer::XLSX::Drawing->new();
my $chartsheet = Excel::Writer::XLSX::Chartsheet->new( @init_data );
$chart->{_palette} = $self->{_palette};
$chartsheet->{_chart} = $chart;
$chartsheet->{_drawing} = $drawing;
$self->{_worksheets}->[$index] = $chartsheet;
$self->{_sheetnames}->[$index] = $name;
push @{ $self->{_charts} }, $chart;
return $chartsheet;
}
else {
# Set the embedded chart name if present.
$chart->{_chart_name} = $arg{name} if $arg{name};
# Set index to 0 so that the activate() and set_first_sheet() methods
# point back to the first worksheet if used for embedded charts.
$chart->{_index} = 0;
$chart->{_palette} = $self->{_palette};
$chart->_set_embedded_config_data();
push @{ $self->{_charts} }, $chart;
return $chart;
}
}
###############################################################################
#
# _check_sheetname( $name )
#
# Check for valid worksheet names. We check the length, if it contains any
# invalid characters and if the name is unique in the workbook.
#
sub _check_sheetname {
my $self = shift;
my $name = shift || "";
my $chart = shift || 0;
my $invalid_char = qr([\[\]:*?/\\]);
# Increment the Sheet/Chart number used for default sheet names below.
if ( $chart ) {
$self->{_chartname_count}++;
}
else {
$self->{_sheetname_count}++;
}
# Supply default Sheet/Chart name if none has been defined.
if ( $name eq "" ) {
if ( $chart ) {
$name = $self->{_chart_name} . $self->{_chartname_count};
}
else {
$name = $self->{_sheet_name} . $self->{_sheetname_count};
}
}
# Check that sheet name is <= 31. Excel limit.
croak "Sheetname $name must be <= 31 chars" if length $name > 31;
# Check that sheetname doesn't contain any invalid characters
if ( $name =~ $invalid_char ) {
croak 'Invalid character []:*?/\\ in worksheet name: ' . $name;
}
# Check that the worksheet name doesn't already exist since this is a fatal
# error in Excel 97. The check must also exclude case insensitive matches.
foreach my $worksheet ( @{ $self->{_worksheets} } ) {
my $name_a = $name;
my $name_b = $worksheet->{_name};
if ( lc( $name_a ) eq lc( $name_b ) ) {
croak "Worksheet name '$name', with case ignored, is already used.";
}
}
return $name;
}
###############################################################################
#
# add_format(%properties)
#
# Add a new format to the Excel workbook.
#
sub add_format {
my $self = shift;
my @init_data =
( \$self->{_xf_format_indices}, \$self->{_dxf_format_indices}, @_ );
my $format = Excel::Writer::XLSX::Format->new( @init_data );
push @{ $self->{_formats} }, $format; # Store format reference
return $format;
}
###############################################################################
#
# add_shape(%properties)
#
# Add a new shape to the Excel workbook.
#
sub add_shape {
my $self = shift;
my $fh = undef;
my $shape = Excel::Writer::XLSX::Shape->new( $fh, @_ );
$shape->{_palette} = $self->{_palette};
push @{ $self->{_shapes} }, $shape; # Store shape reference.
return $shape;
}
###############################################################################
#
# set_1904()
#
# Set the date system: 0 = 1900 (the default), 1 = 1904
#
sub set_1904 {
my $self = shift;
if ( defined( $_[0] ) ) {
$self->{_1904} = $_[0];
}
else {
$self->{_1904} = 1;
}
}
###############################################################################
#
# get_1904()
#
# Return the date system: 0 = 1900, 1 = 1904
#
sub get_1904 {
my $self = shift;
return $self->{_1904};
}
###############################################################################
#
# set_custom_color()
#
# Change the RGB components of the elements in the colour palette.
#
sub set_custom_color {
my $self = shift;
# Match a HTML #xxyyzz style parameter
if ( defined $_[1] and $_[1] =~ /^#(\w\w)(\w\w)(\w\w)/ ) {
@_ = ( $_[0], hex $1, hex $2, hex $3 );
}
my $index = $_[0] || 0;
my $red = $_[1] || 0;
my $green = $_[2] || 0;
my $blue = $_[3] || 0;
my $aref = $self->{_palette};
# Check that the colour index is the right range
if ( $index < 8 or $index > 64 ) {
carp "Color index $index outside range: 8 <= index <= 64";
return 0;
}
# Check that the colour components are in the right range
if ( ( $red < 0 or $red > 255 )
|| ( $green < 0 or $green > 255 )
|| ( $blue < 0 or $blue > 255 ) )
{
carp "Color component outside range: 0 <= color <= 255";
return 0;
}
$index -= 8; # Adjust colour index (wingless dragonfly)
# Set the RGB value.
my @rgb = ( $red, $green, $blue );
$aref->[$index] = [@rgb];
# Store the custom colors for the style.xml file.
push @{ $self->{_custom_colors} }, sprintf "FF%02X%02X%02X", @rgb;
return $index + 8;
}
###############################################################################
#
# set_color_palette()
#
# Sets the colour palette to the Excel defaults.
#
sub set_color_palette {
my $self = shift;
$self->{_palette} = [
[ 0x00, 0x00, 0x00, 0x00 ], # 8
[ 0xff, 0xff, 0xff, 0x00 ], # 9
[ 0xff, 0x00, 0x00, 0x00 ], # 10
[ 0x00, 0xff, 0x00, 0x00 ], # 11
[ 0x00, 0x00, 0xff, 0x00 ], # 12
[ 0xff, 0xff, 0x00, 0x00 ], # 13
[ 0xff, 0x00, 0xff, 0x00 ], # 14
[ 0x00, 0xff, 0xff, 0x00 ], # 15
[ 0x80, 0x00, 0x00, 0x00 ], # 16
[ 0x00, 0x80, 0x00, 0x00 ], # 17
[ 0x00, 0x00, 0x80, 0x00 ], # 18
[ 0x80, 0x80, 0x00, 0x00 ], # 19
[ 0x80, 0x00, 0x80, 0x00 ], # 20
[ 0x00, 0x80, 0x80, 0x00 ], # 21
[ 0xc0, 0xc0, 0xc0, 0x00 ], # 22
[ 0x80, 0x80, 0x80, 0x00 ], # 23
[ 0x99, 0x99, 0xff, 0x00 ], # 24
[ 0x99, 0x33, 0x66, 0x00 ], # 25
[ 0xff, 0xff, 0xcc, 0x00 ], # 26
[ 0xcc, 0xff, 0xff, 0x00 ], # 27
[ 0x66, 0x00, 0x66, 0x00 ], # 28
[ 0xff, 0x80, 0x80, 0x00 ], # 29
[ 0x00, 0x66, 0xcc, 0x00 ], # 30
[ 0xcc, 0xcc, 0xff, 0x00 ], # 31
[ 0x00, 0x00, 0x80, 0x00 ], # 32
[ 0xff, 0x00, 0xff, 0x00 ], # 33
[ 0xff, 0xff, 0x00, 0x00 ], # 34
[ 0x00, 0xff, 0xff, 0x00 ], # 35
[ 0x80, 0x00, 0x80, 0x00 ], # 36
[ 0x80, 0x00, 0x00, 0x00 ], # 37
[ 0x00, 0x80, 0x80, 0x00 ], # 38
[ 0x00, 0x00, 0xff, 0x00 ], # 39
[ 0x00, 0xcc, 0xff, 0x00 ], # 40
[ 0xcc, 0xff, 0xff, 0x00 ], # 41
[ 0xcc, 0xff, 0xcc, 0x00 ], # 42
[ 0xff, 0xff, 0x99, 0x00 ], # 43
[ 0x99, 0xcc, 0xff, 0x00 ], # 44
[ 0xff, 0x99, 0xcc, 0x00 ], # 45
[ 0xcc, 0x99, 0xff, 0x00 ], # 46
[ 0xff, 0xcc, 0x99, 0x00 ], # 47
[ 0x33, 0x66, 0xff, 0x00 ], # 48
[ 0x33, 0xcc, 0xcc, 0x00 ], # 49
[ 0x99, 0xcc, 0x00, 0x00 ], # 50
[ 0xff, 0xcc, 0x00, 0x00 ], # 51
[ 0xff, 0x99, 0x00, 0x00 ], # 52
[ 0xff, 0x66, 0x00, 0x00 ], # 53
[ 0x66, 0x66, 0x99, 0x00 ], # 54
[ 0x96, 0x96, 0x96, 0x00 ], # 55
[ 0x00, 0x33, 0x66, 0x00 ], # 56
[ 0x33, 0x99, 0x66, 0x00 ], # 57
[ 0x00, 0x33, 0x00, 0x00 ], # 58
[ 0x33, 0x33, 0x00, 0x00 ], # 59
[ 0x99, 0x33, 0x00, 0x00 ], # 60
[ 0x99, 0x33, 0x66, 0x00 ], # 61
[ 0x33, 0x33, 0x99, 0x00 ], # 62
[ 0x33, 0x33, 0x33, 0x00 ], # 63
];
return 0;
}
###############################################################################
#
# set_tempdir()
#
# Change the default temp directory.
#
sub set_tempdir {
my $self = shift;
my $dir = shift;
croak "$dir is not a valid directory" if defined $dir and not -d $dir;
$self->{_tempdir} = $dir;
}
###############################################################################
#
# define_name()
#
# Create a defined name in Excel. We handle global/workbook level names and
# local/worksheet names.
#
sub define_name {
my $self = shift;
my $name = shift;
my $formula = shift;
my $sheet_index = undef;
my $sheetname = '';
my $full_name = $name;
# Remove the = sign from the formula if it exists.
$formula =~ s/^=//;
# Local defined names are formatted like "Sheet1!name".
if ( $name =~ /^(.*)!(.*)$/ ) {
$sheetname = $1;
$name = $2;
$sheet_index = $self->_get_sheet_index( $sheetname );
}
else {
$sheet_index = -1; # Use -1 to indicate global names.
}
# Warn if the sheet index wasn't found.
if ( !defined $sheet_index ) {
carp "Unknown sheet name $sheetname in defined_name()\n";
return -1;
}
# Warn if the name contains invalid chars as defined by Excel help.
if ( $name !~ m/^[\w\\][\w.]*$/ || $name =~ m/^\d/ ) {
carp "Invalid characters in name '$name' used in defined_name()\n";
return -1;
}
# Warn if the name looks like a cell name.
if ( $name =~ m/^[a-zA-Z][a-zA-Z]?[a-dA-D]?[0-9]+$/ ) {
carp "Invalid name '$name' looks like a cell name in defined_name()\n";
return -1;
}
# Warn if the name looks like a R1C1.
if ( $name =~ m/^[rcRC]$/ || $name =~ m/^[rcRC]\d+[rcRC]\d+$/ ) {
carp "Invalid name '$name' like a RC cell ref in defined_name()\n";
return -1;
}
push @{ $self->{_defined_names} }, [ $name, $sheet_index, $formula ];
}
###############################################################################
#
# set_properties()
#
# Set the document properties such as Title, Author etc. These are written to
# property sets in the OLE container.
#
sub set_properties {
my $self = shift;
my %param = @_;
# Ignore if no args were passed.
return -1 unless @_;
# List of valid input parameters.
my %valid = (
title => 1,
subject => 1,
author => 1,
keywords => 1,
comments => 1,
last_author => 1,
created => 1,
category => 1,
manager => 1,
company => 1,
status => 1,
);
# Check for valid input parameters.
for my $parameter ( keys %param ) {
if ( not exists $valid{$parameter} ) {
carp "Unknown parameter '$parameter' in set_properties()";
return -1;
}
}
# Set the creation time unless specified by the user.
if ( !exists $param{created} ) {
$param{created} = $self->{_localtime};
}
$self->{_doc_properties} = \%param;
}
###############################################################################
#
# add_vba_project()
#
# Add a vbaProject binary to the XLSX file.
#
sub add_vba_project {
my $self = shift;
my $vba_project = shift;
croak "No vbaProject.bin specified in add_vba_project()"
if not $vba_project;
croak "Couldn't locate $vba_project in add_vba_project(): $!"
unless -e $vba_project;
$self->{_vba_project} = $vba_project;
}
###############################################################################
#
# _store_workbook()
#
# Assemble worksheets into a workbook.
#
sub _store_workbook {
my $self = shift;
my $tempdir = File::Temp->newdir( DIR => $self->{_tempdir} );
my $packager = Excel::Writer::XLSX::Package::Packager->new();
my $zip = Archive::Zip->new();
# Add a default worksheet if non have been added.
$self->add_worksheet() if not @{ $self->{_worksheets} };
# Ensure that at least one worksheet has been selected.
if ( $self->{_activesheet} == 0 ) {
$self->{_worksheets}->[0]->{_selected} = 1;
$self->{_worksheets}->[0]->{_hidden} = 0;
}
# Set the active sheet.
for my $sheet ( @{ $self->{_worksheets} } ) {
$sheet->{_active} = 1 if $sheet->{_index} == $self->{_activesheet};
}
# Convert the SST strings data structure.
$self->_prepare_sst_string_data();
# Prepare the worksheet VML elements such as comments and buttons.
$self->_prepare_vml_objects();
# Set the defined names for the worksheets such as Print Titles.
$self->_prepare_defined_names();
# Prepare the drawings, charts and images.
$self->_prepare_drawings();
# Add cached data to charts.
$self->_add_chart_data();
# Prepare the worksheet tables.
$self->_prepare_tables();
# Package the workbook.
$packager->_add_workbook( $self );
$packager->_set_package_dir( $tempdir );
$packager->_create_package();
# Free up the Packager object.
$packager = undef;
# Add the files to the zip archive. Due to issues with Archive::Zip in
# taint mode we can't use addTree() so we have to build the file list
# with File::Find and pass each one to addFile().
my @xlsx_files;
my $wanted = sub { push @xlsx_files, $File::Find::name if -f };
File::Find::find(
{
wanted => $wanted,
untaint => 1,
untaint_pattern => qr|^(.+)$|
},
$tempdir
);
# Store the xlsx component files with the temp dir name removed.
for my $filename ( @xlsx_files ) {
my $short_name = $filename;
$short_name =~ s{^\Q$tempdir\E/?}{};
$zip->addFile( $filename, $short_name );
}
if ( $self->{_internal_fh} ) {
if ( $zip->writeToFileHandle( $self->{_filehandle} ) != 0 ) {
carp 'Error writing zip container for xlsx file.';
}
}
else {
# Archive::Zip needs to rewind a filehandle to write the zip headers.
# This won't work for arbitrary user defined filehandles so we use
# a temp file based filehandle to create the zip archive and then
# stream that to the filehandle.
my $tmp_fh = tempfile( DIR => $self->{_tempdir} );
my $is_seekable = 1;
if ( $zip->writeToFileHandle( $tmp_fh, $is_seekable ) != 0 ) {
carp 'Error writing zip container for xlsx file.';
}
my $buffer;
seek $tmp_fh, 0, 0;
while ( read( $tmp_fh, $buffer, 4_096 ) ) {
local $\ = undef; # Protect print from -l on commandline.
print { $self->{_filehandle} } $buffer;
}
}
}
###############################################################################
#
# _prepare_sst_string_data()
#
# Convert the SST string data from a hash to an array.
#
sub _prepare_sst_string_data {
my $self = shift;
my @strings;
$#strings = $self->{_str_unique} - 1; # Pre-extend array
while ( my $key = each %{ $self->{_str_table} } ) {
$strings[ $self->{_str_table}->{$key} ] = $key;
}
# The SST data could be very large, free some memory (maybe).
$self->{_str_table} = undef;
$self->{_str_array} = \@strings;
}
###############################################################################
#
# _prepare_format_properties()
#
# Prepare all of the format properties prior to passing them to Styles.pm.
#
sub _prepare_format_properties {
my $self = shift;
# Separate format objects into XF and DXF formats.
$self->_prepare_formats();
# Set the font index for the format objects.
$self->_prepare_fonts();
# Set the number format index for the format objects.
$self->_prepare_num_formats();
# Set the border index for the format objects.
$self->_prepare_borders();
# Set the fill index for the format objects.
$self->_prepare_fills();
}
###############################################################################
#
# _prepare_formats()
#
# Iterate through the XF Format objects and separate them into XF and DXF
# formats.
#
sub _prepare_formats {
my $self = shift;
for my $format ( @{ $self->{_formats} } ) {
my $xf_index = $format->{_xf_index};
my $dxf_index = $format->{_dxf_index};
if ( defined $xf_index ) {
$self->{_xf_formats}->[$xf_index] = $format;
}
if ( defined $dxf_index ) {
$self->{_dxf_formats}->[$dxf_index] = $format;
}
}
}
###############################################################################
#
# _set_default_xf_indices()
#
# Set the default index for each format. This is mainly used for testing.
#
sub _set_default_xf_indices {
my $self = shift;
for my $format ( @{ $self->{_formats} } ) {
$format->get_xf_index();
}
}
###############################################################################
#
# _prepare_fonts()
#
# Iterate through the XF Format objects and give them an index to non-default
# font elements.
#
sub _prepare_fonts {
my $self = shift;
my %fonts;
my $index = 0;
for my $format ( @{ $self->{_xf_formats} } ) {
my $key = $format->get_font_key();
if ( exists $fonts{$key} ) {
# Font has already been used.
$format->{_font_index} = $fonts{$key};
$format->{_has_font} = 0;
}
else {
# This is a new font.
$fonts{$key} = $index;
$format->{_font_index} = $index;
$format->{_has_font} = 1;
$index++;
}
}
$self->{_font_count} = $index;
# For the DXF formats we only need to check if the properties have changed.
for my $format ( @{ $self->{_dxf_formats} } ) {
# The only font properties that can change for a DXF format are: color,
# bold, italic, underline and strikethrough.
if ( $format->{_color}
|| $format->{_bold}
|| $format->{_italic}
|| $format->{_underline}
|| $format->{_font_strikeout} )
{
$format->{_has_dxf_font} = 1;
}
}
}
###############################################################################
#
# _prepare_num_formats()
#
# Iterate through the XF Format objects and give them an index to non-default
# number format elements.
#
# User defined records start from index 0xA4.
#
sub _prepare_num_formats {
my $self = shift;
my %num_formats;
my $index = 164;
my $num_format_count = 0;
for my $format ( @{ $self->{_xf_formats} }, @{ $self->{_dxf_formats} } ) {
my $num_format = $format->{_num_format};
# Check if $num_format is an index to a built-in number format.
# Also check for a string of zeros, which is a valid number format
# string but would evaluate to zero.
#
if ( $num_format =~ m/^\d+$/ && $num_format !~ m/^0+\d/ ) {
# Index to a built-in number format.
$format->{_num_format_index} = $num_format;
next;
}
if ( exists( $num_formats{$num_format} ) ) {
# Number format has already been used.
$format->{_num_format_index} = $num_formats{$num_format};
}
else {
# Add a new number format.
$num_formats{$num_format} = $index;
$format->{_num_format_index} = $index;
$index++;
# Only increase font count for XF formats (not for DXF formats).
if ( $format->{_xf_index} ) {
$num_format_count++;
}
}
}
$self->{_num_format_count} = $num_format_count;
}
###############################################################################
#
# _prepare_borders()
#
# Iterate through the XF Format objects and give them an index to non-default
# border elements.
#
sub _prepare_borders {
my $self = shift;
my %borders;
my $index = 0;
for my $format ( @{ $self->{_xf_formats} } ) {
my $key = $format->get_border_key();
if ( exists $borders{$key} ) {
# Border has already been used.
$format->{_border_index} = $borders{$key};
$format->{_has_border} = 0;
}
else {
# This is a new border.
$borders{$key} = $index;
$format->{_border_index} = $index;
$format->{_has_border} = 1;
$index++;
}
}
$self->{_border_count} = $index;
# For the DXF formats we only need to check if the properties have changed.
for my $format ( @{ $self->{_dxf_formats} } ) {
my $key = $format->get_border_key();
if ( $key =~ m/[^0:]/ ) {
$format->{_has_dxf_border} = 1;
}
}
}
###############################################################################
#
# _prepare_fills()
#
# Iterate through the XF Format objects and give them an index to non-default
# fill elements.
#
# The user defined fill properties start from 2 since there are 2 default
# fills: patternType="none" and patternType="gray125".
#
sub _prepare_fills {
my $self = shift;
my %fills;
my $index = 2; # Start from 2. See above.
# Add the default fills.
$fills{'0:0:0'} = 0;
$fills{'17:0:0'} = 1;
# Store the DXF colours separately since them may be reversed below.
for my $format ( @{ $self->{_dxf_formats} } ) {
if ( $format->{_pattern}
|| $format->{_bg_color}
|| $format->{_fg_color} )
{
$format->{_has_dxf_fill} = 1;
$format->{_dxf_bg_color} = $format->{_bg_color};
$format->{_dxf_fg_color} = $format->{_fg_color};
}
}
for my $format ( @{ $self->{_xf_formats} } ) {
# The following logical statements jointly take care of special cases
# in relation to cell colours and patterns:
# 1. For a solid fill (_pattern == 1) Excel reverses the role of
# foreground and background colours, and
# 2. If the user specifies a foreground or background colour without
# a pattern they probably wanted a solid fill, so we fill in the
# defaults.
#
if ( $format->{_pattern} == 1
&& $format->{_bg_color} ne '0'
&& $format->{_fg_color} ne '0' )
{
my $tmp = $format->{_fg_color};
$format->{_fg_color} = $format->{_bg_color};
$format->{_bg_color} = $tmp;
}
if ( $format->{_pattern} <= 1
&& $format->{_bg_color} ne '0'
&& $format->{_fg_color} eq '0' )
{
$format->{_fg_color} = $format->{_bg_color};
$format->{_bg_color} = 0;
$format->{_pattern} = 1;
}
if ( $format->{_pattern} <= 1
&& $format->{_bg_color} eq '0'
&& $format->{_fg_color} ne '0' )
{
$format->{_bg_color} = 0;
$format->{_pattern} = 1;
}
my $key = $format->get_fill_key();
if ( exists $fills{$key} ) {
# Fill has already been used.
$format->{_fill_index} = $fills{$key};
$format->{_has_fill} = 0;
}
else {
# This is a new fill.
$fills{$key} = $index;
$format->{_fill_index} = $index;
$format->{_has_fill} = 1;
$index++;
}
}
$self->{_fill_count} = $index;
}
###############################################################################
#
# _prepare_defined_names()
#
# Iterate through the worksheets and store any defined names in addition to
# any user defined names. Stores the defined names for the Workbook.xml and
# the named ranges for App.xml.
#
sub _prepare_defined_names {
my $self = shift;
my @defined_names = @{ $self->{_defined_names} };
for my $sheet ( @{ $self->{_worksheets} } ) {
# Check for Print Area settings.
if ( $sheet->{_autofilter} ) {
my $range = $sheet->{_autofilter};
my $hidden = 1;
# Store the defined names.
push @defined_names,
[ '_xlnm._FilterDatabase', $sheet->{_index}, $range, $hidden ];
}
# Check for Print Area settings.
if ( $sheet->{_print_area} ) {
my $range = $sheet->{_print_area};
# Store the defined names.
push @defined_names,
[ '_xlnm.Print_Area', $sheet->{_index}, $range ];
}
# Check for repeat rows/cols. aka, Print Titles.
if ( $sheet->{_repeat_cols} || $sheet->{_repeat_rows} ) {
my $range = '';
if ( $sheet->{_repeat_cols} && $sheet->{_repeat_rows} ) {
$range = $sheet->{_repeat_cols} . ',' . $sheet->{_repeat_rows};
}
else {
$range = $sheet->{_repeat_cols} . $sheet->{_repeat_rows};
}
# Store the defined names.
push @defined_names,
[ '_xlnm.Print_Titles', $sheet->{_index}, $range ];
}
}
@defined_names = _sort_defined_names( @defined_names );
$self->{_defined_names} = \@defined_names;
$self->{_named_ranges} = _extract_named_ranges( @defined_names );
}
###############################################################################
#
# _sort_defined_names()
#
# Sort internal and user defined names in the same order as used by Excel.
# This may not be strictly necessary but unsorted elements caused a lot of
# issues in the the Spreadsheet::WriteExcel binary version. Also makes
# comparison testing easier.
#
sub _sort_defined_names {
my @names = @_;
#<<< Perltidy ignore this.
@names = sort {
# Primary sort based on the defined name.
_normalise_defined_name( $a->[0] )
cmp
_normalise_defined_name( $b->[0] )
||
# Secondary sort based on the sheet name.
_normalise_sheet_name( $a->[2] )
cmp
_normalise_sheet_name( $b->[2] )
} @names;
#>>>
return @names;
}
# Used in the above sort routine to normalise the defined names. Removes any
# leading '_xmln.' from internal names and lowercases the strings.
sub _normalise_defined_name {
my $name = shift;
$name =~ s/^_xlnm.//;
$name = lc $name;
return $name;
}
# Used in the above sort routine to normalise the worksheet names for the
# secondary sort. Removes leading quote and lowercases the strings.
sub _normalise_sheet_name {
my $name = shift;
$name =~ s/^'//;
$name = lc $name;
return $name;
}
###############################################################################
#
# _extract_named_ranges()
#
# Extract the named ranges from the sorted list of defined names. These are
# used in the App.xml file.
#
sub _extract_named_ranges {
my @defined_names = @_;
my @named_ranges;
NAME:
for my $defined_name ( @defined_names ) {
my $name = $defined_name->[0];
my $index = $defined_name->[1];
my $range = $defined_name->[2];
# Skip autoFilter ranges.
next NAME if $name eq '_xlnm._FilterDatabase';
# We are only interested in defined names with ranges.
if ( $range =~ /^([^!]+)!/ ) {
my $sheet_name = $1;
# Match Print_Area and Print_Titles xlnm types.
if ( $name =~ /^_xlnm\.(.*)$/ ) {
my $xlnm_type = $1;
$name = $sheet_name . '!' . $xlnm_type;
}
elsif ( $index != -1 ) {
$name = $sheet_name . '!' . $name;
}
push @named_ranges, $name;
}
}
return \@named_ranges;
}
###############################################################################
#
# _prepare_drawings()
#
# Iterate through the worksheets and set up any chart or image drawings.
#
sub _prepare_drawings {
my $self = shift;
my $chart_ref_id = 0;
my $image_ref_id = 0;
my $drawing_id = 0;
for my $sheet ( @{ $self->{_worksheets} } ) {
my $chart_count = scalar @{ $sheet->{_charts} };
my $image_count = scalar @{ $sheet->{_images} };
my $shape_count = scalar @{ $sheet->{_shapes} };
next unless ( $chart_count + $image_count + $shape_count );
$drawing_id++;
for my $index ( 0 .. $chart_count - 1 ) {
$chart_ref_id++;
$sheet->_prepare_chart( $index, $chart_ref_id, $drawing_id );
}
for my $index ( 0 .. $image_count - 1 ) {
my $filename = $sheet->{_images}->[$index]->[2];
my ( $image_id, $type, $width, $height, $name ) =
$self->_get_image_properties( $filename );
$image_ref_id++;
$sheet->_prepare_image( $index, $image_ref_id, $drawing_id, $width,
$height, $name, $type );
}
for my $index ( 0 .. $shape_count - 1 ) {
$sheet->_prepare_shape( $index, $drawing_id );
}
my $drawing = $sheet->{_drawing};
push @{ $self->{_drawings} }, $drawing;
}
# Sort the workbook charts references into the order that the were
# written from the worksheets above.
my @chart_data = @{ $self->{_charts} };
@chart_data = sort { $a->{_id} <=> $b->{_id} } @chart_data;
$self->{_charts} = \@chart_data;
$self->{_drawing_count} = $drawing_id;
}
###############################################################################
#
# _prepare_vml_objects()
#
# Iterate through the worksheets and set up the VML objects.
#
sub _prepare_vml_objects {
my $self = shift;
my $comment_id = 0;
my $vml_drawing_id = 0;
my $vml_data_id = 1;
my $vml_shape_id = 1024;
my $vml_files = 0;
my $comment_files = 0;
for my $sheet ( @{ $self->{_worksheets} } ) {
next unless $sheet->{_has_vml};
$vml_files++;
$comment_files++ if $sheet->{_has_comments};
$comment_id++ if $sheet->{_has_comments};
$vml_drawing_id++;
my $count =
$sheet->_prepare_vml_objects( $vml_data_id, $vml_shape_id,
$vml_drawing_id, $comment_id );
# Each VML file should start with a shape id incremented by 1024.
$vml_data_id += 1 * int( ( 1024 + $count ) / 1024 );
$vml_shape_id += 1024 * int( ( 1024 + $count ) / 1024 );
}
$self->{_num_vml_files} = $vml_files;
$self->{_num_comment_files} = $comment_files;
# Add a font format for cell comments.
if ( $comment_files > 0 ) {
my $format = Excel::Writer::XLSX::Format->new(
\$self->{_xf_format_indices},
\$self->{_dxf_format_indices},
font => 'Tahoma',
size => 8,
color_indexed => 81,
font_only => 1,
);
$format->get_xf_index();
push @{ $self->{_formats} }, $format;
}
}
###############################################################################
#
# _prepare_tables()
#
# Set the table ids for the worksheet tables.
#
sub _prepare_tables {
my $self = shift;
my $table_id = 0;
for my $sheet ( @{ $self->{_worksheets} } ) {
my $table_count = scalar @{ $sheet->{_tables} };
next unless $table_count;
$sheet->_prepare_tables( $table_id + 1 );
$table_id += $table_count;
}
}
###############################################################################
#
# _add_chart_data()
#
# Add "cached" data to charts to provide the numCache and strCache data for
# series and title/axis ranges.
#
sub _add_chart_data {
my $self = shift;
my %worksheets;
my %seen_ranges;
# Map worksheet names to worksheet objects.
for my $worksheet ( @{ $self->{_worksheets} } ) {
$worksheets{ $worksheet->{_name} } = $worksheet;
}
CHART:
for my $chart ( @{ $self->{_charts} } ) {
RANGE:
while ( my ( $range, $id ) = each %{ $chart->{_formula_ids} } ) {
# Skip if the series has user defined data.
if ( defined $chart->{_formula_data}->[$id] ) {
if ( !exists $seen_ranges{$range}
|| !defined $seen_ranges{$range} )
{
my $data = $chart->{_formula_data}->[$id];
$seen_ranges{$range} = $data;
}
next RANGE;
}
# Check to see if the data is already cached locally.
if ( exists $seen_ranges{$range} ) {
$chart->{_formula_data}->[$id] = $seen_ranges{$range};
next RANGE;
}
# Convert the range formula to a sheet name and cell range.
my ( $sheetname, @cells ) = $self->_get_chart_range( $range );
# Skip if we couldn't parse the formula.
next RANGE if !defined $sheetname;
# Handle non-contiguous ranges: (Sheet1!$A$1:$A$2,Sheet1!$A$4:$A$5).
# We don't try to parse the ranges. We just return an empty list.
if ( $sheetname =~ m/^\([^,]+,/ ) {
$chart->{_formula_data}->[$id] = [];
$seen_ranges{$range} = [];
next RANGE;
}
# Die if the name is unknown since it indicates a user error in
# a chart series formula.
if ( !exists $worksheets{$sheetname} ) {
die "Unknown worksheet reference '$sheetname' in range "
. "'$range' passed to add_series().\n";
}
# Find the worksheet object based on the sheet name.
my $worksheet = $worksheets{$sheetname};
# Get the data from the worksheet table.
my @data = $worksheet->_get_range_data( @cells );
# Convert shared string indexes to strings.
for my $token ( @data ) {
if ( ref $token ) {
$token = $self->{_str_array}->[ $token->{sst_id} ];
# Ignore rich strings for now. Deparse later if necessary.
if ( $token =~ m{^<r>} && $token =~ m{</r>$} ) {
$token = '';
}
}
}
# Add the data to the chart.
$chart->{_formula_data}->[$id] = \@data;
# Store range data locally to avoid lookup if seen again.
$seen_ranges{$range} = \@data;
}
}
}
###############################################################################
#
# _get_chart_range()
#
# Convert a range formula such as Sheet1!$B$1:$B$5 into a sheet name and cell
# range such as ( 'Sheet1', 0, 1, 4, 1 ).
#
sub _get_chart_range {
my $self = shift;
my $range = shift;
my $cell_1;
my $cell_2;
my $sheetname;
my $cells;
# Split the range formula into sheetname and cells at the last '!'.
my $pos = rindex $range, '!';
if ( $pos > 0 ) {
$sheetname = substr $range, 0, $pos;
$cells = substr $range, $pos + 1;
}
else {
return undef;
}
# Split the cell range into 2 cells or else use single cell for both.
if ( $cells =~ ':' ) {
( $cell_1, $cell_2 ) = split /:/, $cells;
}
else {
( $cell_1, $cell_2 ) = ( $cells, $cells );
}
# Remove leading/trailing apostrophes and convert escaped quotes to single.
$sheetname =~ s/^'//g;
$sheetname =~ s/'$//g;
$sheetname =~ s/''/'/g;
my ( $row_start, $col_start ) = xl_cell_to_rowcol( $cell_1 );
my ( $row_end, $col_end ) = xl_cell_to_rowcol( $cell_2 );
# Check that we have a 1D range only.
if ( $row_start != $row_end && $col_start != $col_end ) {
return undef;
}
return ( $sheetname, $row_start, $col_start, $row_end, $col_end );
}
###############################################################################
#
# _store_externs()
#
# Write the EXTERNCOUNT and EXTERNSHEET records. These are used as indexes for
# the NAME records.
#
sub _store_externs {
my $self = shift;
}
###############################################################################
#
# _store_names()
#
# Write the NAME record to define the print area and the repeat rows and cols.
#
sub _store_names {
my $self = shift;
}
###############################################################################
#
# _quote_sheetname()
#
# Sheetnames used in references should be quoted if they contain any spaces,
# special characters or if the look like something that isn't a sheet name.
# TODO. We need to handle more special cases.
#
sub _quote_sheetname {
my $self = shift;
my $sheetname = $_[0];
if ( $sheetname =~ /^Sheet\d+$/ ) {
return $sheetname;
}
else {
return qq('$sheetname');
}
}
###############################################################################
#
# _get_image_properties()
#
# Extract information from the image file such as dimension, type, filename,
# and extension. Also keep track of previously seen images to optimise out
# any duplicates.
#
sub _get_image_properties {
my $self = shift;
my $filename = shift;
my %images_seen;
my @image_data;
my @previous_images;
my $image_id = 1;
my $type;
my $width;
my $height;
my $image_name;
if ( not exists $images_seen{$filename} ) {
( $image_name ) = fileparse( $filename );
# TODO should also match seen images based on checksum.
# Open the image file and import the data.
my $fh = FileHandle->new( $filename );
croak "Couldn't import $filename: $!" unless defined $fh;
binmode $fh;
# Slurp the file into a string and do some size calcs.
my $data = do { local $/; <$fh> };
my $size = length $data;
#my $checksum = TODO.
if ( unpack( 'x A3', $data ) eq 'PNG' ) {
# Test for PNGs.
( $type, $width, $height ) = $self->_process_png( $data );
$self->{_image_types}->{png} = 1;
}
elsif ( unpack( 'n', $data ) == 0xFFD8 ) {
# Test for JPEG files.
( $type, $width, $height ) =
$self->_process_jpg( $data, $filename );
$self->{_image_types}->{jpeg} = 1;
}
elsif ( unpack( 'A2', $data ) eq 'BM' ) {
# Test for BMPs.
( $type, $width, $height ) =
$self->_process_bmp( $data, $filename );
$self->{_image_types}->{bmp} = 1;
}
else {
# TODO. Add Image::Size to support other types.
croak "Unsupported image format for file: $filename\n";
}
push @{ $self->{_images} }, [ $filename, $type ];
# Also store new data for use in duplicate images.
push @previous_images, [ $image_id, $type, $width, $height ];
$images_seen{$filename} = $image_id++;
$fh->close;
}
else {
# We've processed this file already.
my $index = $images_seen{$filename} - 1;
# Increase image reference count.
$image_data[$index]->[0]++;
}
return ( $image_id, $type, $width, $height, $image_name );
}
###############################################################################
#
# _process_png()
#
# Extract width and height information from a PNG file.
#
sub _process_png {
my $self = shift;
my $type = 'png';
my $width = unpack "N", substr $_[0], 16, 4;
my $height = unpack "N", substr $_[0], 20, 4;
return ( $type, $width, $height );
}
###############################################################################
#
# _process_bmp()
#
# Extract width and height information from a BMP file.
#
# Most of the checks came from old Spredsheet::WriteExcel code.
#
sub _process_bmp {
my $self = shift;
my $data = $_[0];
my $filename = $_[1];
my $type = 'bmp';
# Check that the file is big enough to be a bitmap.
if ( length $data <= 0x36 ) {
croak "$filename doesn't contain enough data.";
}
# Read the bitmap width and height. Verify the sizes.
my ( $width, $height ) = unpack "x18 V2", $data;
if ( $width > 0xFFFF ) {
croak "$filename: largest image width $width supported is 65k.";
}
if ( $height > 0xFFFF ) {
croak "$filename: largest image height supported is 65k.";
}
# Read the bitmap planes and bpp data. Verify them.
my ( $planes, $bitcount ) = unpack "x26 v2", $data;
if ( $bitcount != 24 ) {
croak "$filename isn't a 24bit true color bitmap.";
}
if ( $planes != 1 ) {
croak "$filename: only 1 plane supported in bitmap image.";
}
# Read the bitmap compression. Verify compression.
my $compression = unpack "x30 V", $data;
if ( $compression != 0 ) {
croak "$filename: compression not supported in bitmap image.";
}
return ( $type, $width, $height );
}
###############################################################################
#
# _process_jpg()
#
# Extract width and height information from a JPEG file.
#
sub _process_jpg {
my $self = shift;
my $data = $_[0];
my $filename = $_[1];
my $type = 'jpeg';
my $width;
my $height;
my $offset = 2;
my $data_length = length $data;
# Search through the image data to find the 0xFFC0 marker. The height and
# width are contained in the data for that sub element.
while ( $offset < $data_length ) {
my $marker = unpack "n", substr $data, $offset, 2;
my $length = unpack "n", substr $data, $offset + 2, 2;
if ( $marker == 0xFFC0 || $marker == 0xFFC2 ) {
$height = unpack "n", substr $data, $offset + 5, 2;
$width = unpack "n", substr $data, $offset + 7, 2;
last;
}
$offset = $offset + $length + 2;
last if $marker == 0xFFDA;
}
if ( not defined $height ) {
croak "$filename: no size data found in jpeg image.\n";
}
return ( $type, $width, $height );
}
###############################################################################
#
# _get_sheet_index()
#
# Convert a sheet name to its index. Return undef otherwise.
#
sub _get_sheet_index {
my $self = shift;
my $sheetname = shift;
my $sheet_count = @{ $self->{_sheetnames} };
my $sheet_index = undef;
$sheetname =~ s/^'//;
$sheetname =~ s/'$//;
for my $i ( 0 .. $sheet_count - 1 ) {
if ( $sheetname eq $self->{_sheetnames}->[$i] ) {
$sheet_index = $i;
}
}
return $sheet_index;
}
###############################################################################
#
# set_optimization()
#
# Set the speed/memory optimisation level.
#
sub set_optimization {
my $self = shift;
my $level = defined $_[0] ? $_[0] : 1;
croak "set_optimization() must be called before add_worksheet()"
if $self->sheets();
$self->{_optimization} = $level;
}
###############################################################################
#
# Deprecated methods for backwards compatibility.
#
###############################################################################
# No longer required by Excel::Writer::XLSX.
sub compatibility_mode { }
sub set_codepage { }
###############################################################################
#
# XML writing methods.
#
###############################################################################
###############################################################################
#
# _write_workbook()
#
# Write <workbook> element.
#
sub _write_workbook {
my $self = shift;
my $schema = 'http://schemas.openxmlformats.org';
my $xmlns = $schema . '/spreadsheetml/2006/main';
my $xmlns_r = $schema . '/officeDocument/2006/relationships';
my @attributes = (
'xmlns' => $xmlns,
'xmlns:r' => $xmlns_r,
);
$self->xml_start_tag( 'workbook', @attributes );
}
###############################################################################
#
# write_file_version()
#
# Write the <fileVersion> element.
#
sub _write_file_version {
my $self = shift;
my $app_name = 'xl';
my $last_edited = 4;
my $lowest_edited = 4;
my $rup_build = 4505;
my @attributes = (
'appName' => $app_name,
'lastEdited' => $last_edited,
'lowestEdited' => $lowest_edited,
'rupBuild' => $rup_build,
);
if ( $self->{_vba_project} ) {
push @attributes, codeName => '{37E998C4-C9E5-D4B9-71C8-EB1FF731991C}';
}
$self->xml_empty_tag( 'fileVersion', @attributes );
}
###############################################################################
#
# _write_workbook_pr()
#
# Write <workbookPr> element.
#
sub _write_workbook_pr {
my $self = shift;
my $date_1904 = $self->{_1904};
my $show_ink_annotation = 0;
my $auto_compress_pictures = 0;
my $default_theme_version = 124226;
my $codename = $self->{_vba_codename};
my @attributes;
push @attributes, ( 'codeName' => $codename ) if $codename;
push @attributes, ( 'date1904' => 1 ) if $date_1904;
push @attributes, ( 'defaultThemeVersion' => $default_theme_version );
$self->xml_empty_tag( 'workbookPr', @attributes );
}
###############################################################################
#
# _write_book_views()
#
# Write <bookViews> element.
#
sub _write_book_views {
my $self = shift;
$self->xml_start_tag( 'bookViews' );
$self->_write_workbook_view();
$self->xml_end_tag( 'bookViews' );
}
###############################################################################
#
# _write_workbook_view()
#
# Write <workbookView> element.
#
sub _write_workbook_view {
my $self = shift;
my $x_window = $self->{_x_window};
my $y_window = $self->{_y_window};
my $window_width = $self->{_window_width};
my $window_height = $self->{_window_height};
my $tab_ratio = $self->{_tab_ratio};
my $active_tab = $self->{_activesheet};
my $first_sheet = $self->{_firstsheet};
my @attributes = (
'xWindow' => $x_window,
'yWindow' => $y_window,
'windowWidth' => $window_width,
'windowHeight' => $window_height,
);
# Store the tabRatio attribute when it isn't the default.
push @attributes, ( tabRatio => $tab_ratio ) if $tab_ratio != 500;
# Store the firstSheet attribute when it isn't the default.
push @attributes, ( firstSheet => $first_sheet +1 ) if $first_sheet > 0;
# Store the activeTab attribute when it isn't the first sheet.
push @attributes, ( activeTab => $active_tab ) if $active_tab > 0;
$self->xml_empty_tag( 'workbookView', @attributes );
}
###############################################################################
#
# _write_sheets()
#
# Write <sheets> element.
#
sub _write_sheets {
my $self = shift;
my $id_num = 1;
$self->xml_start_tag( 'sheets' );
for my $worksheet ( @{ $self->{_worksheets} } ) {
$self->_write_sheet( $worksheet->{_name}, $id_num++,
$worksheet->{_hidden} );
}
$self->xml_end_tag( 'sheets' );
}
###############################################################################
#
# _write_sheet()
#
# Write <sheet> element.
#
sub _write_sheet {
my $self = shift;
my $name = shift;
my $sheet_id = shift;
my $hidden = shift;
my $r_id = 'rId' . $sheet_id;
my @attributes = (
'name' => $name,
'sheetId' => $sheet_id,
);
push @attributes, ( 'state' => 'hidden' ) if $hidden;
push @attributes, ( 'r:id' => $r_id );
$self->xml_empty_tag( 'sheet', @attributes );
}
###############################################################################
#
# _write_calc_pr()
#
# Write <calcPr> element.
#
sub _write_calc_pr {
my $self = shift;
my $calc_id = 124519;
my $concurrent_calc = 0;
my @attributes = (
'calcId' => $calc_id,
'fullCalcOnLoad' => 1
);
$self->xml_empty_tag( 'calcPr', @attributes );
}
###############################################################################
#
# _write_ext_lst()
#
# Write <extLst> element.
#
sub _write_ext_lst {
my $self = shift;
$self->xml_start_tag( 'extLst' );
$self->_write_ext();
$self->xml_end_tag( 'extLst' );
}
###############################################################################
#
# _write_ext()
#
# Write <ext> element.
#
sub _write_ext {
my $self = shift;
my $xmlns_mx = 'http://schemas.microsoft.com/office/mac/excel/2008/main';
my $uri = 'http://schemas.microsoft.com/office/mac/excel/2008/main';
my @attributes = (
'xmlns:mx' => $xmlns_mx,
'uri' => $uri,
);
$self->xml_start_tag( 'ext', @attributes );
$self->_write_mx_arch_id();
$self->xml_end_tag( 'ext' );
}
###############################################################################
#
# _write_mx_arch_id()
#
# Write <mx:ArchID> element.
#
sub _write_mx_arch_id {
my $self = shift;
my $Flags = 2;
my @attributes = ( 'Flags' => $Flags, );
$self->xml_empty_tag( 'mx:ArchID', @attributes );
}
##############################################################################
#
# _write_defined_names()
#
# Write the <definedNames> element.
#
sub _write_defined_names {
my $self = shift;
return unless @{ $self->{_defined_names} };
$self->xml_start_tag( 'definedNames' );
for my $aref ( @{ $self->{_defined_names} } ) {
$self->_write_defined_name( $aref );
}
$self->xml_end_tag( 'definedNames' );
}
##############################################################################
#
# _write_defined_name()
#
# Write the <definedName> element.
#
sub _write_defined_name {
my $self = shift;
my $data = shift;
my $name = $data->[0];
my $id = $data->[1];
my $range = $data->[2];
my $hidden = $data->[3];
my @attributes = ( 'name' => $name );
push @attributes, ( 'localSheetId' => $id ) if $id != -1;
push @attributes, ( 'hidden' => 1 ) if $hidden;
$self->xml_data_element( 'definedName', $range, @attributes );
}
1;
__END__
=head1 NAME
Workbook - A class for writing Excel Workbooks.
=head1 SYNOPSIS
See the documentation for L<Excel::Writer::XLSX>
=head1 DESCRIPTION
This module is used in conjunction with L<Excel::Writer::XLSX>.
=head1 AUTHOR
John McNamara jmcnamara@cpan.org
=head1 COPYRIGHT
(c) MM-MMXIIII, John McNamara.
All Rights Reserved. This module is free software. It may be used, redistributed and/or modified under the same terms as Perl itself.
|