1

Is it possible to use Excel::Writer::XLSX module of perl and create charts with cells containing formulas?

Here is what I am doing:

1) Created an xlsx file with multiple worksheets - no issues

2) Created charts in one worksheet with constant values from other worksheets - no issues

3) Created a worksheet with cells containing formulas - no issues (I can see values in output xlsx)

4) Trying to create a chart from #3, its empty even though I can see the values as I noted above

Please help!!!

jmcnamara
  • 38,196
  • 6
  • 90
  • 108
raj_arni
  • 959
  • 2
  • 15
  • 29

1 Answers1

1

Item 4 should work. Here is an example:

#!/usr/bin/perl

use strict;
use warnings;
use Excel::Writer::XLSX;

my $workbook   = Excel::Writer::XLSX->new( 'chart_column.xlsx' );
my $worksheet1 = $workbook->add_worksheet();
my $worksheet2 = $workbook->add_worksheet();
my $bold       = $workbook->add_format( bold => 1 );

# Add the worksheet data that the charts will refer to.
my $headings = [ 'Number', 'Batch 1', 'Batch 2' ];
my $data = [
    [ 2,  3,  4,  5,  6,  7 ],
    [ 10, 40, 50, 20, 10, 50 ],
    [ 30, 60, 70, 50, 40, 30 ],
];

# Add the data to worksheet2.
$worksheet2->write( 'A1', $headings, $bold );
$worksheet2->write( 'A2', $data );


# Add formulas in worksheet1 to refer to the data in worksheet2.
for my $row (1 .. 7) {
    $worksheet1->write( $row -1, 0, '=Sheet2!A' . $row );
    $worksheet1->write( $row -1, 1, '=Sheet2!B' . $row );
    $worksheet1->write( $row -1, 2, '=Sheet2!C' . $row );
}


# Create a new chart object. In this case an embedded chart.
my $chart = $workbook->add_chart( type => 'column', embedded => 1 );

# Configure the series.
$chart->add_series(
    name       => '=Sheet1!$B$1',
    categories => '=Sheet1!$A$2:$A$7',
    values     => '=Sheet1!$B$2:$B$7',
);
$chart->add_series(
    name       => '=Sheet1!$C$1',
    categories => '=Sheet1!$A$2:$A$7',
    values     => '=Sheet1!$C$2:$C$7',
);

# Insert the chart into the worksheet (with an offset).
$worksheet1->insert_chart( 'D2', $chart, 25, 10 );

$workbook->close();

__END__

And here is the output:

enter image description here

So it looks like it works in Excel. However, it is possible that it won't work with some spreadsheet applications that don't calculate the results of formulas.

jmcnamara
  • 38,196
  • 6
  • 90
  • 108