<?xml version="1.0" encoding="windows-1252"?>
<node id="743574" title="xlsmerge - Merge worksheets from different Excel files into one Workbook" created="2009-02-13 04:58:17" updated="2009-02-13 04:58:17">
<type id="1748">
sourcecode</type>
<author id="5348">
Corion</author>
<data>
<field name="doctext">
&lt;code&gt;
#!/usr/bin/perl -w
use strict;
use Spreadsheet::ParseExcel;
use Spreadsheet::WriteExcel;
use File::Glob qw(bsd_glob);
use Getopt::Long;
use POSIX qw(strftime);

GetOptions(
    'output|o=s' =&gt; \my $outfile,
    'strftime|t' =&gt; \my $do_strftime,
) or die;

if ($do_strftime) {
    $outfile = strftime $outfile, localtime;
};

my $output = Spreadsheet::WriteExcel-&gt;new($outfile)
    or die "Couldn't create '$outfile': $!";

for (@ARGV) {
    my ($filename,$sheetname,$targetname);
    my @files;
    if (m!^(.*\.xls):(.*?)(?::([\w ]+))$!) {
        ($filename,$sheetname,$targetname) = ($1,qr($2),$3);
        warn $filename;
        if ($do_strftime) {
            $filename = strftime $filename, localtime;
        };
        @files = glob $filename;
    } else {
        ($filename,$sheetname,$targetname) = ($_,qr(.*),undef);
        if ($do_strftime) {
            $filename = strftime $filename, localtime;
        };
        push @files, glob $filename;
    };

    for my $f (@files) {
        my $excel = Spreadsheet::ParseExcel::Workbook-&gt;Parse($f);
        foreach my $sheet (@{$excel-&gt;{Worksheet}}) {
            if ($sheet-&gt;{Name} !~ /$sheetname/) {
                warn "Skipping '" . $sheet-&gt;{Name} . "' (/$sheetname/)";
                next;
            };
            $targetname ||= $sheet-&gt;{Name};
            #warn sprintf "Copying %s to %s\n", $sheet-&gt;{Name}, $targetname;

            my $s = $output-&gt;add_worksheet($targetname);
            $sheet-&gt;{MaxRow} ||= $sheet-&gt;{MinRow};
            foreach my $row ($sheet-&gt;{MinRow} .. $sheet-&gt;{MaxRow}) {
                my @rowdata = map {
                    $sheet-&gt;{Cells}-&gt;[$row]-&gt;[$_]-&gt;{Val};
                } $sheet-&gt;{MinCol} ..  $sheet-&gt;{MaxCol};
                $s-&gt;write($row,0,\@rowdata);
            }
        }
    };
};

$output-&gt;close;
&lt;/code&gt;</field>
<field name="codedescription">
&lt;p&gt;This script is a raw utility that I use to merge "information" and "data" sheets from different Excel workbooks. The basic syntax is as follows:&lt;/p&gt;
&lt;c&gt;
xlsmerge -s -o results-%Y%m%d.xls info.xls:Information query_results.xls:Sheet1
&lt;/c&gt;
&lt;p&gt;The above command line will create &lt;c&gt;results-20091302.xls&lt;/c&gt; containing a worksheet "Information" and one worksheet "Sheet1" from the respective Excel files. There is no renaming functionality and duplicate sheet names are fatal.&lt;/p&gt;</field>
<field name="codecategory">
Utillity Scripts</field>
<field name="codeauthor">
&lt;c&gt;/msg Corion&lt;/c&gt;</field>
</data>
</node>
