Skip to main content

Perl and Excel: How to Read, Write, Parse Excel Files using Perl

If you want to manipulate excel files programmatically, you can use Perl Spreadsheet module, which provides an object interface that makes it easier to create and parse Excel files.

Install Spreadsheet WriteExcel Module

Method 1: Standard install using make
Download the zipped tar file of Spreadsheet-ParseExcel and Spreadsheet-WriteExcel from cpan.
Untar and unzip the module as follows:
tar -zxvf Spreadsheet-WriteExcel.tar.gz
cd to the directory the tar creates. Execute the steps below to to install the Spreadsheet-WriteExcel module.
perl Makefile.PL
make
make test
make install
Use the above procedure to install Spreadsheet-ParseExcel also.
Method 2: CPAN.pm install
If you have CPAN.pm configured you can install the module as follows:
perl -MCPAN -e 'install "Spreadsheet::WriteExcel"'
perl -MCPAN -e 'install "Spreadsheet::ParseExcel"'
For additional installation help refer to: How To Install Perl Modules Manually and Using CPAN command

Perl Spreadsheet::ParseExcel Module

The Spreadsheet::ParseExcel module can be used to read information from Excel 95-2003 binary files.
The advantage is that Spreadsheet::ParseExcel is compatible with Linux and Windows OS.
The Perl code given below does the following:
  • The new() method is used to create a new Spreadsheet::ParseExcel parser object.
  • The spreadsheet is parsed into a top-level object called $parser.
  • The workbook contains several worksheets; iterate through them by using the workbook worksheets() property.
  • Each worksheet has a MinRow and MinCol and corresponding MaxRow and MaxCol properties, which can be used to figure out the range the worksheet can access.
  • Cells can be obtained from a worksheet through the Cells property;
#!/usr/bin/perl –w

    use strict;
    use Spreadsheet::ParseExcel;

    my $FileName = “/home/selva/Report.xls";
    my $parser   = Spreadsheet::ParseExcel->new();
    my $workbook = $parser->parse($FileName);

    die $parser->error(), ".\n" if ( !defined $workbook );

    # Following block is used to Iterate through all worksheets
    # in the workbook and print the worksheet content 

    for my $worksheet ( $workbook->worksheets() ) {

        # Find out the worksheet ranges
        my ( $row_min, $row_max ) = $worksheet->row_range();
        my ( $col_min, $col_max ) = $worksheet->col_range();

        for my $row ( $row_min .. $row_max ) {
            for my $col ( $col_min .. $col_max ) {

                # Return the cell object at $row and $col
                my $cell = $worksheet->get_cell( $row, $col );
                next unless $cell;

                print "Row, Col    = ($row, $col)\n";
                print "Value       = ", $cell->value(),       "\n";

            }
        }
    }

Perl Spreadsheet::WriteExcel Module

The Spreadsheet::WriteExcel Perl module can be used to create a cross-platform Excel binary file. Multiple worksheets can be added to a workbook and formatting can be applied to cells. Text, numbers, formulas, hyperlinks, images and charts can be written to the cells.
The file produced by this module is compatible with Excel 97-2007 and this module is compatible with Linux, Windows OS.
  • The Perl code given below does the following:
  • A new Excel workbook is created using the new() constructor which accepts $FileName as a parameter.
  • Added the new worksheet named PERL to the workbook
  • The add_format() method can be used to create new Format objects which are used to apply formatting to a cell.
  • The set_column() method is used to change the default properties of a single column or a range of columns. In this code I changed the width of the column to 20.
  • Using Write() method write the data in given row and column.
#!/usr/bin/perl –w
use strict;
use Spreadsheet::WriteExcel;

# Create a new Excel file
my $FileName = “/home/selva/Report.xls";
my $workbook = Spreadsheet::WriteExcel->new($FileName);

# Add a worksheet
my $worksheet1 = $workbook->add_worksheet('PERL’);

# Define the format and add it to the worksheet
my $format = $workbook->add_format(
center_across => 1,
bold => 1,
size => 10,
border => 4,
color => 'black',
bg_color => 'cyan',
border_color => 'black',
align => 'vcenter',
);

# Change width for only first column
$worksheet1->set_column(0,0,20);

# Write a formatted and unformatted string, row and column
# notation.
$worksheet1->write(0,0, "PERL FLAVOURS", $format);
$worksheet1->write(1,0,"Active State PERL");
$worksheet1->write(2,0,"Strawberry PERL");
$worksheet1->write(3,0,"Vennila PERL");
Other than the functions mentioned above, Spreadsheet::WriteExcel has plenty of methods to write Text, numbers, formulas, hyperlinks, images and charts in Excel File.

Comments

Popular posts from this blog

20 perl programming tips

1. List all Installed Perl Modules from Unix Command Line Get a list of all installed perl modules as shown below. $ perl -MFile::Find=find -MFile::Spec::Functions -Tlw -e 'find { wanted => sub { print canonpath $_ if /\.pm\z/ }, no_chdir => 1 }, @INC' /usr/lib/perl5/vendor_perl/5.8.8/i386-linux-thread-multi/HTML/Filter.pm /usr/lib/perl5/vendor_perl/5.8.8/i386-linux-thread-multi/HTML/LinkExtor.pm /usr/lib/perl5/vendor_perl/5.8.8/i386-linux-thread-multi/HTML/PullParser.pm /usr/lib/perl5/vendor_perl/5.8.8/i386-linux-thread-multi/HTML/Parser.pm /usr/lib/perl5/vendor_perl/5.8.8/i386-linux-thread-multi/HTML/TokeParser.pm ..... In the above example, File::Find  and  File::Spec::Functions  module are used to list all installed modules. -M option  loads the module. It executes  use module  before executing the script -T option  enables taint checking, which instructs perl to keep track of data from the user and avoid doing anything insecure w...

How to Connect to MySQL from Perl

How do I connect to a MySQL database from a perl program? use perl DBI module to connect to a MySQL database as explained below. If you don’t have perl DBI and DBD::mysql module installed, install perl module using cpan as we discussed earlier. # perl -MCPAN -e shell cpan> install DBI cpan> install DBD::mysql On a very high level, you’ll have to do the following three steps to connect to a MySQL database and get data. 1. Connect to the MySQL Database In the DBI module, you’ll use the connect function as shown below. $dbc = DBI->connect($source, $username, $password) DBI->connect function takes the following three arguments: $source – This is in the format of “DBI:mysql:[database]:[hostname]”. Replace the [database] and [hostname] with values from your system. In the example shown below, it is connecting to the database called “mycompany” that is running on the localhost. $username – The username that is used to connect to the MySQL database. $pass...