jjap
jjap

Reputation: 189

Excel::Writer::XLSX cells (with date and time) need to be refreshed

I can successfully create xlsx from the results of a DBI query with the Excel::Writer::XLSX package.

The only trouble is the date and time cells, when opened in Excel 2010, need to be refreshed i.e. F2 <enter> to display properly.

Example displayed: 2012-12-02 17:48:33.000 when spreadsheet is opened

Once refreshed : 02/12/2012 17:49 desired format after F2 <enter>

I would be grateful for any hints/guidance on what could cause this and if this issue can be resolved within my Perl script?

Many thanks...

PS Automatic calculations are enabled, StrawberryPerl 5.16 on Win 7

UPDATE: For the sake of completeness and as it may be of help to others: I was using the following construct to write records from a query which could be plain strings or datetime.

If one muff's either the regex capturing the date, or the sprintf to put it in the proper format string required by the write_excel_date method, a plain string is written to the cell. That was my problem.

if ( $item =~ qr[(\d{4})-(\d{2})-(\d{2})\s(\d{2}):(\d{2}):(\d{2})\.000] ) {
    my $date = sprintf "%4d-%02d-%02dT%02d:%02d:%02d", $1, $2, $3, $4, $5, $6;
    $worksheet->write_date_time( $row, $col++, $date, $date_format);
}
else {
    $worksheet->write( $row, $col++, $item );
}

Upvotes: 2

Views: 3097

Answers (2)

jmcnamara
jmcnamara

Reputation: 41584

If you write the dates using the Worksheet write_date_time() method then you shouldn't have to refresh them in Excel since they are just formatted numbers and don't require re-cacluation.

If however, you are writing the dates as strings then you would need to do something in Excel to convert them to dates. You shouldn't need to do that though since Excel::Writer::XLSX provides a dedicated method for writing dates:

#!/usr/bin/perl

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

my $workbook    = Excel::Writer::XLSX->new( 'date_example.xlsx' );
my $worksheet   = $workbook->add_worksheet();
my $date_format = $workbook->add_format( num_format => 'dd/mm/yyyy hh:mm' );

# Increase the column width to make the output clearer.
$worksheet->set_column( 'A:A', 20 );

# Write the date.
$worksheet->write_date_time( 'A1', '2012-12-02T17:48:33.000', $date_format );

__END__

enter image description here

See the Dates and Times section of the Excel::Writer::XLSX documentation for a detailed explanation of how to deal with dates.

Upvotes: 3

nullrevolution
nullrevolution

Reputation: 4137

what about adding a line of VBA code to the Workbook_Open() event?

Private Sub Workbook_Open()

  Application.Calculate

End Sub

would that meet your needs?

Upvotes: 0

Related Questions