Spreadsheet :: WriteExcel基于其他单元格值的条件格式

我试图在我的Excel表中添加条件格式。 不幸的是Spreadsheet :: WriteExcel页面上的例子太简单了,我不知道该怎么做。

我想通过RC10单元格值更改行背景颜色。 在Excel中,我将添加格式公式

=IF(RC10="xxxx";1;0) 

我试过在Spreadsheet :: WriteExcel中做这样的事情:

 my $detail_rest_fmt = $excel->add_format(font => "Calibri", size => 11, valign => "vcenter", align => "right", border => 1); $detail_rest_fmt->set_num_format("[Green]=IF(RC10=\"xxxx\";1;0);[Red]=IF(RC10=\"yyyyyy\";1;0)"); 

但没有任何影响。

坏消息是我认为用Spreadsheet :: WriteExcel很难做到这一点。

好消息是可以用Excel :: Writer :: XLSX轻松完成。 这恰好是Spreadsheet :: WriteExcel的一种后裔。 请阅读文章: Spreadsheet :: WriteExcel已经死亡。 万岁的Excel :: Writer :: XLSX

下面的代码完全符合你想要的格式(只能基于单元格A1而不是RC10,当然这个可以改变):

 #!/usr/bin/perl -w use strict; use Excel::Writer::XLSX; my @matrix = ( ['xxxx', '<-- Change the value in cell A1 to change the colour of row 4'], [qw(Redyard Kipling)], [qw(If--)], [qw(If you can keep your head when all about you)], [qw(Are losing theirs and blaming it on you;)], ); writeSpreadsheet('conditional.formatting.xlsx', \@matrix); sub writeSpreadsheet { my ($outFile, $matrix) = @_; my $MIN_COL_WIDTH = 5; my $MAX_COL_WIDTH = 35; my $workbook = Excel::Writer::XLSX->new($outFile); my $worksheet = $workbook->add_worksheet(); my $redFormat = $workbook->add_format(font => 'Arial', color => 'red'); my $greenFormat = $workbook->add_format(font => 'Arial', color => 'green', bold => 1); $worksheet->set_row(0, undef, $workbook->add_format(font => 'Arial', align => 'center', bold => 1)); $worksheet->conditional_formatting('A4:Z4', { type => 'formula', criteria => '=$A$1 = "xxxx"', format => $greenFormat } ); $worksheet->conditional_formatting('A4:Z4', { type => 'formula', criteria => '=$A$1 = "yyyyyy"', format => $redFormat } ); foreach my $row (0 .. $#$matrix) { foreach my $col (0 .. $#{$matrix->[$row]}) { $worksheet->write($row, $col, $matrix->[$row][$col] || ''); } } } 

安东,是对的。 Spreadsheet :: WriteExcel中不支持条件格式。

但是,更新的,API兼容的替代品, Excel :: Writer :: XLSX提供了一组丰富的条件格式化function。

请参阅Excel :: Writer :: XLSX和本示例中更新的条件格式文档。

conditional_formatting的行为很奇怪。 我有这样的事情:

 my $yyy = $excel->add_format(font => "Calibri", size => 11, valign => "vcenter", align => "right", border => 1, border_color => "black", bg_color => $green); for my $section (@sections) { for my $sector (@sectors) { my $xxxx = $excel->add_format(font => "Calibri", size => 11, valign => "vcenter", align => "right", border => 1, border_color => "black", bg_color => $green); $sheet->conditional_formatting("A1", { type => "formula", criteria => '=J4="T1"', format => $yyy }); } } 

当我使用$ yyy它不工作(在Excel中有设置模式填充,而不是backgroud颜色)当我使用$ xxxx它工作正常。 $ yyy和$ xxxx是一样的,那么为什么它不工作?

对于你的第二个问题:

由于范围问题,在使用这些格式之前,可能会遇到格式被垃圾收集的问题。

如果是范围问题,可以在程序的最后添加一个$workbook->close()来查看是否修复了这个问题。

否则,我们需要一个更完整的示例程序来debugging它。